1

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; 
}
?>

2 Answers 2

2

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);
} 
Sign up to request clarification or add additional context in comments.

4 Comments

Okee, that is acceptable. Can you do me one with more than one aaa ? i.e. aaa=111, aaa=222, aaa=ccc and a for loop with the response? - thanks
Thanks - can't I move the curl_init and all the setopts except the postfields outside the loop?
You can try it - I'm not sure how cURL builds that object and if you need to reinitialize it each time.
@Jimmy, I get Expect: 100-continue so can we make it a GET instead of POST?
2

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";
    }
}

1 Comment

Thanks - I think I will stay in PHP if this kind of complexity is needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.