简体   繁体   English

使用 PHP 从远程服务器运行 curl

[英]Running curl from a remote server using PHP

I have this type of curl statement我有这种类型的 curl 声明

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

I would like to run this varying aaa=bbb from a list我想从列表中运行这个不同的 aaa=bbb

UPDATE: Code that works, built on Jimmy's code更新:有效的代码,建立在 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; 
}
?>

In PHP, the code would look different since you'd probably want to use the built-in cURL client rather than exec() (edited to include a loop):在 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);
} 

In Perl, you'd probably use LWP as it is contained in the standard distribution.在 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