Home » Php » linux – PHP Curl with –data flag?

linux – PHP Curl with –data flag?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Can someone write a PHP script that reproduces the functionality of this linux shell command?

curl -X POST -u "USERNAME:PASS" \
    -H "Content-Type: application/json" \
        --data '{"aps": {"alert": "this is a message"}}' \
            https://mywebsite.com/push/service/

I think I almost got it in my code, but I’m not sure how to handle the --data attribute.

Here’s what my code looks like so far:

    $headers = array();
    $headers[] = "Content-Type: application/json";
    $body = '{"aps":{"alert":"this is a message"}}';

    $ch = curl_init();
    // Set the cURL options
    curl_setopt($ch, CURLOPT_URL,            "https://mywebsite.com/push/service/");
    curl_setopt($ch, CURLOPT_USERPWD,        "USERNAME:PASSWORD");
    curl_setopt($ch, CURLOPT_POST,           TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS,     $body);
    curl_setopt($ch, CURLOPT_HTTPHEADER,     $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

    // Execute post
    $result = curl_exec($ch);

    // Close connection
    curl_close($ch);
    print_r($result);
How to&Answers:

example in:

http://code.google.com/apis/gdata/articles/using_cURL.html

curl https://www.google.com/accounts/ClientLogin \
--data-urlencode [email protected] --data-urlencode Passwd=new+foundland \
-d accountType=GOOGLE \
-d source=Google-cURL-Example \
-d service=lh2

Answer:

A general rule: use the “–libcurl example.c” option to get curl to generate source code for a C program that would use libcurl. The API is very similar to the PHP/CURL one as you will see and you should then quickly realize that –data translates to CURLOPT_POSTFIELDS.

Oh, and you’ll note that the -X usage is completely superfluous! 😉