PHP实现支持GET,POST,Multipart/form-data的HTTP请求类,multipartform-data
PHP实现支持GET,POST,Multipart/form-data的HTTP请求类,multipartform-data
本文实例讲述了PHP实现支持GET,POST,Multipart/form-data的HTTP请求类及其应用,分享给大家供大家参考。具体如下:
HttpRequest.class.php类文件如下:
<?php /** HttpRequest class, HTTP请求类,支持GET,POST,Multipart/form-data * Date: 2013-09-25 * Author: fdipzone * Ver: 1.0 * * Func: * public setConfig 设置连接参数 * public setFormdata 设置表单数据 * public setFiledata 设置文件数据 * public send 发送数据 * private connect 创建连接 * private disconnect 断开连接 * private sendGet get 方式,处理发送的数据,不会处理文件数据 * private sendPost post 方式,处理发送的数据 * private sendMultipart multipart 方式,处理发送的数据,发送文件推荐使用此方式 */ class HttpRequest{ // class start private $_ip = ''; private $_host = ''; private $_url = ''; private $_port = ''; private $_errno = ''; private $_errstr = ''; private $_timeout = 15; private $_fp = null; private $_formdata = array(); private $_filedata = array(); // 设置连接参数 public function setConfig($config){ $this->_ip = isset($config['ip'])? $config['ip'] : ''; $this->_host = isset($config['host'])? $config['host'] : ''; $this->_url = isset($config['url'])? $config['url'] : ''; $this->_port = isset($config['port'])? $config['port'] : ''; $this->_errno = isset($config['errno'])? $config['errno'] : ''; $this->_errstr = isset($config['errstr'])? $config['errstr'] : ''; $this->_timeout = isset($confg['timeout'])? $confg['timeout'] : 15; // 如没有设置ip,则用host代替 if($this->_ip==''){ $this->_ip = $this->_host; } } // 设置表单数据 public function setFormData($formdata=array()){ $this->_formdata = $formdata; } // 设置文件数据 public function setFileData($filedata=array()){ $this->_filedata = $filedata; } // 发送数据 public function send($type='get'){ $type = strtolower($type); // 检查发送类型 if(!in_array($type, array('get','post','multipart'))){ return false; } // 检查连接 if($this->connect()){ switch($type){ case 'get': $out = $this->sendGet(); break; case 'post': $out = $this->sendPost(); break; case 'multipart': $out = $this->sendMultipart(); break; } // 空数据 if(!$out){ return false; } // 发送数据 fputs($this->_fp, $out); // 读取返回数据 $response = ''; while($row = fread($this->_fp, 4096)){ $response .= $row; } // 断开连接 $this->disconnect(); $pos = strpos($response, "\r\n\r\n"); $response = substr($response, $pos+4); return $response; }else{ return false; } } // 创建连接 private function connect(){ $this->_fp = fsockopen($this->_ip, $this->_port, $this->_errno, $this->_errstr, $this->_timeout); if(!$this->_fp){ return false; } return true; } // 断开连接 private function disconnect(){ if($this->_fp!=null){ fclose($this->_fp); $this->_fp = null; } } // get 方式,处理发送的数据,不会处理文件数据 private function sendGet(){ // 检查是否空数据 if(!$this->_formdata){ return false; } // 处理url $url = $this->_url.'?'.http_build_query($this->_formdata); $out = "GET ".$url." http/1.1\r\n"; $out .= "host: ".$this->_host."\r\n"; $out .= "connection: close\r\n\r\n"; return $out; } // post 方式,处理发送的数据 private function sendPost(){ // 检查是否空数据 if(!$this->_formdata && !$this->_filedata){ return false; } // form data $data = $this->_formdata? $this->_formdata : array(); // file data if($this->_filedata){ foreach($this->_filedata as $filedata){ if(file_exists($filedata['path'])){ $data[$filedata['name']] = file_get_contents($filedata['path']); } } } if(!$data){ return false; } $data = http_build_query($data); $out = "POST ".$this->_url." http/1.1\r\n"; $out .= "host: ".$this->_host."\r\n"; $out .= "content-type: application/x-www-form-urlencoded\r\n"; $out .= "content-length: ".strlen($data)."\r\n"; $out .= "connection: close\r\n\r\n"; $out .= $data; return $out; } // multipart 方式,处理发送的数据,发送文件推荐使用此方式 private function sendMultipart(){ // 检查是否空数据 if(!$this->_formdata && !$this->_filedata){ return false; } // 设置分割标识 srand((double)microtime()*1000000); $boundary = '---------------------------'.substr(md5(rand(0,32000)),0,10); $data = '--'.$boundary."\r\n"; // form data $formdata = ''; foreach($this->_formdata as $key=>$val){ $formdata .= "content-disposition: form-data; name=\"".$key."\"\r\n"; $formdata .= "content-type: text/plain\r\n\r\n"; if(is_array($val)){ $formdata .= json_encode($val)."\r\n"; // 数组使用json encode后方便处理 }else{ $formdata .= rawurlencode($val)."\r\n"; } $formdata .= '--'.$boundary."\r\n"; } // file data $filedata = ''; foreach($this->_filedata as $val){ if(file_exists($val['path'])){ $filedata .= "content-disposition: form-data; name=\"".$val['name']."\"; filename=\"".$val['filename']."\"\r\n"; $filedata .= "content-type: ".mime_content_type($val['path'])."\r\n\r\n"; $filedata .= implode('', file($val['path']))."\r\n"; $filedata .= '--'.$boundary."\r\n"; } } if(!$formdata && !$filedata){ return false; } $data .= $formdata.$filedata."--\r\n\r\n"; $out = "POST ".$this->_url." http/1.1\r\n"; $out .= "host: ".$this->_host."\r\n"; $out .= "content-type: multipart/form-data; boundary=".$boundary."\r\n"; $out .= "content-length: ".strlen($data)."\r\n"; $out .= "connection: close\r\n\r\n"; $out .= $data; return $out; } } // class end ?>
demo示例程序如下:
<?php require('HttpRequest.class.php'); $config = array( 'ip' => 'demo.fdipzone.com', // 如空则用host代替 'host' => 'demo.fdipzone.com', 'port' => 80, 'errno' => '', 'errstr' => '', 'timeout' => 30, 'url' => '/getapi.php', //'url' => '/postapi.php', //'url' => '/multipart.php' ); $formdata = array( 'name' => 'fdipzone', 'gender' => 'man' ); $filedata = array( array( 'name' => 'photo', 'filename' => 'photo.jpg', 'path' => 'photo.jpg' ) ); $obj = new HttpRequest(); $obj->setConfig($config); $obj->setFormData($formdata); $obj->setFileData($filedata); $result = $obj->send('get'); //$result = $obj->send('post'); //$result = $obj->send('multipart'); echo '<pre class="brush:php;toolbar:false">'; print_r($result); echo '
完整实例代码可以点击此处本站下载。
希望本文所述对大家的PHP程序设计有所帮助。
文件上传类型为file的控件,后台获取时只能用$_FILES来获取,其他的控件类型才是用$_POST来获取,你只需要用$_FILES获取的值来进行你的处理。
只是需要文件上传才用它的
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
改成
xmlHttp.setRequestHeader("Content-Type","multipart/form-data;");
至于发送二进制数据,你自己解决吧。
-----------------------------7db8c30150364 这个其实有规律的
就是一个开始段一个结束段,7db8c30150364 只是用一串不重复的字符,标识一起其中间的东西就是数据,Content-Disposition: form-data; name="polls[]" 这个是用来表示什么数据,文件名是啥。
其实在socket发包中,上传文件的时候就要这么用,有空研究一下HTTP里面POST 文件时,应该如何处理。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
