有人能告诉我如何用HTTP POST做一个PHP cURL吗?

我想这样发送数据:

username=user1, password=passuser1, gender=1

到www.example.com

我希望cURL返回result=OK这样的响应。有什么例子吗?


当前回答

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;
}

其他回答

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;
}

下面是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, "");
    ...
?>

最简单的是以application/json的形式发送数据。这将接受一个数组作为输入,并正确地将其编码为json字符串:

$data = array(
    'field1' => 'field1value',
    'field2' => 'field2value',
)

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type:application/json',
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resultStr = curl_exec($ch);
return json_decode($resultStr, true);

我很惊讶没有人建议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()

如果你试图用cookies登录网站。

这段代码:

if ($server_output == "OK") { ... } else { ... }

如果您尝试登录,它可能无法工作,因为许多网站返回状态200,但发布不成功。

检查登录帖子是否成功的简单方法是检查它是否再次设置cookie。如果在输出中有一个Set-Cookies字符串,这意味着帖子没有成功,它开始一个新的会话。

同样,帖子可以成功,但是状态可以重定向,而不是200。

为了确保帖子成功,试试下面的方法:

Follow location在post之后,所以它会转到post重定向到的页面:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

然后检查请求中是否存在新的cookie:

if (!preg_match('/^Set-Cookie:\s*([^;]*)/mi', $server_output)) 

{echo 'post successful'; }

else { echo 'not successful'; }