Christopher
Christopher

Reputation: 13157

Php Curl adding Params

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

Upvotes: 38

Views: 146525

Answers (4)

user14135278
user14135278

Reputation:

Here is A Simple Solution for this.

 $mobile_number = $_POST['mobile_number'];
 $sessionid = $_POST['session_id'];
    CURLOPT_URL => 'https://xxyz.jkl.com/v2.0/search?varible_that_you_want_to_pass='.$mobile_number.'&requestId=1616581154955&locale=en-US&sessionId='.$sessionid,

Upvotes: -2

Coder
Coder

Reputation: 3103

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.

Upvotes: 83

The Mask
The Mask

Reputation: 17427

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

Upvotes: 13

ChrisR
ChrisR

Reputation: 14447

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.

Upvotes: 28

Related Questions