search
HomeBackend DevelopmentPHP TutorialPHP's curl implements get, post and cookie (example introduction)_PHP tutorial

PHP's curl implements get, post and cookie (example introduction)_PHP tutorial

Jul 21, 2016 pm 03:06 PM
cookiecurldreamhostgetphppostHostintroduceandExampleaccomplishServeof

Host service providers such as dreamhost show the use of fopen. Using PHP's curl can support FTP, FTPS, HTTP HTPPS SCP SFTP TFTP TELNET DICT FILE and LDAP. curl supports SSL certificate, HTTP POST, HTTP PUT, FTP upload, Kerberos, HTTP-based upload, proxy, cookie, user + password certificate, file transfer recovery, http proxy channel. The most commonly used one is http-based get and post method.
Code implementation:
1. HTTP get implementation

Copy code The code is as follows:

$ch = curl_init("http://www.domain.com/api/index.php?test=1") ;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // Get data and return
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // Get data and return when CURLOPT_RETURNTRANSFER is enabled
echo $output = curl_exec($ch) ;

/* Write Input file*/
$fh = fopen("out.html", 'w') ;
fwrite($fh, $output) ;
fclose($fh) ;

2. HTTP post implementation
Copy code The code is as follows:

$url = 'http://www.domain.com/api/' ;
$fields = array(
'lname'=>'justcoding' ,
          'fname'=>'phplover',                                                'email'=>'1353777303@ gmail.com' ,
'phone'=>'1353777303'
);
//$post_data = implode('&',$fields);


Note: The parameters of the post request must be connected using the get method and passed as a string:

For example: $params = 'userId ='.$this->user_id.'&auth='.$this->auth.'&sig='.$this->sig
There are also cross-platform requests, curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // Use automatic jump (very important) //open connection

$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL,$url) ;
curl_setopt($ch, CURLOPT_POST,count($fields)) ; // enable A regular POST request of type: application/x-www-form-urlencoded will be sent, just like the form submission.
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields); // "POST" operation in HTTP. If you want to transfer a file, you need a file name starting with @

ob_start();
curl_exec($ch);
$result = ob_get_contents();
ob_end_clean();

echo $result;

//close connection
curl_close($ch) ;




Copy code
The code is as follows:
if($_GET['test'])
{
print_r($_GET);
}

if($_POST)
{
print_r($_POST);
}




php curl transmission cookie


Two ways:

One is automatic:

Copy Code
The code is as follows: curl_setopt($curlHandle, CURLOPT_COOKIEJAR, 'cookie.txt '); //Save curl_setopt($curlHandle, CURLOPT_COOKIEFILE, 'cookie.txt '); //Read

so that COOKIE will automatically follow.
But it needs to be divided into two times. First, the cookie is generated by the first visit, and then the cookie can be used by the link
Example:



Copy code
The code is as follows:


function get_curlcuconent2($filename,$referer)
{
$cookie_jar = tempnam('./tmp','JSESSIONID');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $filename);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1) ;

//Set the cookie path for file reading and submission
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);
$filecontent=curl_exec($ch);
curl_close($ ch);

$ch = curl_init();
$hostname ="www.domain.com";
//$referer="http://www.domain.com/" ;
curl_setopt($ch, CURLOPT_URL, $filename);
curl_setopt($ch, CURLOPT_REFERER, $referer); // Look here, you can also say you are from google
curl_setopt($ch, CURLOPT_USERAGENT, "www.domain.com");

//$request = "JSESSIONID=abc6szw15ozvZ_PU9b-8r"; //Set POST parameters
//curl_setopt($ch, CURLOPT_POSTFIELDS, $request) ;
// In the above sentence, of course you can say you are baidu, just change the value here and it will be ok. You can achieve the function of a thief, $_SERVER['HTTP_USER_AGENT']
//You can also do it yourself A spider, so just fake CURLOPT_USERAGENT here
//If you want to put this program on linux and execute it with php -q, you must also write the specific $_SERVER['HTTP_USER_AGENT'], you can also fake it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
curl_setopt($ch, CURLOPT_HEADER, false);//Set whether to output page content
curl_setopt($ch, CURLOPT_GET, 1); // post,get past

$filecontent = curl_exec($ch);
preg_match_all("/charset=(.+?)[NULL"' ]/is",$filecontent, $charsetarray);
if(strtolower($charsetarray[1][0])=="utf-8")
$filecontent=iconv( 'utf-8', 'gb18030//IGNORE' , $filecontent);
curl_close($ch);
return $filecontent;
}

?>

A customization:
Copy code The code is as follows:

$header[]= 'Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, text/html, * '. '/* ';
$header[]= 'Accept-Language : zh-cn ';
$header[]= 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727) ';
$header[] = 'Host: '.$Your target HOST;
$header[]= 'Connection: Keep-Alive ';
$header[]= 'Cookie: '.$Your COOKIE string;

curl_setopt($curlHandel,CURLOPT_HTTPHEADER,$header);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327597.htmlTechArticleHost service providers such as dreamhost show the use of fopen. Using PHP's curl can support FTP, FTPS, HTTP HTPPS SCP SFTP TFTP TELNET DICT FILE and LDAP. curl supports...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools