php 发送与接收流文件

来源:互联网 发布:我友网络 编辑:程序博客网 时间:2024/05/26 12:06

php 发送与接收流文件


sendStreamFile.php 把文件以流的形式发送

receiveStreamFile.php 接收流文件并保存到本地


sendStreamFile.php

[php] view plain copy
  1. <?php  
  2. /** php 发送流文件 
  3. * @param  String  $url  接收的路径 
  4. * @param  String  $file 要发送的文件 
  5. * @return boolean 
  6. */  
  7. function sendStreamFile($url$file){  
  8.   
  9.     if(file_exists($file)){  
  10.   
  11.         $opts = array(  
  12.             'http' => array(  
  13.                 'method' => 'POST',  
  14.                 'header' => 'content-type:application/x-www-form-urlencoded',  
  15.                 'content' => file_get_contents($file)  
  16.             )  
  17.         );  
  18.   
  19.         $context = stream_context_create($opts);  
  20.         $response = file_get_contents($url, false, $context);  
  21.         $ret = json_decode($response, true);  
  22.         return $ret['success'];  
  23.   
  24.     }else{  
  25.         return false;  
  26.     }  
  27.   
  28. }  
  29.   
  30. $ret = sendStreamFile('http://localhost/fdipzone/receiveStreamFile.php''send.txt');  
  31. var_dump($ret);  
  32. ?>  

receiveStreamFile.php

[php] view plain copy
  1. <?php  
  2. /** php 接收流文件 
  3. * @param  String  $file 接收后保存的文件名 
  4. * @return boolean 
  5. */  
  6. function receiveStreamFile($receiveFile){  
  7.   
  8.     $streamData = isset($GLOBALS['HTTP_RAW_POST_DATA'])? $GLOBALS['HTTP_RAW_POST_DATA'] : '';  
  9.   
  10.     if(empty($streamData)){  
  11.         $streamData = file_get_contents('php://input');  
  12.     }  
  13.   
  14.     if($streamData!=''){  
  15.         $ret = file_put_contents($receiveFile$streamData, true);  
  16.     }else{  
  17.         $ret = false;  
  18.     }  
  19.   
  20.     return $ret;  
  21.   
  22. }  
  23.   
  24. $receiveFile = 'receive.txt';  
  25. $ret = receiveStreamFile($receiveFile);  
  26. echo json_encode(array('success'=>(bool)$ret));  
  27. ?>  
原创粉丝点击