简体   繁体   中英

PHP curl: CURLOPT_URL, CURLOPT_POST, and CURLOPT_POSTFIELDS

If I have a URL that looks like this:

$url = 'http://domain.com/?foo=bar';

And then execute curl as follows:

$resource = curl_init();
curl_setopt($resource, CURLOPT_URL, $url);
curl_setopt($resource, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($resource);
curl_close($resource);

I understand that I make this request via GET (default).

Now if I set the following option in the same scenario:

curl_setopt($resource, CURLOPT_POST, 1);

I understand it uses POST instead of GET, but does it then POST foo with a value of bar ? Or would the proper way for that be:

$url = 'http://domain.com/';
$post = 'foo=bar';
$resource = curl_init();
curl_setopt($resource, CURLOPT_URL, $url);
curl_setopt($resource, CURLOPT_POST, 1);
curl_setopt($resource, CURLOPT_POSTFIELDS, $post);
curl_setopt($resource, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($resource);
curl_close($resource);

And what happens if I do this (ie submit the value in the URL and via CURLOPT_POSTFIELDS):

$url = 'http://domain.com/?foo=bar';
$post = 'foo=bar';
$resource = curl_init();
curl_setopt($resource, CURLOPT_URL, $url);
curl_setopt($resource, CURLOPT_POST, 1);
curl_setopt($resource, CURLOPT_POSTFIELDS, $post);
curl_setopt($resource, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($resource);
curl_close($resource);

How will the data be submitted in that scenario?

The difference between POST and GET is how the server retrieves the data. As you have set CURLOPT_POST to true, the server normally receives the parameters via the CURLOPT_POSTFIELDS value (ie the parameters in the HTTP body) and presumably ignore the parameters sent in the URL string - but that really depends on the individual server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM