使用API​​ PUT请求上传文件

fes*_*sja 20 php upload curl put request

我正在用PHP构建API.其中一种方法是place.new(PUT请求).它需要几个字符串字段,它还需要一个图像.但是我无法让它发挥作用.使用POST请求很简单,但我不知道如何使用PUT以及如何在服务器上获取数据.

谢谢您的帮助!

测试CURL代码

$curl = curl_init();
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $this->url);

curl_setopt($curl, CURLOPT_PUT, 1);
curl_setopt($curl, CURLOPT_INFILE, $image);
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($image));

$this->result = curl_exec($curl);
curl_close($curl); 
Run Code Online (Sandbox Code Playgroud)

服务器代码

if ( $im_s = file_get_contents('php://input') )
{
    $image = imagecreatefromstring($im_s);

    if ( $image != '' )
    {
        $filename = sha1($title.rand(11111, 99999)).'.jpg';
        $photo_url = $temp_dir . $filename;
        imagejpeg($image, $photo_url);

        // upload image
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

发送

// Correct: /Users/john/Sites/....
// Incorrect: http://localhost/...
$image = fopen($file_on_dir_not_url, "rb");

$curl = curl_init();
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $url);

curl_setopt($curl, CURLOPT_PUT, 1);
curl_setopt($curl, CURLOPT_INFILE, $image);
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($file_on_dir_not_url));

$result = curl_exec($curl);
curl_close($curl); 
Run Code Online (Sandbox Code Playgroud)

接收

/* Added to clarify, per comments */
$putdata = fopen("php://input", "r");

/* Open a file for writing */
$fp = fopen($photo_url, "w");

/* Read the data 1 KB at a time
    and write to the file */
while ($data = fread($putdata, 1024))
{
    fwrite($fp, $data);
}

/* Close the streams */
fclose($fp);
fclose($putdata);
Run Code Online (Sandbox Code Playgroud)

chx*_*chx 11

你读过http://php.net/manual/en/features.file-upload.put-method.php吗?Script PUT /put.php全部设置?

另外,$image它是什么- 它需要是文件处理程序,而不是文件名.

PS.使用file_get_contents将尝试将服务器上的任何PUT加载到内存中.不是个好主意.请参阅链接的手册页.