


PHP implements HTTP request classes that support GET, POST, Multipart/form-data, multipartform-data_PHP tutorial
PHP implements HTTP request classes that support GET, POST, Multipart/form-data, multipartform-data
This article describes the example of PHP implementing the HTTP request class and its application that supports GET, POST, Multipart/form-data, and shares it with everyone for your reference. The details are as follows:
HttpRequest.class.php class file is as follows:
<?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 ?>
The demo sample program is as follows:
<?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 ''; ?>
The complete example code can be downloaded from this website by clicking here.
I hope this article will be helpful to everyone’s PHP programming design.
For controls whose file upload type is file, you can only use $_FILES to obtain them in the background. For other control types, you can use $_POST to obtain them. You only need to use the value obtained by $_FILES for your processing.
Use it only if you need to upload files
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
Changed to
xmlHttp.setRequestHeader( "Content-Type","multipart/form-data;");
As for sending binary data, you can figure it out yourself.
--------------------------------7db8c30150364 This is actually regular
, which is a beginning segment and an ending segment, 7db8c30150364 Just use a string of non-repeating characters to identify the data. Content-Disposition: form-data; name="polls[]" What data is used to represent and what is the file name.
In fact, this is how to use it when uploading files in socket sending. If you have time, study how to handle POST files in HTTP.

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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 and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
