I'm curling a url that drops a json result. The result of the curl is always NULL though.
main.php
function getUserSettings(){
...
$json = json_encode($userSettings);
header('Content-Type: application/json');
return $json;
}
getusersettings.php
...
$api->uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : die();
$result = $api->getUserSettings();
echo $result;
...
settings.php
<?php
session_start();
if(isset($_SESSION['uid'])) {
//get the user settings
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, 'https://www.url.com/api/getstgs');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result, true);
print_r($obj);die();
}
...
generate html
...
?>
The json looks like this:
{"lcns":[{"product_name":"Addon: Addonname","license_key_decrypted":"XXXXXXXXXXXXXX","expires_at":"0000-00-00 00:00:00"}],"stgs":[{"Type":"1","Amount":"0"}]}
Per the shown code, the cURL call is expected to 'fail'.
This is because cURL makes a new request which does not automatically include session information or cookies. Such behavior can be duplicated using cURL from the command-line or a browser tab in a new incognito window. (Checking the result of web requests from other tools can diagnose a number of issues much quicker than code changes.)
The following is expected to fail the request instead of returning the desired JSON unless the session "uid" value has previously been established this request. It does not matter if there is a session "uid" value in the request which invoked cURL: the request made by cURL is separate.
$api->uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : die();
Related
I'm trying to write a simple curl function that queries the freegeoip.net site with the IP address of a site visitor. This is usually done by typing "https://freegeoip.net/csv/{IP Address}" in the browser address line. The site then processes the request and returns a csv file that can be opened or saved. I'm trying to access the csv data directly so that I can parse and use it. This is the code that I am using:
<?php
$ip=$_SERVER["REMOTE_ADDR"];
$geturl = "http://freegeoip.net/csv/".$ip;
$data = curl_get_contents($geturl);
echo ("<br>Data = '".$data."'<br>");
function curl_get_contents($url)
{
$ch = curl_init($url);
if($ch)
{
$tmp = curl_exec($ch);
curl_close($ch);
return $tmp;
}
else
{
echo "Curl not loaded!<br>";
}
}
?>
This is what I am getting back:
...,US,United States,ST,State,City,?????,America/New_York,.*****,-.****,***
Data = '1'
As you can see, my function is accessing and showing the csv data but not returning it to the $data variable. Apparently, the data is being shown when the "curl_exec($ch);" command is being executed. I want to parse and use the returned data but can't until the data is returned. What am I doing wrong?
The documentation of curl_exec() says:
Return Values
Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
What it doesn't say is explained in the documentation page of curl_setopt(), on the CURLOPT_RETURNTRANSFER option:
Option: CURLOPT_RETURNTRANSFER
Set value to: TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
That is, by default, curl_exec() outputs the body of the response it gets. In order to make it return the value and not output it, you have to use curl_setopt():
$ch = curl_init($url);
curl_exec($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
you need to add following line before curl_exec other wise the result will output instead of returning it to $tmp variable.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
You aren't telling Curl that you want the data to be returned rather than output:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
curl_setopt($ch, CURLOPT_URL, "http://freegeoip.net/csv/".$ip);
$csv=curl_exec($ch);
But this is rather verbose when, depending on your config, you can:
$csv=file_get_contents("http://freegeoip.net/csv/".$ip);
I am using file_get_contents to get the json from URLs. The same URL works sometimes and sometimes it doesn't. When it doesn't, file_get_contents does not return any error and just stops the whole script. It's too confusing.
What's error you get? It's warning or Fatal Error?
if it's warning, please add # to befor file_get_contents like: #file_get_contents
if other, please check data before execute other process
$jsondata =#file_get_contents('YOur URl');
if($jsondata){
// Process your code
}else{
//do nothing
}
What a URL is returning when the correct data is not outputted ?
1)
$json_data =file_get_contents('URl');
if($json_data){
//parse the data
}else{
//show error
}
2 to find what exactly the url returns
$json_data =file_get_contents('URl');
var_dump($json_data);
3 use cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
var_dump($obj)
I have 2 .php files
The first php creates a session:
<?php
session_start();
$_SESSION['ID'] = '1';
$_SESSION['NAME'] = 'ALIAS';
$_SESSION['TIME'] = time();
print_r($_SESSION);
The second file has the same session and if it is called from the same browser using the GET method should return the values of the session:
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == "GET"){
$key = $_GET["access_token"];
if($key=="b8bc45179e0c022a0a5e7738356549a3ebf3788c"){
$json = array("status" => 1, "msg" => $_SESSION['NAME']);
}else{
$json = array("status" => 0, "msg" => "ACCESS ERROR");
}
header('Content-type: application/json');
echo json_encode($json);
}
It is a success when I call from navigation bar from browser as follows:
https://test.com.mx/p_session.php?access_token=b8bc45179e0c022a0a5e7738356549a3ebf3788c
I get:
{"status":1,"msg":ALIAS}
but when a script from a third party:
<?php
$ch = curl_init('https://test.com.mx/p_session?access_token=b8bc45179e0c022a0a5e7738356549a3ebf3788c');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$response = curl_exec($ch);
curl_close($ch);
print_r($response);
calls from the same browser I get:
{"status":1,"msg":null}
Exist way of make this possible?
When you use sessions in PHP, a session cookie is set to the clients browser, containing a session id.
Curl, by default, doesn't keep cookies so when you call the second file, it can't access your cookies.
First, you should call the first url with curl, get the cookies it returns to you, then request the second url with these cookies. Also, you aren't even calling the first file in the first place, so it didn't even return you a cookie anyway. (even if it did, you wouldn't be able to keep it like this without options, though)
example options:
curl_setopt( $curl_handle, CURLOPT_COOKIESESSION, true);
curl_setopt( $curl_handle, CURLOPT_COOKIEJAR, $cookie);
curl_setopt( $curl_handle, CURLOPT_COOKIEFILE, $cookie);
you should call the first url with curl, keep the cookies, then call the second url.
related: PHP Curl And Cookies
google "curl php cookie" and similar for more, but this is basically it.
I wanted to try to get data from a JSON string which is loaded from another page. I currently have used Curl to get the data from the webpage but I can't acces the data in it.
I've already tried:
var_dump(json_decode($result->version, true));
var_dump(json_decode($result[3][0]["date"], true));
But this does't seem to work as it always returns NULL
$url="https://roosters.deltion.nl/api/roster?group=AO2B&start=20160125&end=20160201";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
First decode the JSON, then get the properties you want. Like this:
$yourObject = json_decode($result);
var_dump($youObject->version);
this is working for me.
<?php
$url = "https://roosters.deltion.nl/api/roster?group=AO2B&start=20160125&end=20160201";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
// Execute
$result = curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
$data = json_decode($result);
//echo $data->data[0]['date'];
echo "<pre>";
print_r($data->data[0]->date);
}
?>
if you want to get date of all index then try this in loop.
Firstly if your using GET there is no need to use CURL,
$result = file_get_contents(https://roosters.deltion.nl/api/roster?group=AO2B&start=20160125&end=20160201);
Will work just as well without any of the overhead. I suspect that your CURL isn't returning the page content so using file_get_contents() will fix it.
From a PHP page, I'm trying to POST some data to another PHP page and get data back.
Here is what I currently have:
<?php
// Initialize cURL session
$ch = curl_init('postpage.php');
// Set some options on the session
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('field1' => 'Andrew'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute post
$result = curl_exec($ch);
var_dump($result);
// Close the session
curl_close($ch);
?>
and in postpage.php:
<?php
echo 'Receipt of post request. field1:'.$_POST["field1"];
?>
All the var_dump gives me is this:
string(0) ""
Why am I not getting the text back?
Thanks!
The curl executed from your php script is not aware of the current environment, that is, you cannot use relative urls. The url you supply to curl_init must be absolute (i.e. including http://)
If this is indeed the actual initialization you're doing, the error may lie in the arguments of curl_init() which expects a fully qualified URL.
Also, you might want to employ some error diagnostics. curl_exec returns FALSE on failure. The reason why can be determined with curl_error():
$ch = curl_init( ... );
// ... some curl_setopt()
$result = curl_exec($ch);
if ($result === FALSE)
{
die("cURL error: " . curl_error($ch));
}