使用cURL发布文件对路径开头的@不起作用
So I'm trying to send files to another page using cURL, along with other POST variables. Most of it works, except the file sending. But it only doesn't work on my localhost. When it's uploaded to the hosted web server, it works exactly like it should.
I also don't want to use CURLFile because the web server doesn't support it.
Here is the code:
// Output the image
imagejpeg($fileData['imageBackground'], $newFileName, 75);
// Get Old Background
$query['getBackground'] = $this->PDO->prepare("SELECT backgroundImage FROM accounts WHERE token = :token");
$query['getBackground']->execute(array(':token' => $token));
$queryData = $query['getBackground']->fetch(PDO::FETCH_ASSOC);
$verificationKey = self::newVerificationKey($token);
// Send the file to the remote
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uploadURL);
curl_setopt($ch, CURLOPT_POST, true);
$postArgs = array(
'action' => 'updateBackground',
'verificationKey' => $verificationKey,
'file' => '@' . realpath($newFileName),
'oldBackground' => $queryData['backgroundImage']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
unlink($newFileName);
Thanks in advance!
Most likely your webserver is running an older version which supports the "@" - but not curlfile. Your local machine supports curlfile - but not the "@" (in the default configuration)...
You can use
if (class_exists("CurlFile")){
$postArgs = array(
'action' => 'updateBackground',
'verificationKey' => $verificationKey,
'file' => new CurlFile($newFileName),
'oldBackground' => $queryData['backgroundImage']
);
}else{
$postArgs = array(
'action' => 'updateBackground',
'verificationKey' => $verificationKey,
'file' => '@' . realpath($newFileName),
'oldBackground' => $queryData['backgroundImage']
);
}
which is recommended, because the @
-way is considered unsafe, so use CurlFile
, when available.
However, to have the @
-way working lokaly as well, you can use
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
This defaulted to false
prior to PHP 5.5, but defaults to true
for later versions.
Note, play arround with the "order". There seems to be an issue with CURLOPT_POSTFIELDS
beeing somewhat sensitive to existing options. So
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
might not work, while
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
might.