Reputation: 177930
I have this type of curl statement
curl -u xxx:yyy -d "aaa=111" http://someapi.com/someservice
I would like to run this varying aaa=bbb from a list
UPDATE: Code that works, built on Jimmy's code
<?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;
}
?>
Upvotes: 1
Views: 791
Reputation: 15264
In Perl, you'd probably use LWP
as it is contained in the standard distribution.
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";
}
}
Upvotes: 2
Reputation: 13614
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):
$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);
}
Upvotes: 2