PHP模拟表单POST图片

作者:王炜
日期:2014年02月12日

<?php
/**
 * 功能:模拟表单POST图片
 * 参数: $posturl 提交地址
 *       $data  提交的其他数据
 *       $file  图片绝对路径
 */
function postdata($posturl,$data=array(),$file=''){
 $url = parse_url($posturl);
 if(!$url) return "couldn't parse url";
 if(!isset($url['port'])) $url['port'] = "";
 if(!isset($url['query'])) $url['query'] = "";
 
 $boundary = "---------------------------".substr(md5(rand(0,32000)),0,10);
 $boundary_2 = "--$boundary";
 
 $content = $encoded = "";
 if($data){
  while (list($k,$v) = each($data)){
   $encoded .= $boundary_2."\r\nContent-Disposition: form-data; name=\"".rawurlencode($k)."\"\r\n\r\n";
   $encoded .= rawurlencode($v)."\r\n";
  }
 }
 
 if($file){
  $ext=strrchr($file,".");
  $type = "image/jpeg";
  switch($ext){
   case '.gif': $type = "image/gif";
    break;
   case '.jpg': $type = "image/jpeg";
    break;
   case '.png': $type = "image/png";
    break;
  }
  $encoded .= $boundary_2."\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"$file\"\r\nContent-Type: $type\r\n\r\n";
  $content = join("", file($file));
  $encoded.=$content."\r\n";
 }
 
 $encoded .= "\r\n".$boundary_2."--\r\n\r\n";
 $length = strlen($encoded);
 
 $fp = fsockopen($url['host'], $url['port'] ? $url['port'] : 80);
 if(!$fp) return "Failed to open socket to $url[host]";
 
 fputs($fp, sprintf("POST %s%s%s HTTP/1.0\r\n", $url['path'], $url['query'] ? "?" : "", $url['query']));
 fputs($fp, "Host: $url[host]\r\n");
 fputs($fp, "Content-type: multipart/form-data; boundary=$boundary\r\n");
 fputs($fp, "Content-length: ".$length."\r\n");
 fputs($fp, "Connection: close\r\n\r\n");
 fputs($fp, $encoded);
 
 $line = fgets($fp,1024);
 if (!eregi("^HTTP/1\.. 200", $line)) return null;
 
 $results = "";
 $inheader = 1;
 while(!feof($fp)){
 $line = fgets($fp,1024);
 if($inheader && ($line == "\r\n" || $line == "\r\r\n")){
 $inheader = 0;
 }elseif(!$inheader){
 $results .= $line;
 }
 }
 fclose($fp);
 return $results;
}

$posturl = 'http://www.phpzu.com/test.php';//post提交地址
$data = array('name'=>'张三','sex'=>1);//提交的其他数据
$file = 'http://imgstatic.baidu.com/img/image/shouye/yiping2.jpg';//图片的绝对路径可以是url地址
postdata("http://www.phpzu.com/a.php",$data,'http://imgstatic.baidu.com/img/image/shouye/yiping2.jpg');

?>

欢迎转载,转载请保留链接: https://www.phpzu.com/article/2014/02/12/139.html

PHP模拟表单POST图片:等您坐沙发呢!

发表评论

*

code

0