Upload a file using php curl into the backendless files storage

I am trying to upload a file(it could be image or a document) into the ‘backendless files’ through a php form.

I have created a new folder in the backendless files(root) in the name of ‘Uploads’ where i want all the uploaded files to be saved.

I have a basic code through which i am unable to upload the file and i need some help.

Backendless Version v5.2.14

Client SDK (REST)

Application ID :30BB5E5E-6AE8-53E0-FFE4-87303ACE0300

Expected Behavior

  1. I want the form to display a window where i have to upload the file which i want to be saved into the backendless files. (done)
  2. I want a new folder to be created in the name of the person uploading the file,which will be in the ‘Uploads’ folder.
  3. the new file should go in that new folder.

Actual Behavior

  1. For now it doesn’t give any error and also doesn’t upload the file, its like a dead form.

Reproducible Test Case

<?php

	//get the incident id from the url and if its missing throw an error	
	if( !isset($_GET['incident']) && !isset($_POST['incident']) )
		{
			echo "<script> alert('Incident id is missing.'); window.location.href = '#'; </script>";  
		}
	//set the incident id to $id 			
	if( isset($_GET['incident']) )
		{
				// $id = hexdec($_GET['incident']) ^ 42; 
			$ID = $_GET['incident'];  //to test form without xor 
		}	

	// //Check if incident id is present in the Incident table 		    
	// 	 $user_info = $wpdb->get_row("SELECT * FROM Incident WHERE IncidentID = {$id} ");

	//retrieve the data from the backendless table and check if the incident id is present in it
	$service_url1 = 'https://api.backendless.com/30BB5E5E-6AE8-53E0-FFE4-87303ACE0300/<REST-API>/data/Incident';
	$curl1 = curl_init($service_url1);
	curl_setopt($curl1, CURLOPT_RETURNTRANSFER, true);
	$curl_response1 = curl_exec($curl1);
	if ($curl_response1 === false) {
	    $info1 = curl_getinfo($curl1);
	    curl_close($curl1);
	    die('error occured during curl exec. Additioanl info: ' . var_export($info1));
	}
	curl_close($curl1);
	//getting the array which is stored in $curl_response1, putting it in decoded and pulling out only the incident id field and arranging it properly.
	$decoded = json_decode($curl_response1);
	$res1 = array_column($decoded, 'IncidentID');
	$res2 = implode("', '", $res1);

	// //displaying the results for learning purpose 
	//  	echo "<br>res2 = ".$res2;
	//  	echo "<br>ID  = ".$ID ;	
	//  	echo "<br>res1 = ".$res1." : ";
	//  	print_r($res1); 

	//checking if the incident id is present in the array(res1)
	if (!in_array($ID, $res1)) 
		{
			echo "<script> alert('Incident id not found.'); window.location.href = '#'; </script>";	
		}		
		

$errmsg = '';
if (isset($_POST['Submit']))
{
	$filename = $_FILES['uploadoc']['name'];
    $filedata = $_FILES['uploadoc']['tmp_name'];
    $filesize = $_FILES['uploadoc']['size'];
    $filetype = $_FILES['uploadoc']['type'];
	
    $url = "https://api.backendless.com/30BB5E5E-6AE8-53E0-FFE4-87303ACE0300/v5.2.14/files/Uploads".$filename;// e.g. http://localhost/myuploader/upload.php // request URL
    
    if ($filedata != '')
    {
        $headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
        $postfields = array("filedata" => $filedata, "filename" => $filename);
        $ch = curl_init();
        $options = array(
            CURLOPT_URL => $url,
            CURLOPT_HEADER => true,
            CURLOPT_POST => 1,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POSTFIELDS => $postfields,
            CURLOPT_INFILESIZE => $filesize,
            CURLOPT_RETURNTRANSFER => true
        ); // cURL options
        curl_setopt_array($ch, $options);
        curl_exec($ch);
        if(!curl_errno($ch))
        {
            $info = curl_getinfo($ch);
            if ($info['http_code'] == 200)
                $errmsg = "File uploaded successfully";
        }
        else
        {
            $errmsg = curl_error($ch);
        }
        curl_close($ch);
    }
    else
    {
        $errmsg = "Please select the file";
    }
}
			
?>

<html>
<head>
	<style>
		.upload-doc-submit{margin-top: 20px;}
	</style>
</head>
<body style="text-align:left;" onload="StartTimers();" onclick="ResetTimers();">
<div>
	<form method="post" id="upload-doc" onsubmit="return validate();" enctype="multipart/form-data">
	
		<table>
			<tr>
				<div class="col-sm-12 col-xs-12">
					<span class="wpcf7-form-control-wrap uploadoc">
						<td>
							<label>Upload Document : </label>
							<input type="file" name="uploadoc" class="wpcf7-form-control wpcf7-file wpcf7-validates-as-required" accept=".docx,.jpg,.doc" aria-required="true" aria-invalid="false" required="">
						</td>
					</span>
				</div>  
			</tr>	

			<tr>
				<div class="col-sm-12 col-xs-12">
						<td align="center" valign="middle">
							<input type="hidden" name="incident" value="$id">
							<input  type="submit" id="btnSubmit"  value="Submit" name="Submit" class="wpcf7-form-control wpcf7-submit upload-doc-submit center">
						</td>
					</span>
				</div>  
			</tr>
		</table> 

    </form>
</div>
</body>
</html>

<script>
	jQuery(document).ready(  function()
	{
		jQuery("#userregistration").validate
			({
		    	ignore: ":hidden",
		    	rules: 
		    		{
		            	uploadoc: 
		            		{
		                		required : true
		                	}		

		        	},
		   		messages: 
		    		{
		           		uploadoc: 
		                	{   
		                		required : "Please choose a file." 
		                	}		
		    		},
			});
		
	});
</script>

<?php

if (isset($_POST['Submit']))
	{
		echo " <br />  <br />  <div style='text-align:center'>or</div>";
		echo '<br />  <br />  <th><strong><u><center><a  style="color:#2c666d" target="_blank" href="javascript:window.close();">Click here to return.</a></center></u></th>';
	}	

?>

Hello @Shaurya_Kane

Try change

$url = "https://api.backendless.com/30BB5E5E-6AE8-53E0-FFE4-87303ACE0300/v5.2.14/files/Uploads".$filename;

to

$url = "https://api.backendless.com/30BB5E5E-6AE8-53E0-FFE4-87303ACE0300/<Rest-api-key>/files/Uploads/".$filename;

Hello @Volodymyr_Ialovyi
It still doesnt upload the file :frowning:

  1. I create file on my computer - /home/vova/Desktop/1.txt
  2. I executed the command:
curl -H Content-Type:"multipart/form-data" --form upload=@/home/vova/Desktop/1.txt -X POST -v http://api.backendless.com/<App-id>/<Rest-api-key>/files/Uploads/1.txt
  1. Went to the console - Files - click “Uploads” directory - I see new file with name “1.txt”

Unfortunately, I do not know much about php, I did not find exactly which file you are trying to upload.

Try to follow the 3 steps that I described to make sure you can upload the file using the REST request.

I understand that what you are doing is through the backendless console only. but here im trying to upload through the code into the backendless files.

@Volodymyr_Ialovyi
where exactly do i execute the command in backendless ??

Do you mean how to execute the command

curl -H Content-Type:"multipart/form-data" --form upload=@/home/vova/Desktop/1.txt -X POST -v http://api.backendless.com/<App-id>/<Rest-api-key>/files/Uploads/1.txt

?
If yes then in the terminal

1 Like

Yes i meant the same…
Where can i find the terminal ? in the files option only or some where else?

Where can i find the terminal ? in the files option only or some where else?

What operating system are you using?

@Volodymyr_Ialovyi
Windows 10

Terminal -
https://www.isunshare.com/windows-10/4-ways-to-open-command-prompt-in-windows-10.html
Having executed the command in the terminal, you will verify that this operation is working and the server is working correctly.

Then you will need to transform this request for php, example - https://stackoverflow.com/questions/5647461/how-do-i-send-a-post-request-with-php

@Volodymyr_Ialovyi
I did as you said in cmd…
got the following result:
“C:>curl -H Content-Type:“multipart/form-data” --form upload=@/C:/Users/shaurya/Downloads/373410.jpg -X POST -v http://api.backendless.com/< App-id >/< Rest-api-key >/files/Uploads/373410.jpg
‘curl’ is not recognized as an internal or external command,
operable program or batch file.”

ps: ofcouse in < App-id > / < Rest-api-key >: i had put the keys .

Try - https://www.thewindowsclub.com/how-to-install-curl-on-windows-10