Php Curl adding Params - php

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

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.

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.

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

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,

Related

Send data GET lost data with hashmark# [duplicate]

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

error using php and curl sending api request

I'm sending API request using curl and php. The first one works but not the second one. Error shows that postfields data is empty, or the whole request is null. I'm confused.
this is my code
$request_id = "aaa7996d-8d5c-4116-b759-6afb1c84ff39";
$res_url = "http://opeapi.ws.pho.to/getresult";
$res_data = array('request_id'=>$request_id);
$res_ch = curl_init();
curl_setopt($res_ch, CURLOPT_URL, $res_url);
curl_setopt( $res_ch, CURLOPT_POST, true );
curl_setopt($res_ch, CURLOPT_POSTFIELDS,$res_data);
curl_setopt($res_ch, CURLOPT_RETURNTRANSFER, 1);
$results = curl_exec($res_ch);
curl_close($res_ch);
var_dump($results);
but the results returned:
SecurityError612Bad, invalid or empty REQUEST_ID parameter.
Here are a few things I tries:
$res_data = array('request_id'=>urlencode($request_id));
$res_data = "request_id=".$request_id;
$res_data1 = json_encode($res_data);
$res_data1 = http_build_query($res_data);
$res_url = "http://opeapi.ws.pho.to/getresult?request_id=aaa7996d-8d5c-4116-b759-6afb1c84ff39";
none of them really works.
but the curious thing is I have another request before this one. Also using Pho.to API. I processed a photo using their parameters and got the result using curl and php. That one works (that's why I get the request_id to obtain the processing result)
this is my former request. it works, why not the second one??
$data = '(some xml parameters)';
$sign_data = hash_hmac('SHA1', $data,'***');
$url = "http://opeapi.ws.pho.to/addtask";
$posting = array('app_id'=>'***','key'=>'***','sign_data'=>$sign_data,'data'=>$data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_POSTFIELDS,$posting);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
error message suggest there is no request_id...
or the whole request $curl is null...
Any help or suggestion will be deeply appreciated!!! Please~Thanks!!!
I figured it out!
It turns out I'm supposed to use a get request (in order to get my data), not a post.
So I directly write my url to...http://?request_id=, and deleted all the option lines about request (because the default process is get, not post), and it worked!
took me 7 hours to figure this out...TAT

How to send OData to RESTful API in PHP cURL Request

I am trying to send OData parameters in a GET request to a RESTful API using PHP. A properly formatted OData request to this service looks like so:
https://myapi.org/endpoint?filter=family_name eq 'Doe'
It seems like I should just append these variables to the end of my CURLOPT_URL before sending the request, but the API service doesn't seem to receive the OData.
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('OSDI-API-Token:xxxxxxxxxxxx'));
curl_setopt($ch, CURLOPT_URL, "https://myapi.org/endpoint?filter=family_name eq 'Doe'");
$response = curl_exec($ch);
curl_close($ch);
echo "<pre>";
print_r($response);
echo "</pre>";
Output is NULL. This seems like a strange response considering that this same request with identical headers and the same Odata URL searches and finds the correct data in the API's browser.
Can anybody confirm whether or not this is the correct way to send OData parameters through a cURL request?
Appending the OData parameters directly to the CURLOPT_URL doesn't work, because it doesn't form a valid URL. The spaces and quotes need to be escaped as family_name%20eq%20%27Doe%27 or family_name+eq+%27Doe%27.
A simpler way would be to use http_build_query() to attach the parameters to the URL prior to setting CURLOPT_URL:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('OSDI-API-Token: xxxxxxxxxx'));
$api_request_parameters = array('filter'=>"family_name eq 'Doe'");
$api_request_url = "https://myapi.org/endpoint";
$api_request_url .= "?".http_build_query($api_request_parameters);
$curl_setopt($ch, CURLOPT_URL, $api_request_url);
$response = curl_exec($ch);
curl_close($ch);
I know that this question has been closed for a while but just to complement the answer with more points above, you need to declare '$' in the filter key if you are going to use http_build_query (), for example:
$api_request_parameters = array ('$filter' => "family_name eq 'Doe'");
$api_request_url. = "?". http_build_query ($api_request_parameters);
If you declare without '$' in filter, the filter will not work correctly and the return of this will be all records and in some cases it may return an error.
If you choose not to use http_build_query () you need to escape all spaces, for example, let's say the request is this:
https://myapi.org/endpoint?filter=family_name eq 'Doe test 1234'
The parameters would look like this:
https://myapi.org/endpoint?filter=family_name+eq+%27Doe%20test%201234%27

How to use an array in an API using curl

I am trying to access the cdnify API to purge cache for an individual file ( https://cdnify.com/learn/api#purgecache )
This is my current code
$cdn_api_user = env('CDNIFY_API');
$cdn_api_password = env('CDNIFY_API_PASS');
$cdn_api_resource = env('CDNIFY_API_RESOURCE');
$cdnifyapicacheurl = 'https://' . $cdn_api_user . ':' . $cdn_api_password . '#' . 'cdnify.com/api/v1/resources/' . $cdn_api_resource . '/cache';
return print $cdnifyapicacheurl;
$fields = array(
'files' => $storageFilename
);
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $cdnifyapicacheurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
//unless you have installed root CAs you can't verify the remote server's certificate. Disable checking if this is suitable for your application
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//perform the HTTP DELETE
$result = curl_exec($ch);
//close connection
curl_close($ch);
the env variables at the top call in my api key, password, and resource for the url. I have verified I am logging in via that url.
When I debug through my code i get an error on
$fields = array(
'files' => $storageFilename
);
which is Array to string conversion.
The $storageFilename variable returns
$storageFilename = "/" . $directoryname . "/" . $asset->name;
which is the filename required for the API call of DELETE.
I can't get passed that $fields array. The other stuff below it may or may not run properly. I am just stuck on how to write this part out.
CURLOPT_POST is just there to indicate if some post data should be included in the HTTP request, so its value should a boolean (true or false).
If your array $fields represents the data to be posted, you need to use http_build_query() to assign them to CURLOPT_POSTFIELDS:
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
There is a return in your code that stops the code the curl code is not getting executed remove it or comment it using // and try again and CURLOPT_POST value is boolean true or false that indicates if you want to use post method or not, your CURL code is really messed up you want to use http delete method or post method ?? You can only use one method, please learn how to use php cURL first http://php.net/manual/en/book.curl.php

Post to another page within a PHP script

How can I make a post request to a different php page within a php script? I have one front end computer as the html page server, but when the user clicks a button, I want a backend server to do the processing and then send the information back to the front end server to show the user. I was saying that I can have a php page on the back end computer and it will send the information back to the front end. So once again, how can I do a POST request to another php page, from a php page?
Possibly the easiest way to make PHP perform a POST request is to use cURL, either as an extension or simply shelling out to another process. Here's a post sample:
// where are we posting to?
$url = 'http://foo.com/script.php';
// what post fields?
$fields = array(
'field1' => $field1,
'field2' => $field2,
);
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
// execute post
$result = curl_exec($ch);
// close connection
curl_close($ch);
Also check out Zend_Http set of classes in the Zend framework, which provides a pretty capable HTTP client written directly in PHP (no extensions required).
2014 EDIT - well, it's been a while since I wrote that. These days it's worth checking Guzzle which again can work with or without the curl extension.
Assuming your php install has the CURL extension, it is probably the easiest way (and most complete, if you wish).
Sample snippet:
//set POST variables
$url = 'http://domain.com/get-post.php';
$fields = array(
'lname'=>urlencode($last_name),
'fname'=>urlencode($first_name),
'email'=>urlencode($email)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
Credits go to http://php.dzone.com.
Also, don't forget to visit the appropriate page(s) in the PHP Manual
index.php
$url = 'http://[host]/test.php';
$json = json_encode(['name' => 'Jhonn', 'phone' => '128000000000']);
$options = ['http' => [
'method' => 'POST',
'header' => 'Content-type:application/json',
'content' => $json
]];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
test.php
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
echo $data['name']; // Jhonn
For PHP processing, look into cURL. It will allow you to call pages on your back end and retrieve data from it. Basically you would do something like this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL,$fetch_url);
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt ($ch,CURLOPT_USERAGENT, $user_agent;
curl_setopt ($ch,CURLOPT_CONNECTTIMEOUT,60);
$response = curl_exec ( $ch );
curl_close($ch);
You can also look into the PHP HTTP Extension.
Like the rest of the users say it is easiest to do this with CURL.
If curl isn't available for you then maybe
http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
If that isn't possible you could write sockets yourself
http://petewarden.typepad.com/searchbrowser/2008/06/how-to-post-an.html
For those using cURL, note that CURLOPT_POST option is taken as a boolean value, so there's actually no need to set it to the number of fields you are POSTing.
Setting CURLOPT_POST to TRUE (i.e. any integer except zero) will just tell cURL to encode the data as application/x-www-form-urlencoded, although I bet this is not strictly necessary when you're passing a urlencoded string as CURLOPT_POSTFIELDS, since cURL should already tell the encoding by the type of the value (string vs array) which this latter option is set to.
Also note that, since PHP 5, you can use the http_build_query function to make PHP urlencode the fields array for you, like this:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
Solution is in target="_blank" like this:
http://www.ozzu.com/website-design-forum/multiple-form-submit-actions-t25024.html
edit form like this:
<form method="post" action="../booking/step1.php" onsubmit="doubleSubmit(this)">
And use this script:
<script type="text/javascript">
<!--
function doubleSubmit(f)
{
// submit to action in form
f.submit();
// set second action and submit
f.target="_blank";
f.action="../booking/vytvor.php";
f.submit();
return false;
}
//-->
</script>
Although not ideal, if the cURL option doesn't do it for you, may be try using shell_exec();
CURL method is very popular so yes it is good to use it. You could also explain more those codes with some extra comments because starters could understand them.

Categories