Home  >  Article  >  Backend Development  >  POST data using PHP CURL_PHP Tutorial

POST data using PHP CURL_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:33:31940browse

curl is a file transfer tool using URL syntax, supporting FTP, FTPS, HTTP HTTPS SCP SFTP TFTP TELNET DICT FILE and LDAP. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploads, Kerberos, HTTP-based uploads, proxies, cookies, user+password authentication, file transfer recovery, http proxy channels and a host of other useful tricks.

It turns out that PHP does not extend this function by default, but it is still available, but it is not enabled. Open the PHP installation directory, search for the following three files ssleay32.dll, libeay32.dll and php_curl.dll, copy them one by one to the system32 folder in the system directory, modify the php.ini file, and find the line; extension= php_curl.dll. Remove the ; sign in front, save, and restart the server.

Here are a few examples.

Send SMS and MMS

	$xml_data = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
	<TaskDataTransfer4EReq xmlns="http://www.aspirehld.com/iecp/TaskDataTransfer4EReq">
	<eid> </eid>
	<username> </username>
	<password> </password>
	<src> </src>
	<destmsisdn>'.$pns.'</destmsisdn>
	<content type="sms">
		<title>'.$content.'</title>
	</content>
	</TaskDataTransfer4EReq>';
	
	$url = 'http://www.bkjia.com/service/taskSubmit';//接收XML地址
	
	$header = "Content-type: text/xml";//定义content-type为xml
	$ch = curl_init(); //初始化curl
	curl_setopt($ch, CURLOPT_URL, $url);//设置链接
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置HTTP头
	curl_setopt($ch, CURLOPT_POST, 1);//设置为POST方式
	curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);//POST数据
	$response = curl_exec($ch);//接收返回信息
	if(curl_errno($ch)){//出错则显示错误信息
		print curl_error($ch);
	}
	curl_close($ch); //关闭curl链接
	echo $response;//显示返回信息

POST data Fetion interface

$username = 13800138000;
$password = 123456;
$sendto = 13912345678;
$message = "测试一个试试看!";

$curlPost = 'username='.urlencode($username).'&
password='.urlencode($password).'&
sendto='.urlencode($sendto).'&
message='.urlencode($message).'';

$ch = curl_init();//初始化curl
curl_setopt($ch,CURLOPT_URL,'http://sms.api.bz/fetion.php');//抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch);//运行curl
curl_close($ch);
print_r($data);//输出结果

Fetion interface mode: http://sms.api.bz/fetion.php?username=your mobile Fetion login mobile number, &password=your mobile Fetion login password, &sendto=the mobile phone number of Fetion friends who receive SMS messages, &message=SMS content.

To summarize the curl method:

  1. Initialize curl
  2. Use curl_setopt to set the target url, and other options
  3. curl_exec, execute curl
  4. After execution, close curl
  5. The last step is output

CERL Multithreading

curl is generally used to crawl web pages, the second is to get or post data, and the third application is to implement multi-threaded tasks in PHP. Let’s implement multi-threading:

<?php
/*
curl 多线程抓取
*/

 /** 
     * curl 多线程 
     *  
     * @param array $array 并行网址 
     * @param int $timeout 超时时间
     * @return array 
     */ 
 function Curl_http($array,$timeout){
 	$res = array();
 	$mh = curl_multi_init();//创建多个curl语柄
	$startime = getmicrotime();
 	foreach($array as $k=>$url){
 		$conn[$k]=curl_init($url);
 		
        curl_setopt($conn[$k], CURLOPT_TIMEOUT, $timeout);//设置超时时间
        curl_setopt($conn[$k], CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($conn[$k], CURLOPT_MAXREDIRS, 7);//HTTp定向级别
        curl_setopt($conn[$k], CURLOPT_HEADER, 0);//这里不要header,加块效率
        curl_setopt($conn[$k], CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
        curl_setopt($conn[$k],CURLOPT_RETURNTRANSFER,1);
        curl_multi_add_handle ($mh,$conn[$k]);
 	}
	 //防止死循环耗死cpu 这段是根据网上的写法
		do {
			$mrc = curl_multi_exec($mh,$active);//当无数据,active=true
		} while ($mrc == CURLM_CALL_MULTI_PERFORM);//当正在接受数据时
		while ($active and $mrc == CURLM_OK) {//当无数据时或请求暂停时,active=true
			if (curl_multi_select($mh) != -1) {
				do {
					$mrc = curl_multi_exec($mh, $active);
				} while ($mrc == CURLM_CALL_MULTI_PERFORM);
			}
		}
 	
 	foreach ($array as $k => $url) {
 		  curl_error($conn[$k]);
    	  $res[$k]=curl_multi_getcontent($conn[$k]);//获得返回信息
    	  $header[$k]=curl_getinfo($conn[$k]);//返回头信息
    	  curl_close($conn[$k]);//关闭语柄
    	  curl_multi_remove_handle($mh  , $conn[$k]);   //释放资源  
		}
		
		curl_multi_close($mh);
		$endtime = getmicrotime();
		$diff_time = $endtime - $startime;
		
		return array('diff_time'=>$diff_time,
					 'return'=>$res,
					'header'=>$header		
					);
 	
 }
 //计算当前时间
 function getmicrotime() {
	    list($usec, $sec) = explode(" ",microtime());
	    return ((float)$usec + (float)$sec);
	}
	
	//测试一下,curl 三个网址
	$array = array(
				"http://www.weibo.com/",
				"http://www.renren.com/",
				"http://www.qq.com/"
				);

	$data = Curl_http($array,'10');//调用
	var_dump($data);//输出
	 
?>

Because $active has to wait until all url data is received before it becomes false, so the return value of curl_multi_exec is used here to determine whether there is still data. When there is data, curl_multi_exec will be called continuously. If there is no data temporarily, it will enter the select stage. , it can be awakened to continue execution as soon as new data comes. The advantage here is that there is no unnecessary consumption of CPU.

The steps for writing this multi-threading method:

  1. Call curl_multi_init
  2. Call curl_multi_add_handle in a loop. What needs to be noted in this step is that the second parameter of curl_multi_add_handle is the subhandle from curl_init.
  3. Continuously calling curl_multi_exec
  4. Call curl_multi_getcontent in a loop as needed to get the results
  5. Call curl_multi_remove_handle, and call curl_close
  6. for each word handle
  7. Call curl_multi_close

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752459.htmlTechArticlecurl is a file transfer tool using URL syntax, supporting FTP, FTPS, HTTP HTTPS SCP SFTP TFTP TELNET DICT FILE and LDAP. curl supports SSL certificate, HTTP POST, HTTP PUT, FTP upload, ker...
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