问题
Im a newbie im trying to get a script to trigger another script with Curl in PHP but it dosent seem to be sending the paramaters.
Is there a seperate function to append parameters?
<?php
$time = time();
$message = "hello world";
$urlmessage = urlencode( $message );
$ch = curl_init("http://mysite.php?message=$urlmessage&time=$time");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
?>
Could anyone point me in the right direction??
回答1:
You need curl_setopt() along with the CURLOPT_POSTFIELDS param. That'll POST the given params to the target page.
curl_setopt($ch, CURLOPT_POSTFIELDS, 'foo=1&bar=2&baz=3');
PS: also check http_build_query() which is handy when sending many variables.
回答2:
The accepted answer is good for POST, but what if OP wanted specifically to GET? Some REST APIs specify the http method and often it's no good POSTing when you should be GETting.
Here is a fragment of code that does GET with some params:
$endpoint = 'http://example.com/endpoint';
$params = array('foo' => 'bar');
$url = $endpoint . '?' . http_build_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
This will cause your request to be made with GET
to http://example.com/endpoint?foo=bar
. This is the default http method, unless you set it to something else like POST
with curl_setopt($ch, CURLOPT_POST, true)
- so don't do that if you specifically need to GET.
If you need to use one of the other http methods (DELETE or PUT for example) then use curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method)
. This also works for GET and POST.
回答3:
you need set CURLOPT_POST
as true
and CURLOPT_POSTFIELDS
=> parameters
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
a suggestion,set 'CURLOPT_RETURNTRANSFER
', as true to return the transfer as a string of the return value of curl_exec($ch)
instead of outputting it out directly
来源:https://stackoverflow.com/questions/6367761/php-curl-adding-params