使用php://input接收手机图片上传二进制流

最近的工作中要用到手机上传图片到PHP服务端,一般会有两种方式来实现,一种是让手机客户端模拟HTTP POST方式,还有一种就是用二进制流方式。

最后决定用二进制方式来接收图片的上传。

1.客户端模拟图片上传程序(test.php):

<?php
$data=file_get_contents('1.png');
$http_entity_body = $data;
$http_entity_type = 'application/x-www-form-urlencoded';
$http_entity_length = strlen($http_entity_body);
$host = '127.0.0.1';
$port = 80;
$path = '/upload.php';
$fp = fsockopen($host, $port, $error_no, $error_desc, 30);
if ($fp) {
  fputs($fp, "POST {$path} HTTP/1.1\r\n");
  fputs($fp, "Host: {$host}\r\n");
  fputs($fp, "Content-Type: {$http_entity_type}\r\n");
  fputs($fp, "Content-Length: {$http_entity_length}\r\n");
  fputs($fp, "Connection: close\r\n\r\n");
  fputs($fp, $http_entity_body . "\r\n\r\n");
 
  while (!feof($fp)) {
    $d .= fgets($fp, 4096);
  }
  fclose($fp);
  echo $d;
}
?>

2.服务端接收程序(upload.php):

<?php
error_reporting(E_ALL);
function get_contents() { 
  $xmlstr = file_get_contents('php://input')?file_get_contents('php://input') : gzuncompress($GLOBALS['HTTP_RAW_POST_DATA']);//得到post过来的二进制原始数据
  $filename=time().'.png';
  if(file_put_contents($filename,$xmlstr)){
 echo 'success';
  }else{
 echo 'failed';
  }
}
get_contents();
?>

执行test.php,看看你的根目录是不是有新的图片了!

众所周知,通过二进制方式的不能够通过get,post方式拿到参数,那怎么进行参数的传递呢?

答案就是让客户端把二进制进行一个分割组拼即可,服务端只需要把拿到的二进制字符串进行分隔就可以得到了。

3户端模拟图片上传程序(test2php):

<?php
$data=file_get_contents('1.png');
$data = 'www.4jcms.com[x]四季企业网站系统[]'.$data;//假设服务端需要额外的两个参数,URL以及站名,我们用“[x]”进行组合,服务端也用这个进行拆分
$http_entity_body = $data;
$http_entity_type = 'application/x-www-form-urlencoded';
$http_entity_length = strlen($http_entity_body);
$host = '127.0.0.1';
$port = 80;
$path = '/upload2php';
$fp = fsockopen($host, $port, $error_no, $error_desc, 30);
if ($fp) {
  fputs($fp, "POST {$path} HTTP/1.1\r\n");
  fputs($fp, "Host: {$host}\r\n");
  fputs($fp, "Content-Type: {$http_entity_type}\r\n");
  fputs($fp, "Content-Length: {$http_entity_length}\r\n");
  fputs($fp, "Connection: close\r\n\r\n");
  fputs($fp, $http_entity_body . "\r\n\r\n");
 
  while (!feof($fp)) {
    $d .= fgets($fp, 4096);
  }
  fclose($fp);
  echo $d;
}
?>

4服务端接收程序(upload2php):

<?php
error_reporting(E_ALL);
function get_contents() { 
  $xmlstr = file_get_contents('php://input')?file_get_contents('php://input') : gzuncompress($GLOBALS['HTTP_RAW_POST_DATA']);//得到post过来的二进制原始数据
  $arr = explode("[x]",$data,3);
  $url = $arr[0];  //网址参数
  $sitename = $arr[1];  //站名参数
  $data = $arr[2];  //图片二进制字符串
  $filename=time().'.png';
  if(file_put_contents($filename,$data)){
 echo 'success';
  }else{
 echo 'failed';
  }
}
get_contents();
?>

运行test2.php看看,是不是就得到你想要的结果了呢。

猜你喜欢

转载自wangking717.iteye.com/blog/2279237