I need to create a new PHP HTTP Request within my code. It returns a json-encoded array of data. How do I create a new HTTP Request and not redirect to that location?
Thanks.
assuming you're trying to get a json file and put it into an array:
$content = file_get_contents('http://www.example.com/test.json');
$json_array = json_decode($content);
print_r($json_array)
This is what you are looking for: http://codular.com/curl-with-php
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://stackoverflow.com'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
//For testing only
print_r('<pre>');
print_r($resp);die();
Related
I want to retrieve the final URL formed using a CURL request, but none of them work what I want to retrieve.
for example - I directly paste an API call in the browser address bar, it works, but when using CURL request I get some errors.
To find that I want to retrieve the final request URL formed by CURL or all the request parameters included in CURL Request.
The various methods I have tried is like:
$ch = curl_init();
$f = fopen('request.txt', 'w');
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_STDERR => $f,
));
$response = curl_exec($ch);
fclose($f);
curl_close($ch);
Alternatively -
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$data = curl_exec($ch);
var_dump($data);
var_dump(curl_getinfo($ch));
Thanks.
Update:
My request should form url like this:
https://api-3t.sandbox.paypal.com/nvp/?METHOD=SetExpressCheckout&VERSION=86&PWD=9mypassword&USER=my_user_name&SIGNATURE=my_api_signature&L_BILLINGTYPE0=RecurringPayments&L_BILLINGAGREEMENTDESCRIPTION0=FitnessMembership&cancelUrl=http://localhost/recurring-payment/index.php&returnUrl=http://localhost/recurring-payment/review.php
Now I want to get all the info in the above URL being submitted to Paypal API.
So I can retrieve this info being sent through CURL.
I am currently trying to get a simple HTTP JSON response from a website.
When I look at the page when I use Google Chrome:
{"columns":[{"name":"xx","dataType":"varchar","size":255,"nullable":true},{"name":"xx","dataType":"varchar","size":255,"nullable":true},{"name":"xx","dataType":"decimal","size":17,"nullable":true},{"name":"xx","dataType":"varchar","size":255,"nullable":true},{"name":"xx","dataType":"varchar","size":4,"nullable":true},{"name":"xx","dataType":"varchar","size":2,"nullable":true},{"name":"xx","dataType":"varchar","size":20,"nullable":true}],"rows":[["xxxxx","xxxx/xxxx","xxxx","Yacouba","5xx","xx","xxxxx"]]}
However when I use the following php code:
<?php
$json_url = "xxxx"; // url is something else but privacy reasons etc
// Initializing curl
$ch = curl_init();
// Configuring curl options
$options = array(
CURLOPT_URL => $json_url,
CURLOPT_POST => FALSE
);
// Setting curl options
curl_setopt_array($ch, $options);
// Getting results
$result = curl_exec($ch); // Getting jSON result string
curl_close($ch);
json_decode($result);
var_dump($result);
and then the output is as fallows:
‹ì½`I–%&/mÊ{JõJ×àt¡€`$Ø#ìÁˆÍæ’ìiG#)«*ÊeVe]f#Ìí¼÷Þ{ï½÷Þ{ï½÷º;N'÷ßÿ?\fdlöÎJÚÉž!€ªÈ?~|?"~ñGÓª\/–ÍG¾÷‹?Zf‹ü£Gͪ¦)òú÷/³I^~4úh–µÙ›ë¾ºÌêé<«éæø}°wÿþè£åº¤¦%ýÙÖëü—Œz€–Y¶ø8—U=ËëbyñûÏòIÑæëú÷¯Vù²i³l9Ïòi±ÈJx÷Á&ü´E°iëŒÞÕyóû¯¦¿ÿ²n6CÛ¿=¬²½ ØÞmFXçeÖ9¡v°´ï>ª«+pÈ÷>ÚýôÓ{Ôúm±l&y}‘/ïþ>Ù´ZO2úpoow´»C¿¹ÏîïìJ?žŸÐ?;;;û÷÷?Ýûèûßÿ%ÿOÿÿzbool(true)
What could the problem be?
I fix it! :D with:
CURLOPT_ENCODING => ''
I am trying to learn PHP coming from some very basic Java experience but I am confused about variables in PHP and being reused in the same script. I have the below code which works without issue somehow even though I have multiple values for certain variables such as $url,$curl,$resp how is this working? Is it just being over written as the script executes?
<?php
$zip = $_GET["ziphtml"];
$url = "http://api.wunderground.com/api/4339efkeyf17a9/forecast10day/q/19115.json";
$curl = curl_init();
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
$json_string = $resp;
$parsed_json = json_decode($json_string);
$forecastp2 = $parsed_json->{'forecast'}->{'txt_forecast'}->{'forecastday'}[1]->{'title'};
$forecastp3 = $parsed_json->{'forecast'}->{'txt_forecast'}->{'forecastday'}[2]->{'title'};
$forecastp4 = $parsed_json->{'forecast'}->{'txt_forecast'}->{'forecastday'}[3]->{'title'};
$forecastp5 = $parsed_json->{'forecast'}->{'txt_forecast'}->{'forecastday'}[4]->{'title'};
$forecastp6 = $parsed_json->{'forecast'}->{'txt_forecast'}->{'forecastday'}[5]->{'title'};
$forecastp7 = $parsed_json->{'forecast'}->{'txt_forecast'}->{'forecastday'}[6]->{'title'};
$zip = $_GET["ziphtml"];
$url = "http://api.wunderground.com/api/4dgg345353vdryteyfg339ekey7a9/geolookup/conditions/q/IA/".$zip.".json";
$curl = curl_init();
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
$json_string = $resp;
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'current_observation'}->{'display_location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperatdure in ${location} is: ${temp_f}\n<br /> and it is now ${forecastp2}\n<br /> and then it will be ${forecastp3}\n<br /> and then ${forecastp4}\n<br />and then ${forecastp5}\n<br />and then ${forecastp6}\n<br />and then ${forecastp7}";
?>
It is just overwritten.
Java does the same, but Java checks type, so you cannot reassign values as freely.
A variable is a name for a location in memory. When you store a new value in that location, the old value is lost and the name now refers to the new value.
I have done some research regarding on how to use file_get_content with post. And I have also read this one which is I honestly don't understand since I am not that familiar with PHP. Below is my php code in getting my json and used it for my ajax request, using methog GET.:
<?php
echo(file_get_contents("http://localhost:8001/" . $_GET["path"] . "?json=" . urlencode($_GET["json"])));
?>
Now, I am using method POST and I dont know how to modify my php code to post my data from my javascript. Below is my data which I wanted to post in my url request (that is also what I used as json in method GET):
{"SessionID":"9SQLF17XcFu0MTdj5n",
"operation":"add",
"transaction_date":"2011-7-28T00:00:00",
"supplier_id":"10000000108",
"wood_specie_id":"1",
"lines": [{"...":"...","..":"..."},{"...":"...","..":"..."}],
"scaled_by":"SCALED BY",
"tallied_by":"TALLIED BY",
"checked_by":"CHECKED BY",
"total_bdft":"23.33",
"final":"N"}
I just need to change this code
echo(file_get_contents("http://localhost:8001/" . $_GET["path"] . "?json=" . urlencode($_GET["json"])));
with POST to send my post my data.
EDIT:
I need to produce a request like this:
http://localhost/jQueryStudy/RamagalHTML/processjson.php?path=getData/supplier?json={"SessionID":"KozebJ4SFqdqsJtRpG6t1o3uQxgoeLjT"%2C"dataType":"data"}
You can pass a Stream Context as the third argument to file_get_contents. With the Stream Context, you can influence how the HTTP request will be made, e.g. you can change the Method, add Content or arbirtrary headers.
file_get_contents($url, false, stream_context_create(
array (
'http' => array(
'method'=>'POST',
'header' => "Connection: close\r\nContent-Length: $data_len\r\n",
'content'=>$data_url
)
)
));
After each request, PHP will automatically populate the $http_response_header which will contain all the information about the request, e.g. Status Code and stuff.
$data_url = http_build_query (array('json' => $_GET["json"]));
$data_len = strlen ($data_url);
echo file_get_contents("http://localhost:8001/" . $_GET["path"], false, stream_context_create(
array (
'http' => array(
'method'=>'POST',
'header' => "Connection: close\r\nContent-Length: $data_len\r\n",
'content'=>$data_url
)
)
));
What you need is cURL.
Example:
$dataString = "firstName=John&lastname=Smith";
$ch = curl_init();
//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,2); // number of variables
curl_setopt($ch,CURLOPT_POSTFIELDS,$dataString);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
If i understand you correctly(I might not) you should use CURL.
CURL is the way to submit POST requests within PHP. (but it is not the only way)
What you are doing is sending the data by the GET method
some think like this, please read about it, this one will not work out of the box
<?php
$ch = curl_init("http://localhost:8001/" . $_GET["path"] );
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "json=".urlencode($_GET["json"]));
curl_exec ($ch);
curl_close ($ch);
?>
I am completely new PHP and want a client program to call an URL web service.I am using file_get_content to get the data.How do add additional headers to the request made using file_get_content.
I also was thinking of using cURL. I wanted to know how cURL can be used to do a GET request.
You can add headers to file_get_contents, it takes a parameter called context that can be used for that:
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => "Host: www.example.com\r\n" .
"Cookie: foo=bar\r\n"
)
));
$data = file_get_contents("http://www.example.com/", false, $context);
As for cURL, the basic example from the PHP manual shows you how to perform a GET request:
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>