I'm trying to do a CURL PUT with a file but I'm having issues.
Here is my code:
$url_path_str = 'http://my_url';
$file_path_str = '/my_file_path';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ''.$url_path_str.'');
curl_setopt($ch, CURLOPT_PUT, 1);
$fh_res = fopen($file_path_str, 'r');
$file_data_str = fread($fh_res, filesize($file_path_str));
curl_setopt($ch, CURLOPT_INFILE, $fh_res);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file_path_str));
fclose($fh_res);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curl_response_res = curl_exec ($ch);
The script keeps timing out and I'm not sure why.
I'd appreciate some assistance. Thanks.
I figured this out. It happened to be fclose that was causing the issue. I simply put it after curl_exec.
Here's the amended code:
$url_path_str = 'http://my_url';
$file_path_str = '/my_file_path';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ''.$url_path_str.'');
curl_setopt($ch, CURLOPT_PUT, 1);
$fh_res = fopen($file_path_str, 'r');
curl_setopt($ch, CURLOPT_INFILE, $fh_res);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file_path_str));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curl_response_res = curl_exec ($ch);
fclose($fh_res);
Hope this is helpful to someone else later.
Cheers.
I'm not 100% sure this is the problem, but the only one I can see is that you are reading the contents of the file with fread()
when you don't need to, and are not doing anything with the data. This will leave the pointer at the end of the file, and cURL will be waiting for data from the pointer that it will never get.
Remove this line and see if your still have the problem:
$file_data_str = fread($fh_res, filesize($file_path_str));
Alternatively, if you do actually need the data from the file and are using the $file_data_str
variable later in the script, place this line immediately after the one mentioned above:
rewind($fh_res);
EDIT
Also, I'm not sure about this at all: ''.$url_path_str.''
- you should just be able to do this $url_path_str
and it will have the same effect but be (slightly) more resource-efficient.
If you are absolutely sure that the connection is being timed out and nothing else.. then you can add the following lines of code-
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1000);
curl_setopt($ch, CURLOPT_TIMEOUT, 10000 );