主要就是利用php 的 fsocketopen 消息传输。 这里先通过upload.html 文件提交,利用chrome抓包,可以看到几个关键的信息。
首先指定了表单类型为multipart/form-data;。 boundary是分隔符 因为上传文件不在使用原有的http协议了。请求内容不再可能以 x = y方式发送了。而使用了 分隔符 字段内容 分隔符号 字段内容2 而boundary就是指定分隔符号的标志。 请求的内容就应该是这样的了。
在来看下消息体
#socket_upload.php 拼接http上传协议格式 post请求
fp = fsockopen($this->host,$this->port,$this->errno,$this->errstr,$this->timeout); if (!$this->fp) exit('failed'); //赋值 $this->form = $form; $this->file = $file; //设置头信息,消息体 $this->setHead(); $this->setBody(); //拼接整个请求信息 $this->getStr(); } public function write() { //echo $this->res; //写入 fwrite($this->fp, $this->res); //打印输出信息 $response = ''; while($row=fread($this->fp, 4096)){ $response .= $row; } fclose($this->fp); $pos = strpos($response, "\r\n\r\n"); $response = substr($response, $pos+4); echo $response; } private function getStr() { $this->header .= "Content-Length:".strlen($this->body)."\r\n"; $this->header .= "Connection: close\r\n\r\n"; $this->res = $this->header.$this->body; } //设置头信息 private function setHead() { $this->header .= "POST { $this->url} HTTP/1.1\r\n"; $this->header .= "HOST:{ $this->host} \r\n"; $this->header .= "Content-Type:multipart/form-data; boundary={ $this->boundary}\r\n"; } //设置消息体 private function setBody() { $this->form(); $this->file(); } //非文件表单 private function form() { if ($this->form && is_array($this->form)) { foreach ($this->form as $key=>$val) { $this->body .= "--$this->boundary"."\r\n"; $this->body .= "Content-Disposition: form-data; name=\"{ $key}\"\r\n"; $this->body .= "Content-type:text/plain\r\n\r\n"; $this->body .= "{ $val}\r\n"; } } } //文件表单 private function file() { if ($this->file && is_array($this->file)) { foreach ($this->file as $key=>$val) { $this->body .= "--$this->boundary"."\r\n"; $this->body .= "Content-Disposition: form-data; name=\"{ $val['name']}\"; filename=\"{ $val['filename']}\"\r\n"; $this->body .= "Content-Type: { $val['type']}\r\n\r\n"; $this->body .= file_get_contents($val['path'])."\r\n"; $this->body .= "--{ $this->boundary}"; } } }}$form = [ 'name'=>'lemon', 'age'=>'12'];$file = [ [ 'name'=>'file', 'filename'=>'a.jpg', 'path'=>'a.jpg', 'type'=>'image/jpeg', ]];$upload = new SOCKET_UPLOAD($form,$file);$upload->write();
#接收post请求并保存图片代码
age is:",$age.""; $file = $_FILES['file']; $ext = strrchr($file['name'],'.'); $filename = $_SERVER["REQUEST_TIME"].$ext; if (move_uploaded_file($file['tmp_name'],UPLOAD.'/'.$filename)) { echo ''; }}
范例代码:http://files.cnblogs.com/files/loveyouyou616/socket.zip