Skip to content
Advertisement

Upload file using Curl and receive them in Laravel method

I have been trying to upload file to using curl using laravel app end point.

Below code is on separate server.

$header = $this->getCurlHeader();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$this->url);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
// curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);   
$cfile = new CURLFile($this->filePath . $this->csvFile,  'text/csv','text.csv');
//print_r($cfile);exit;
$postData = array('csv' => $cfile);         
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);                    
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$response = curl_exec($ch);
$hhtpCode = curl_getinfo($ch);
curl_close($ch);
//$this->dbg($hhtpCode);
$this->dbg(json_decode($response,1),1);

And receiving end in laravel app hosted on different server.

public function insert(Request $request, $feed=''){
     //return response()->json(var_dump($request->all()));
     //return response()->json("here in insert");
     return response()->json($_FILES);
     echo "here";
     dd($_FILES);
}

It returns me empty response. I am able to verify curl request using headers.

Any suggestion will be helpful. Thanks.

Advertisement

Answer

You can try something like this on the source server instead:

$target_url = 'https://mywebsite.com'; // Write your URL here
$dir = '/var/www/html/storage/test.zip'; // full directory of the file

$cFile = curl_file_create($dir);
$post = array('file'=> $cFile); // Parameter to be sent

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=json_decode(curl_exec($ch));
curl_close ($ch);

From the destination server, print the request sent.

public function insert(Request $request){
    dd($request->file);
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement