put上传接口数据php,php – 使用API​​ PUT请求上传文件

我正在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);

服务器代码

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值