有人能告诉我如何用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;
}

其他回答

<?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 { ... }
?>

如果表单使用重定向、身份验证、cookie、SSL (https)或其他任何东西,而不是期望POST变量的完全开放脚本,那么您将很快开始咬牙切齿。看看Snoopy,它完全按照您的想法来做,而且不需要设置大量的开销。

发送表单和原始数据的示例:

$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);

如果您要将信息传递到您自己的网站,一个更简单的答案是使用SESSION变量。开始php页面:

session_start();

如果在某些情况下,您希望在PHP中生成信息并将其传递到会话中的下一页,则不要使用POST变量,而是将其分配给session变量。例子:

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

然后在下一页中只需引用这个SESSION变量。注意:在你使用它之后,一定要销毁它,这样它就不会在使用后继续存在:

if (isset($_SESSION['message'])) {echo $_SESSION['message']; unset($_SESSION['message']);}

最简单的是以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);