Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I upload a file that has spaces is its name with curl + php?

Tags:

php

curl

I'm using this code for uploading a file to my server, using HTTP POST:

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
$post = array(
    "upload" => '@' . $filepath
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$curl_result = curl_exec($ch);

This code works when $filepath does not contain spaces. However, it is possible that it might. When I test a path with spaces, I get the curl error "failed creating formpost data".

The curl manual does not tell me what to do, all it gives me are unix filenames without spaces. I tried following http://curl.haxx.se/mail/archive-2006-01/0079.html like so, but it didn't help me either:

"upload" => '"@' . $filepath . '"'
"upload" => '@"' . $filepath . '"'

Anyone have an idea?

like image 616
Tominator Avatar asked Apr 14 '11 11:04

Tominator


1 Answers

Current versions of cURL (and PHP-cURL) handle spaces in filenames with no problems. Older versions may have had bugs, I'm not sure. Check you're using reasonably recent versions.

I can confirm spaces in filenames are no problem at all under PHP 5.2.13 and libcurl/7.19.4 on Linux.

The error message you're getting is the same one as when PHP/cURL can't find a file. Odds are the problems are somewhere else in your code. Probably an issue of having under- or over-escaped the spaces in the filename but probably not an issue with cURL itself.

I'd suggest looking elsewhere in your code for the problem or producing a hard-coded example of the problem occurring (where $filename is being set in the PHP directly rather than read from elsewhere).

like image 186
ADW Avatar answered Nov 03 '22 11:11

ADW