PHP + curl,HTTP POST示例代码?

任何人都可以告诉我如何做一个HTTP POST的PHPcurl?

我想发送这样的数据:

username=user1, password=passuser1, gender=1 

www.domain.com

我期望curl返回result=OK 。 有没有例子?

 <?php // // A very simple PHP example that sends a HTTP POST to a remote site // $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "postvar1=value1&postvar2=value2&postvar3=value3"); // in real life you should use something like: // curl_setopt($ch, CURLOPT_POSTFIELDS, // http_build_query(array('postvar1' => 'value1'))); // receive server response ... curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $server_output = curl_exec ($ch); curl_close ($ch); // further processing .... if ($server_output == "OK") { ... } else { ... } ?> 

因为这个线程在PHP中使用curl发送邮件的结果很高,我想提供最有效的答案,因为上面和下面的所有其他人做了不必要的工作,而答案是非常简单的:

程序

 // set post fields $post = [ 'username' => 'user1', 'password' => 'passuser1', 'gender' => 1, ]; $ch = curl_init('http://www.example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); // execute! $response = curl_exec($ch); // close the connection, release resources used curl_close($ch); // do anything you want with your response var_dump($response); 

面向对象

 <?php namespace MyApp\Http; class Curl { /** @var resource cURL handle */ private $ch; /** @var mixed The response */ private $response = false; /** * @param string $url * @param array $options */ public function __construct($url, array $options = array()) { $this->ch = curl_init($url); foreach ($options as $key => $val) { curl_setopt($this->ch, $key, $val); } curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true); } /** * Get the response * @return string * @throws \RuntimeException On cURL error */ public function getResponse() { if ($this->response) { return $this->response; } $response = curl_exec($this->ch); $error = curl_error($this->ch); $errno = curl_errno($this->ch); if (is_resource($this->ch)) { curl_close($this->ch); } if (0 !== $errno) { throw new \RuntimeException($error, $errno); } return $this->response = $response; } /** * Let echo out the response * @return string */ public function __toString() { return $this->getResponse(); } } // usage $curl = new \MyApp\Http\Curl('http://www.example.com', array( CURLOPT_POSTFIELDS => array('username' => 'user1') )); try { echo $curl; } catch (\RuntimeException $ex) { die(sprintf('Http error %s with code %d', $ex->getMessage(), $ex->getCode())); } 

这里边注意:最好是用getResponse()方法创build一些名为AdapterInterface的接口,并让上面的类实现它。 然后,您可以随时将此实现与另一个类似的适配器交换,而不会对应用程序产生任何副作用。

使用HTTPS /encryptionstream量

通常,在Windows操作系统下,PHP的cURL存在问题。 在尝试连接到HTTPS保护的端点时,您会收到错误消息,告知您certificate verify failed

大多数人在这里做的是告诉cURL库简单地忽略证书错误并继续( curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); )。 因为这会使你的代码工作,所以你引入了巨大的安全漏洞,使恶意用户可以对你的应用程序进行各种攻击,比如中间人攻击等等。

永远不要这样做。 相反,您只需修改您的php.ini并告诉PHP您的CA Certificate文件的位置,以便正确validation证书:

 ; modify the absolute path to the cacert.pem file curl.cainfo=c:\php\cacert.pem 

最新的cacert.pem可以从互联网上下载或从您喜欢的浏览器中提取 。 当更改任何php.ini相关的设置记得要重新启动您的networking服务器。

一个使用php curl_exec做一个HTTP POST的实例:

把它放在一个名为foobar.php的文件中:

 <?php $ch = curl_init(); $skipper = "luxury assault recreational vehicle"; $fields = array( 'penguins'=>$skipper, 'bestpony'=>'rainbowdash'); $postvars = ''; foreach($fields as $key=>$value) { $postvars .= $key . "=" . $value . "&"; } $url = "http://www.google.com"; curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_POST, 1); //0 for a get request curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars); curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3); curl_setopt($ch,CURLOPT_TIMEOUT, 20); $response = curl_exec($ch); print "curl response is:" . $response; curl_close ($ch); ?> 

然后用命令php foobar.php运行它,它将这种输出转储到屏幕上:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Title</title> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="Expires" content="0"> <body> A mountain of content... </body> </html> 

所以你做了一个PHP POST到www.google.com并发送了一些数据。

如果服务器被编程为读取后variables,它可以决定做不同的事情。

这可以很容易达到:

 <?php $post = [ 'username' => 'user1', 'password' => 'passuser1', 'gender' => 1, ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://www.domain.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post)); $response = curl_exec($ch); var_export($response); 

如果表单使用的是redirect,身份validation,cookies,SSL(https)或者其他完全打开的脚本,而这些脚本需要POSTvariables,那么您将会非常快速地开始咬牙切齿。 看看史努比 ,这正是你想到的,而不需要设置大量的开销。

curl发布+error handling+设置标题[感谢@ mantas-d]:

 function curlPost($url, $data=NULL, $headers = NULL) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if(!empty($data)){ curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } if (!empty($headers)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } $response = curl_exec($ch); if (curl_error($ch)) { trigger_error('Curl Error:' . curl_error($ch)); } curl_close($ch); return $response; } curlPost('google.com', [ 'username' => 'admin', 'password' => '12345', ]); 

这里有一些PHP + curl的样板代码http://www.webbotsspidersscreenscrapers.com/DSP_download.php

包括在这些库中将简化开发

 <?php # Initialization include("LIB_http.php"); include("LIB_parse.php"); $product_array=array(); $product_count=0; # Download the target (store) web page $target = "http://www.tellmewhenitchanges.com/buyair"; $web_page = http_get($target, ""); ... ?> 

一个简单的答案,如果你传递信息到你自己的网站是使用一个SESSIONvariables。 开始php页面:

 session_start(); 

如果在某个时候有一些信息需要在PHP中生成并传递到会话中的下一页,而不是使用POSTvariables,则将其分配给SESSIONvariables。 例:

 $_SESSION['message']='www.'.$_GET['school'].'.edu was not found. Please try again.' 

然后在下一页你只需引用这个SESSIONvariables。 注意:使用后请务必将其销毁,以免使用后仍然存在:

 if (isset($_SESSION['message'])) {echo $_SESSION['message']; unset($_SESSION['message']);} 
 curlPost('google.com', [ 'username' => 'admin', 'password' => '12345', ]); function curlPost($url, $data) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response = curl_exec($ch); curl_close($ch); return $response; } 

示例用于Flickr API集成的cURL PHP代码

  # build the API URL to call $params = array( 'api_key' => '3bd4375728949f7d689ae85c5072b83a', 'method' => 'flickr.photos.getRecent', 'format' => 'php_serial', 'per_page' => '5' ); $encoded_params = array(); foreach ($params as $k => $v){ $encoded_params[] = urlencode($k).'='.urlencode($v); } # call the API and decode the response $url = "https://api.flickr.com/services/rest/?".implode('&', $encoded_params); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $rsp = curl_exec($ch); curl_close($ch); $rsp_obj = unserialize($rsp); echo '<pre>'; print_r($res_obj);