使用 cURL 发布文件不适用于路径开头的 @



所以我尝试使用 cURL 和其他 POST 变量将文件发送到另一个页面。除了文件发送外,大部分工作都有效。但它仅在我的本地主机上不起作用。当它上传到托管的 Web 服务器时,它会完全按照应有的方式工作。

我也不想使用 CURLFile,因为 Web 服务器不支持它。

这是代码:

        // 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);

提前感谢!

很可能您的网络服务器运行的是支持"@"的旧版本 - 但不支持 curlfile。您的本地计算机支持 curlfile - 但不支持"@"(默认配置)...

您可以使用

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']
            );
}

建议这样做,因为@-way被认为是不安全的,因此请使用CurlFile,如果可用。

但是,要使@方式也能正常工作,您可以使用

curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

这默认为 PHP 5.5 之前的false,但默认为 true 更高版本。

注意,玩"订单"。CURLOPT_POSTFIELDS对现有选项有些敏感似乎存在问题。所以

curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

可能不起作用,而

curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);

可能。

最新更新