5

I'm sure this question has been asked many times, but I can't figure out why my php script is not working. I have a CSV file that I know it works flawlessly when I upload it using the following command line curl:

curl -H 'Content-Type: text/csv' --data-binary @/Users/johndoe/Downloads/payables.csv -H "Authorization: Bearer [some_token_key]" 'https://example.com/api/v1/imports.json'

And here's my php script when I tried to translate this command into PHP Curl:

$file = "/Users/johndoe/Downloads/payables.csv";
$authorization = "Authorization: Bearer [some_token_key]";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://example.org/api/v1/imports.json");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, [$authorization, 'Content-Type: text/csv']);
$cfile = new CurlFile($file,  'text/csv');
$data = array('data-binary' => realpath($cfile));
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($curl);
curl_close($curl);

Does anyone see what's wrong with my PHP script? I'm using php 5.5, and the error that I see on the receiving site that tries to process the CSV file is that it can't find the the CSV import headers. This doesn't make any sense. Any ideas?

2
  • I think your php script was not able to read file from /Users/johndoe/Downloads/payables.csv , put it in root directory i.e where your php script resides and try Commented May 25, 2017 at 6:56
  • @sumit that didn't work. I placed the file in the root directory of my application and nothing. Same error. Commented May 25, 2017 at 7:22

1 Answer 1

3

Instead of trying to access your download folder upload the files in your project directory then pass it into the curl.

move_uploaded_file($_FILES['file']['tmp_name'], __DIR__.'/uploads/'. $_FILES["image"]['name']);

$file = "uploads/payables.csv";
$authorization = "Authorization: Bearer [some_token_key]";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://example.org/api/v1/imports.json");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, [$authorization, 'Content-Type: text/csv']);
$cfile = new CurlFile($file,  'text/csv');
//curl file itself return the realpath with prefix of @
$data = array('data-binary' => $cfile);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($curl);
curl_close($curl);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.