[英]PHP, cURL, and HTTP POST example?
誰能告訴我如何用 HTTP POST 做一個 PHP cURL?
我想發送這樣的數據:
username=user1, password=passuser1, gender=1
到www.example.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 { ... }
?>
// 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()));
}
這里的旁注:最好創建某種名為AdapterInterface
的接口,例如使用getResponse()
方法並讓上面的類實現它。 然后,您始終可以將此實現與您喜歡的另一個適配器交換,而不會對您的應用程序產生任何副作用。
通常在 Windows 操作系統下 PHP 的 cURL 會出現問題。 在嘗試連接到受 https 保護的端點時,您將收到一條錯誤消息,告訴您certificate verify failed
。
大多數人在這里所做的是告訴 cURL 庫簡單地忽略證書錯誤並繼續( curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
)。 由於這將使您的代碼正常工作,因此您會引入巨大的安全漏洞並使惡意用戶能夠對您的應用程序執行各種攻擊,例如中間人攻擊等。
永遠,永遠不要那樣做。 相反,您只需要修改您的php.ini
並告訴 PHP 您的CA Certificate
文件在哪里,讓它正確驗證證書:
; modify the absolute path to the cacert.pem file
curl.cainfo=c:\php\cacert.pem
最新的cacert.pem
可以從 Internet 下載或從您喜歡的瀏覽器中提取。 更改任何php.ini
相關設置時,請記住重新啟動您的網絡服務器。
把它放在一個名為 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>
因此,您對 www.google.com 進行了 PHP POST 並向其發送了一些數據。
如果服務器被編程為讀取 post 變量,它可以根據它決定做一些不同的事情。
可以通過以下方式輕松實現:
<?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);
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',
]);
$url = "www.domain.com";
$ch = curl_init($url);
HTTPHEADER
選項設置為 cURL:$token = "generated token code";
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json', // for define content type that is json
'bearer: '.$token, // send token in header request
'Content-length: 100' // content length for example 100 characters (can add by strlen($fields))
)
);
CURLOPT_HEADER
為true
:curl_setopt($ch, CURLOPT_HEADER, false);
RETURNTRANSFER
選項設置為true
以將傳輸作為字符串返回,而不是直接輸出:curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
0(to not check the names)
、 1(not supported in cURL 7.28.1)
、 2(default value and for production mode)
:curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$fields = array(
"username" => "user1",
"password" => "passuser1",
"gender" => 1
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
result=OK
的輸出:$result = curl_exec($ch);
curl_close($ch);
call_cURL
類:class class_name_for_call_cURL {
protected function getUrl() {
return "www.domain.com";
}
public function call_cURL() {
$token = "generated token code";
$fields = array(
"username" => "user1",
"password" => "passuser1",
"gender" => 1
);
$url = $this->getUrl();
$output = $this->_execute($fields, $url, $token);
// if you want to get json data
// $output = json_decode($output);
if ($output == "OK") {
return true;
} else {
return false;
}
}
private function _execute($postData, $url, $token) {
// for sending data as json type
$fields = json_encode($postData);
$ch = curl_init($url);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json', // if the content type is json
'bearer: '.$token // if you need token in header
)
);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
$class = new class_name_for_call_cURL();
var_dump($class->call_cURL()); // output is true/false
function get_cURL() {
$url = "www.domain.com";
$token = "generated token code";
$postData = array(
"username" => "user1",
"password" => "passuser1",
"gender" => 1
);
// for sending data as json type
$fields = json_encode($postData);
$ch = curl_init($url);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json', // if the content type is json
'bearer: '.$token // if you need token in header
)
);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
var_dump(get_cURL());
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()
如果表單使用重定向、身份驗證、cookies、SSL (https) 或其他任何需要 POST 變量的完全開放的腳本,那么您將很快開始咬牙切齒。 看看Snoopy ,它完全符合您的想法,同時消除了設置大量開銷的需要。
如果您將信息傳遞到自己的網站,一個更簡單的答案是使用 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']);}
以下是 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, "");
...
?>
$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);
如果您嘗試使用 cookie 登錄網站。
這段代碼:
if ($server_output == "OK") { ... } else { ... }
如果您嘗試登錄,它可能無法正常工作,因為許多網站返回狀態 200,但發布不成功。
檢查登錄帖子是否成功的簡單方法是檢查它是否再次設置cookie。 如果在輸出中有一個 Set-Cookies 字符串,這意味着帖子不成功,它會啟動一個新會話。
此外,帖子可以成功,但狀態可以重定向而不是 200。
為確保帖子成功,請嘗試以下操作:
關注帖子后的位置,因此它將轉到帖子重定向到的頁面:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
然后檢查請求中是否存在新的 cookie:
if (!preg_match('/^Set-Cookie:\s*([^;]*)/mi', $server_output))
{echo 'post successful'; }
else { echo 'not successful'; }
最簡單的是將數據作為 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.