3

Is it possible to get the cURL command from the PHP's object? I mean, make this:

$ch = curl_init('http://'.$host . $url);
//...
$response = curl_exec($ch);

Look like this:

curl -X POST -d http://www.google.com/

Is it possible? Is there a trick or a native method?

Victor Ferreira
  • 6,151
  • 13
  • 64
  • 120
  • 1
    http://php.net/manual/en/function.curl-getinfo.php – Marc B Sep 17 '15 at 21:44
  • i've seen this. but any of those options will give me the curl command? – Victor Ferreira Sep 17 '15 at 21:49
  • 1
    no. there's no php-in-curl-to-php-on-cli translator. php is **NOT** doing `shell_exec('curl....')`, period. it talks to the back-end curl library directly. – Marc B Sep 17 '15 at 21:49
  • Hey @Victor. The command you've mentioned (`curl -X POST -d http://www.google.com/`) is invalid. Anyway, what you want to achieve is to execute a cURL request like you do from the command line, not get a string with the command, right? – Gustavo Straube Sep 18 '15 at 01:29
  • @GustavoStraube I wanted to create a cURL object and get the command line from it. I know it's not valid, was just an example – Victor Ferreira Sep 18 '15 at 01:53
  • @VictorFerreira, have you seen my answer below? Did that help you? – Gustavo Straube Apr 11 '17 at 12:07

1 Answers1

2

It's not possible to get the command line equivalent (options) to execute the tool curl from the PHP library cURL.

Both tool and PHP library use libcurl to perform client-side URL transfers, which is a C library. But that's all. Very likely you have a PHP equivalent for most of curl options available in cURL, however, it's not a rule.

I don't think you simply would like to do requests from your application using curl, if you want so, you'd be using PHP library's. That said, there is no easy way to get what you want. Probably you'll need to build the command as a string. Something like this:

function getCurlCommand($url, $method = 'GET', array $params = null /* , ... */ )
{
    $cmd = 'curl';
    $params = [];
    if ($method !== 'GET') {
        $params[] = '-X ' . $method;
    }
    if ($data !== null) {
        $params[] = '-d ' . http_build_query($data); 
    }

    // ...

    return $cmd . ' ' . implode(' ', $params) . ' ' . $url;
}
Gustavo Straube
  • 3,744
  • 6
  • 39
  • 62