how can i upload a file using PHP
box-api, php
Solution
I don't think POST form data can accept file handler created using `fopen("D:\code\php\bcs\test.data", "r");`
Try accessing file handler by using @ instead . Btw, change \ to / so you don't accidentally put some character as escape character : `$u_file = "@D:/code/php/bcs/test.data";`
You shouldn't `json_encode` the content, what if your file content is not text (says, an image/binary file) .
I think this line gives you problem too. Tried my code with this option, threw me a weird "441 Required length" error . My code works fine without this option : `curl_setopt($ch, CURLOPT_UPLOAD, true);`
Finally, here is my working code :
<?php
public function upload_file()
{
$url = 'https://api.box.com/2.0/files/content';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_ENCODING, "UTF-8");
//this is my method to construct the Authorisation header
$header_details = array($this->default_authen_header());
curl_setopt($ch, CURLOPT_HTTPHEADER, $header_details);
$post_vars = array();
$post_vars['filename'] = "@C:/tmp_touch.txt";
$post_vars['folder_id'] = 0;
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_vars);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
?>
Problem
On this page: `http://developers.box.com/docs/` Upload a file using cURL: ``` METHOD POST /files/content EXAMPLE REQUEST curl https://api.box.com/2.0/files/content \ -H "Authorization: BoxAuth api_key=API_KEY&auth_token=AUTH_TOKEN" \ -F filename1=@FILE_NAME1 \ -F filename2=@FILE_NAME2 \ -F folder_id=FOLDER_ID ``` But Now, I want to upload a file using php, how could I do it? my code: ``` <?php $params = array(); $params['folder_id'] = '485272014'; $u_file = fopen("D:\code\php\bcs\test.data", "r"); $params['filename1'] = $u_file; $params = json_encode($params); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://api.box.com/2.0/files/content"); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); curl_setopt($ch, CURLOPT_UPLOAD, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: BoxAuth api_key=API_KEY&auth_token=TOKEN")); $result = curl_exec($ch); curl_close($ch); print_r($result); fclose($u_file); ?> ``` it didn't work, and I run the script using: `php -f test.php`