Example of using PHP curl function to simulate curl request

Source: Internet
Author: User
Tags curl

PHP has a good curl mechanism, but it is always less satisfying to use, because it takes several steps and a lot of difficult to remember parameters, here I encapsulate the PHP curl to make it less complicated:

The code is as follows Copy Code

<?php
/**
* PHP Mock Curl Request
*
* @param string $url the requested URL
* @param string $method The requested method, the default post
* @param array $data requests for data delivery
* @param array $header header information for the request setting
* @param int $head Print header information
* @param int $body whether to print body information
* @param int $timeout set timeout time
*
* @return Array
*/
Function Curl ($url, $method = "POST", $data =array (), $header =array (), $head =0, $body =0, $timeout = 30)
{
$ch = Curl_init ();
curl_setopt ($ch, Curlopt_url, $url);
if (Strpos ($url, "https")!== false) {
curl_setopt ($ch, Curlopt_ssl_verifypeer, 0);
curl_setopt ($ch, curlopt_ssl_verifyhost, 0);
if (Isset ($_server[' http_user_agent ')) {
curl_setopt ($ch, curlopt_useragent, $_server[' http_user_agent ']);
}
}
if (!empty ($header)) {
curl_setopt ($ch, Curlopt_httpheader, $header);
}
Switch ($method) {
Case ' POST ':
curl_setopt ($ch, Curlopt_post, 1);
curl_setopt ($ch, Curlopt_postfields, $data);
Break
Case ' get ':
Break
Case ' put ':
curl_setopt ($ch, Curlopt_put, 1);
curl_setopt ($ch, Curlopt_infile, "");
curl_setopt ($ch, Curlopt_infilesize, 10);
Break
Case ' DELETE ':
curl_setopt ($ch, Curlopt_customrequest, "DELETE");
Break
Default
Break
}

curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_header, $head);
curl_setopt ($ch, Curlopt_nobody, $body);
curl_setopt ($ch, Curlopt_connecttimeout, $timeout);
$rtn = curl_exec ($ch); Get back
if (Curl_errno ($ch)) {
Echo ' Errno '. Curl_error ($ch);//Catch exception
}
Curl_close ($ch);
return $RTN;
}
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.