Get post request method encapsulation in php
<span style="font-size:18px;">网站上的商城可以搭建ecshop实现,微信端的微商城也可以开发wap版商城,然后通过链接链到微信菜单上,这样实现起来就不需要远程调用数据了,但登陆上有个问题,在微信上进入微商城在用户体验上当然不需要再登陆只需要有微信openid即可。所以有个考虑是在微信端开发微商城,所以的数据是取自网站商城的,这时需要远程请求数据。 有了ihttp_request()方法后,可通过此方法获取远程数据</span>
<span style="font-size:18px;"></span><pre name="code" class="php">function ihttp_request($url, $post = '', $extra = array(), $timeout = 60) { $urlset = parse_url($url); if(empty($urlset['path'])) { $urlset['path'] = '/'; } if(!empty($urlset['query'])) { $urlset['query'] = "?{$urlset['query']}"; } if(empty($urlset['port'])) { $urlset['port'] = $urlset['scheme'] == 'https' ? '443' : '80'; } if(function_exists('curl_init') && function_exists('curl_exec')) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $urlset['scheme']. '://' .$urlset['host'].($urlset['port'] == '80' ? '' : ':'.$urlset['port']).$urlset['path'].$urlset['query']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); if($post) { curl_setopt($ch, CURLOPT_POST, 1); if (is_array($post)) { $post = http_build_query($post); } curl_setopt($ch, CURLOPT_POSTFIELDS, $post); } curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1'); if (!empty($extra) && is_array($extra)) { $headers = array(); foreach ($extra as $opt => $value) { if (strexists($opt, 'CURLOPT_')) { curl_setopt($ch, constant($opt), $value); } elseif (is_numeric($opt)) { curl_setopt($ch, $opt, $value); } else { $headers[] = "{$opt}: {$value}"; } } if(!empty($headers)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } } $data = curl_exec($ch); $status = curl_getinfo($ch); $errno = curl_errno($ch); $error = curl_error($ch); curl_close($ch); if($errno || empty($data)) { return error(1, $error); } else { return ihttp_response_parse($data); } } $method = empty($post) ? 'GET' : 'POST'; $fdata = "{$method} {$urlset['path']}{$urlset['query']} HTTP/1.1\r\n"; $fdata .= "Host: {$urlset['host']}\r\n"; if(function_exists('gzdecode')) { $fdata .= "Accept-Encoding: gzip, deflate\r\n"; } $fdata .= "Connection: close\r\n"; if (!empty($extra) && is_array($extra)) { foreach ($extra as $opt => $value) { if (!strexists($opt, 'CURLOPT_')) { $fdata .= "{$opt}: {$value}\r\n"; } } } $body = ''; if ($post) { if (is_array($post)) { $body = http_build_query($post); } else { $body = urlencode($post); } $fdata .= 'Content-Length: ' . strlen($body) . "\r\n\r\n{$body}"; } else { $fdata .= "\r\n"; } if($urlset['scheme'] == 'https') { $fp = fsockopen('ssl://' . $urlset['host'], $urlset['port'], $errno, $error); } else { $fp = fsockopen($urlset['host'], $urlset['port'], $errno, $error); } stream_set_blocking($fp, true); stream_set_timeout($fp, $timeout); if (!$fp) { return error(1, $error); } else { fwrite($fp, $fdata); $content = ''; while (!feof($fp)) $content .= fgets($fp, 512); fclose($fp); return ihttp_response_parse($content, true); } } function ihttp_response_parse($data, $chunked = false) { $rlt = array(); $pos = strpos($data, "\r\n\r\n"); $split1[0] = substr($data, 0, $pos); $split1[1] = substr($data, $pos + 4, strlen($data)); $split2 = explode("\r\n", $split1[0], 2); preg_match('/^(\S+) (\S+) (\S+)$/', $split2[0], $matches); $rlt['code'] = $matches[2]; $rlt['status'] = $matches[3]; $rlt['responseline'] = $split2[0]; $header = explode("\r\n", $split2[1]); $isgzip = false; $ischunk = false; foreach ($header as $v) { $row = explode(':', $v); $key = trim($row[0]); $value = trim($row[1]); if (is_array($rlt['headers'][$key])) { $rlt['headers'][$key][] = $value; } elseif (!empty($rlt['headers'][$key])) { $temp = $rlt['headers'][$key]; unset($rlt['headers'][$key]); $rlt['headers'][$key][] = $temp; $rlt['headers'][$key][] = $value; } else { $rlt['headers'][$key] = $value; } if(!$isgzip && strtolower($key) == 'content-encoding' && strtolower($value) == 'gzip') { $isgzip = true; } if(!$ischunk && strtolower($key) == 'transfer-encoding' && strtolower($value) == 'chunked') { $ischunk = true; } } if($chunked && $ischunk) { $rlt['content'] = ihttp_response_parse_unchunk($split1[1]); } else { $rlt['content'] = $split1[1]; } if($isgzip && function_exists('gzdecode')) { $rlt['content'] = gzdecode($rlt['content']); } $rlt['meta'] = $data; if($rlt['code'] == '100') { return ihttp_response_parse($rlt['content']); } return $rlt; } function ihttp_response_parse_unchunk($str = null) { if(!is_string($str) or strlen($str) < 1) { return false; } $eol = "\r\n"; $add = strlen($eol); $tmp = $str; $str = ''; do { $tmp = ltrim($tmp); $pos = strpos($tmp, $eol); if($pos === false) { return false; } $len = hexdec(substr($tmp, 0, $pos)); if(!is_numeric($len) or $len < 0) { return false; } $str .= substr($tmp, ($pos + $add), $len); $tmp = substr($tmp, ($len + $pos + $add)); $check = trim($tmp); } while(!empty($check)); unset($tmp); return $str; }
$goods = array(
"api_version" =>"1.0",
"goods_id" => "4",
"ac" => "ac",
"act" => "search_goods_detail" ,
"return_data" => "json",
);
$url = "http://10.92.1.3/api.php"; //Here is the api.php on 1.3 on the 10.92.1.2 server to get its Data
$result = ihttp_request($url,$data);
var_dump($result);
The printed content is:
array(6) {
["code"]=>
string(3) "200 "
["status"]=>
string(2) "OK"
["responseline"]=>
string(15) "HTTP/1.1 200 OK"
["headers"]=>
array (9) {
["Server"]=>
string(5) "nginx"
["Date"]=>
string(19) "Fri, 06 Mar 2015 08"
["Content-Type" ]=>
string(24) "text/html; charset=utf-8"
["Transfer-Encoding"]=>
string(7) "chunked"
["Connection"]=>
string (10) "keep-alive"
["Vary"]=>
string(15) "Accept-Encoding"
["X-Powered-By"]=>
string(10) "PHP/5.3. 17"
["Cache-control"]=>
string(7) "private"
["Set-Cookie"]=>
array(2) {
[0]=>
string(55) "ECS_ID = 05FDCD0810E735BF2B3B3C8ddb5911d94e319b8b; PATH =/"
[1] = & GT;
String (47) "ECS [VISIT_TIMES] = 1; Expires = Sat, 05-MAR-2016 00 "}}
}
[" content "] =>
string(241) "{"result":"success","msg":"","info":{"data_info":[{"goods_id":"1","last_modify":"1423937979 "},{"goods_id":"2","last_modify":"1425595831"},{"goods_id":"3","last_modify":"1423937959"},{"goods_id":"4","last_modify ":"1423942862"}],"counts":"4"}}"
["meta"]=>
string(625) "HTTP/1.1 200 OK
Server: nginx
Date: Fri, 06 Mar 2015 08:03:41 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/5.3.17
Set-Cookie: ECS_ID=05fdcd0810e735bf2b3b3c8ddb5911d94e319b8b; path=/
The printed content is very detailed, even the header information is typed out, but we only need to care about the content in the content. This is the data we need to obtain
["content"]=>
string(241) "{" result":"success","msg":"","info":{"data_info":[{"goods_id":"1","last_modify":"1423937979"},{"goods_id":"2" ,"last_modify":"1425595831"},{"goods_id":"3","last_modify":"1423937959"},{"goods_id":"4","last_modify":"1423942862"}],"counts" :"4"}}"
The above introduces the encapsulation of the get post request method in PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

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



Both curl and Pythonrequests are powerful tools for sending HTTP requests. While curl is a command-line tool that allows you to send requests directly from the terminal, Python's requests library provides a more programmatic way to send requests from Python code. The basic syntax for converting curl to Pythonrequestscurl command is as follows: curl[OPTIONS]URL When converting curl command to Python request, we need to convert the options and URL into Python code. Here is an example curlPOST command: curl-XPOST https://example.com/api

To update the curl version under Linux, you can follow the steps below: Check the current curl version: First, you need to determine the curl version installed in the current system. Open a terminal and execute the following command: curl --version This command will display the current curl version information. Confirm available curl version: Before updating curl, you need to confirm the latest version available. You can visit curl's official website (curl.haxx.se) or related software sources to find the latest version of curl. Download the curl source code: Using curl or a browser, download the source code file for the curl version of your choice (usually .tar.gz or .tar.bz2

Convert basic data types to strings using Java's String.valueOf() function In Java development, when we need to convert basic data types to strings, a common method is to use the valueOf() function of the String class. This function can accept parameters of basic data types and return the corresponding string representation. In this article, we will explore how to use the String.valueOf() function for basic data type conversions and provide some code examples to

PHP8.1 released: Introducing curl for concurrent processing of multiple requests. Recently, PHP officially released the latest version of PHP8.1, which introduced an important feature: curl for concurrent processing of multiple requests. This new feature provides developers with a more efficient and flexible way to handle multiple HTTP requests, greatly improving performance and user experience. In previous versions, handling multiple requests often required creating multiple curl resources and using loops to send and receive data respectively. Although this method can achieve the purpose

From start to finish: How to use php extension cURL for HTTP requests Introduction: In web development, it is often necessary to communicate with third-party APIs or other remote servers. Using cURL to make HTTP requests is a common and powerful way. This article will introduce how to use PHP to extend cURL to perform HTTP requests, and provide some practical code examples. 1. Preparation First, make sure that php has the cURL extension installed. You can execute php-m|grepcurl on the command line to check

Method of converting char array to string: It can be achieved by assignment. Use {char a[]=" abc d\0efg ";string s=a;} syntax to let the char array directly assign a value to string, and execute the code to complete the conversion.

How to handle 301 redirection of web pages in PHPCurl? When using PHPCurl to send network requests, you will often encounter a 301 status code returned by the web page, indicating that the page has been permanently redirected. In order to handle this situation correctly, we need to add some specific options and processing logic to the Curl request. The following will introduce in detail how to handle 301 redirection of web pages in PHPCurl, and provide specific code examples. 301 redirect processing principle 301 redirect means that the server returns a 30

In Linux, curl is a very practical tool for transferring data to and from the server. It is a file transfer tool that uses URL rules to work under the command line; it supports file upload and download, and is a comprehensive transfer tool. . Curl provides a lot of very useful functions, including proxy access, user authentication, ftp upload and download, HTTP POST, SSL connection, cookie support, breakpoint resume and so on.
