首页  >  文章  >  后端开发  >  php如何发送与接收流文件

php如何发送与接收流文件

*文
*文原创
2017-12-25 15:16:232822浏览

php如何发送与接收流文件?本文主要介绍了php发送与接收流文件的方法,实例分析了php针对流文件的常见操作技巧。希望对大家有所帮助。

sendStreamFile.php 把文件以流的形式发送
receiveStreamFile.php 接收流文件并保存到本地

sendStreamFile.php文件:


<?php 
/** php 发送流文件 
* @param String $url 接收的路径 
* @param String $file 要发送的文件 
* @return boolean 
*/ 
function sendStreamFile($url, $file){ 
  if(file_exists($file)){ 
    $opts = array( 
      &#39;http&#39; => array( 
        &#39;method&#39; => &#39;POST&#39;, 
        &#39;header&#39; => &#39;content-type:application/x-www-form-urlencoded&#39;, 
        &#39;content&#39; => file_get_contents($file) 
      ) 
    ); 
    $context = stream_context_create($opts); 
    $response = file_get_contents($url, false, $context); 
    $ret = json_decode($response, true); 
    return $ret[&#39;success&#39;]; 
  }else{ 
    return false; 
  } 
} 
$ret = sendStreamFile(&#39;http://localhost/receiveStreamFile.php&#39;,&#39;send.txt&#39;);
var_dump($ret); 
?>


receiveStreamFile.php文件:


]<?php 
/** php 接收流文件 
* @param String $file 接收后保存的文件名 
* @return boolean 
*/ 
function receiveStreamFile($receiveFile){ 
  $streamData = isset($GLOBALS[&#39;HTTP_RAW_POST_DATA&#39;])? $GLOBALS[&#39;HTTP_RAW_POST_DATA&#39;] : &#39;&#39;; 
 
  if(empty($streamData)){ 
    $streamData = file_get_contents(&#39;php://input&#39;); 
  } 
 
  if($streamData!=&#39;&#39;){ 
    $ret = file_put_contents($receiveFile, $streamData, true);
  }else{ 
    $ret = false; 
  } 
  return $ret; 
} 
$receiveFile = &#39;receive.txt&#39;; 
$ret = receiveStreamFile($receiveFile); 
echo json_encode(array(&#39;success&#39;=>(bool)$ret)); 
?>


下面是其它网友的补充

PHP读取流文件


$filepath = &#39;http://www.vip.com/down&#39;;
$fp = fopen($filepath,"r");
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Content-Disposition: attachment; filename=xxx.pdf");
$buffer = 1024;
while (!feof($fp)) {
$file_con = fread($fp,$buffer);
  echo $file_con;
}
fclose($fp);

相关推荐:

php 文件上传的原理简单介绍

php 文件分割与合并(断点续传)

php 文件读取系列方法详解

以上是php如何发送与接收流文件的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn