有人能告诉我如何用HTTP POST做一个PHP cURL吗?
我想这样发送数据:
username=user1, password=passuser1, gender=1
到www.example.com
我希望cURL返回result=OK这样的响应。有什么例子吗?
有人能告诉我如何用HTTP POST做一个PHP cURL吗?
我想这样发送数据:
username=user1, password=passuser1, gender=1
到www.example.com
我希望cURL返回result=OK这样的响应。有什么例子吗?
当前回答
如果表单使用重定向、身份验证、cookie、SSL (https)或其他任何东西,而不是期望POST变量的完全开放脚本,那么您将很快开始咬牙切齿。看看Snoopy,它完全按照您的想法来做,而且不需要设置大量的开销。
其他回答
程序上的
// 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
// mutatis mutandis
namespace MyApp\Http;
class CurlPost
{
private $url;
private $options;
/**
* @param string $url Request URL
* @param array $options cURL options
*/
public function __construct($url, array $options = [])
{
$this->url = $url;
$this->options = $options;
}
/**
* Get the response
* @return string
* @throws \RuntimeException On cURL error
*/
public function __invoke(array $post)
{
$ch = \curl_init($this->url);
foreach ($this->options as $key => $val) {
\curl_setopt($ch, $key, $val);
}
\curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
\curl_setopt($ch, \CURLOPT_POSTFIELDS, $post);
$response = \curl_exec($ch);
$error = \curl_error($ch);
$errno = \curl_errno($ch);
if (\is_resource($ch)) {
\curl_close($ch);
}
if (0 !== $errno) {
throw new \RuntimeException($error, $errno);
}
return $response;
}
}
使用
// create curl object
$curl = new \MyApp\Http\CurlPost('http://www.example.com');
try {
// execute the request
echo $curl([
'username' => 'user1',
'password' => 'passuser1',
'gender' => 1,
]);
} catch (\RuntimeException $ex) {
// catch errors
die(sprintf('Http error %s with code %d', $ex->getMessage(), $ex->getCode()));
}
旁注:最好是使用getResponse()方法创建某种名为AdapterInterface的接口,并让上面的类实现它。然后,您总是可以将这个实现与您喜欢的另一个适配器交换,而不会对应用程序产生任何副作用。
使用HTTPS /加密流量
在Windows操作系统下,PHP中的cURL通常会有问题。在尝试连接到受https保护的端点时,您将得到一个错误,告诉您证书验证失败。
大多数人在这里做的是告诉cURL库简单地忽略证书错误并继续(curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);)。因为这将使你的代码正常工作,你引入了巨大的安全漏洞,并使恶意用户能够对你的应用程序执行各种攻击,如Man In The Middle攻击或类似的攻击。
永远,永远不要那样做。相反,你只需要修改你的PHP .ini,并告诉PHP你的CA证书文件在哪里,让它正确地验证证书:
; modify the absolute path to the cacert.pem file
curl.cainfo=c:\php\cacert.pem
最新的音乐会。pem可以从互联网上下载,也可以从您喜欢的浏览器中提取。当更改任何php.ini相关设置时,记得重新启动web服务器。
Curl Post +错误处理+设置头[感谢@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',
]);
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);
$error = curl_error($ch);
curl_close($ch);
if ($error !== '') {
throw new \Exception($error);
}
return $response;
}
我很惊讶没有人建议file_get_contents:
$url = "http://www.example.com";
$parameters = array('username' => 'user1', 'password' => 'passuser1', 'gender' => '1');
$options = array('http' => array(
'header' => 'Content-Type: application/x-www-form-urlencoded\r\n',
'method' => 'POST',
'content' => http_build_query($parameters)
));
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
这很简单,很有效;我把它用在两端都能控制代码的环境中。
更好的方法是使用json_decode(并设置代码以返回JSON)
$result = json_decode(file_get_contents($url, false, $context), TRUE);
这种方法在幕后调用curl,但不需要经历那么多困难。
从Stack Overflow上其他地方的原始答案提炼出来的答案: PHP将变量发送到file_get_contents()
发送表单和原始数据的示例:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/post',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify POST method
*/
CURLOPT_POST => true,
/**
* Specify array of form fields
*/
CURLOPT_POSTFIELDS => [
'foo' => 'bar',
'baz' => 'biz',
],
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo($response);