21

PHPでAPIを構築しています。メソッドの1つは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); 

サーバーコード

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
        ...
    }
}

解決

送信

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

受け取る

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

1 に答える 1

11

http://php.net/manual/en/features.file-upload.put-method.phpを読みましたか?Script PUT /put.phpすべて設定しましたか?

また、$imageファイル名ではなく、ファイルハンドラーである必要があります。

追伸 を使用file_get_contentsすると、サーバー上のPUTがメモリに読み込まれようとします。良い考えではありません。リンクされたマニュアルページを参照してください。

于 2011-05-21T10:44:20.527 に答える