簡體   English   中英

使用 PHP 從遠程服務器運行 curl

[英]Running curl from a remote server using PHP

我有這種類型的 curl 聲明

curl -u xxx:yyy -d "aaa=111" http://someapi.com/someservice

我想從列表中運行這個不同的 aaa=bbb

更新:有效的代碼,建立在 Jimmy 的代碼之上

<?PHP
$data = array('Aaa', 'Bbb', 'Ccc');
echo $data;    
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); //Fixes the HTTP/1.1 417 Expectation Failed Bug

curl_setopt($ch, CURLOPT_USERPWD, "xxx:yyy");

foreach ($data as $param) {
    curl_setopt($ch, CURLOPT_URL, 'http://...?aaa='.$param);
    $response = curl_exec($ch);
    echo "<hr>".$response; 
}
?>

在 PHP 中,代碼看起來會有所不同,因為您可能希望使用內置的 cURL 客戶端而不是exec() (已編輯以包含循環):

$data = array('111', '222', 'ccc');    

foreach ($data as $param)
{
    $ch = curl_init();

    $params = array('aaa' => $param);

    curl_setopt($ch, CURLOPT_URL, 'http://someapi.com/someservice');
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, "xxx:yyy");

    /* used for POST
    curl_setopt($ch, CURLOPT_POST, true); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    */

    // for GET, we just override the URL
    curl_setopt($ch, CURLOPT_URL, 'http://someapi.com/someservice?aaa='.$param);

    $response = curl_exec($ch);
} 

在 Perl 中,您可能會使用LWP ,因為它包含在標准發行版中。

use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request::Common;

my $host = 'localhost'; # 'someapi.com';
my $url  = "http://$host/someservice";

my $ua = LWP::UserAgent->new( keep_alive => 1 );
$ua->credentials( $host, 'your realm', 'fridolin', 's3cr3t' );

for my $val ( '111', '222', '333' ) {
    my $req = POST $url, [aaa => $val];
    $req->dump; # debug output
    my $rsp = $ua->request( $req );
    if ( $rsp->is_success ) {
        print $rsp->decoded_content;
    } else {
        print STDERR $rsp->status_line, "\n";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM