Get and decode json with php - php

I'm sure this is similar to other questions, but I have tried the solutions, and couldn't get it to work.
I'm trying to get the location of an IP address, decode the json, and print it. I actually plan to put it into a database, but Im not even sure why I cant get anything to print to the screen.
$ip = $_SERVER['REMOTE_ADDR'];
$json = file_get_contents("http://api.hostip.info/get_json.php?ip=".$ip);
$local = json_decode($json,true);
thanks.

A. When you mean I cant get anything to print to the screen. definitely you can get anything because you did not output anything to screen.
error_reporting(E_ALL);
$ip = $_SERVER['REMOTE_ADDR'];
$json = file_get_contents("http://api.hostip.info/get_json.php?ip=".$ip);
$local = json_decode($json,true);
echo $local['city'] ;
print $local['country_name'] ;
var_dump($local);
B. It would also mean that allow_url_include set to Off which would not allow file_get_contents load a information from another domain

Firstly, the code you've provided does not actually print anything, which would explain why you're getting a blank screen. I assume you're doing something like echo $local; later in the program, but if not, that'll be the problem.
Assuming that isn't the issue....
Two possibilities:
file_get_contents() is returning an error.
json_decode() is returning an error.
Firstly, you should add some additional error trapping in your code to determine which one is the problem.
If you have PHP set to not display errors, consider switching them on so you can see any errors that are generated. Or else look at your server log to see the errors.
file_get_contents() may fail if the URL is invalid. It may also fail if your PHP installation is set to not allow URLs via the file handling functions. If this is the case you'll need to change your php.ini settings. If you can't do that, you'll have to load the file via a different method (eg Curl).
json_decode() is only likely to fail if the string it gets is invalid JSON. You should check the output of the URL to confirm that it looks right, and check it something like firebug to ensure it is valid.
Hope that helps.

Related

where does this URL need urlencoding?

I hosted a website i worked on on amazon web services, and for some reason some things dont work compared to when I run it locally on localhost.
of those things are the
if (array_key_exists("error", $json))
function and
the file_get_contents function.
Ive commented out the array key exists part and that solved the issue, at least for that part of logging in, until i get to the view documents page where a slim application error displays
failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
and the issue for that lies in the viewdocspage.php file, particularly this code:
<?php
$raw = file_get_contents("http://cosoft.us-east-1.elasticbeanstalk.com/cosoft/mywiki/api.php?action=query&list=allpages&format=json");
$pages_response = json_decode($raw, true);
$pages_array = $pages_response["query"]["allpages"];
$page_titles = [];
I looked and read up on many threads that the issue lies with the file_get_contents in which the URL contains special characters, such as spaces (which mine doesnt have) and so needs to be encoded, using urlencode (or rawurlencode..?)
now ive tried encoding the whole url like this:
$raw = file_get_contents(urlencode("http://cosoft.us-east-1.elasticbeanstalk.com/cosoft/mywiki/api.php?action=query&list=allpages&format=json"));
but that resulted in this error:
slim error
Message: file_get_contents(http%3A%2F%2Fcosoft.us-east-1.elasticbeanstalk.com%2Fcosoft%2Fmywiki%2Fapi.php%3Faction%3Dquery%26list%3Dallpages%26format%3Djson): failed to open stream: No such file or directory
I figured that this may happen since I read that not all the URL should be wrapped by this encoding, but heres where Im stuck: which part of the url do i use the encoding on? the only special characters i keep coming accross regarding this error is spaces, but i dont have any spaces, so its something else which i dont know what it is...
Help is appreciated, thanks!
You would just need to url_encode the parameters. Say you had a value $value='My name is earl'
If you wanted to pass this value as a parameter in your url
http://somesite.com/?name=$value there would be spaces in the value that is url_encoded. So if you encode it as 'http://somesite.com/?name='.urlencode($value), when this is encoded the value will turn into My+name+is+earl
Reading resources from a URL may be restricted by the server's configuration.
http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen
You should use CURL for this.

Is there any PHP configuration for passing JSON object to android?

I am trying to send JSON object from PHP web service to my android app. Initially for checking if my PHP file returns the JSON value, I typed the url in browser and got correct value as desired. To check my android code, I executed the code using correct host url but got only '[]' as output in logcat. For debugging purpose, I created a free web hosting and database in hosthinger.com. This time the exact same php and android code worked fine, giving me the desired output. List of things we did to ensure there is no mistake:
Checked the collation of database in both hostings (utf8_unicode_ci)
Both the hosting returned correct value in browser.
Is there any specific PHP configuration for JSON objects?. Or am I missing any header information? I'm not getting a clue why code is working perfectly in one hosting and not in the other.
Here is my PHP code:
<?php
include ('mysqlconnection.php');
$mobile = $_POST['mobile_number'];
$output = array();
$query="select name,status from content;";
$sql = mysql_query($query);
while($row = mysql_fetch_assoc($sql)) {
$output[]= array( 'imagename' => $row['name'], 'status' => $row['status'] );
}
echo json_encode($output);
?>
May be you need to specify content.type in your php:
header('Content-Type: application/json');
You should use an output buffer with a application/json header, instead of just echoing the json_encode() output.
Some servers tend to give errors when you're working with MySQL, check the configurations. And do not use mysql_* functions, use PDO or at least mysqli instead.
You should check for possible errors in your code, check your connection, query results etc.,THEN you can generate a JSON to give output.
Make sure your server's error_reporting is set to 0. Sometimes servers print out warnings, notices and error messages that messes up your output.
You can use Google Chrome's PostMan Extension to view the results of your web service. It also shows output as json parsed.

Can't get content with file_get_contents function

I want to get movie Rating from IMDB website.
For example, I have a url http://p.media-imdb.com/static-content/documents/v1/title/tt1520211/ratings%3Fjsonp=imdb.rating.run:imdb.api.title.ratings/data.json
Run it and you can see the movie rating is 8.7 and I wan to get it, so I used this query:
$s="http://p.media-imdb.com/static-content/documents/v1/title/tt1520211/ratings%3Fjsonp=imdb.rating.run:imdb.api.title.ratings/data.json";
$s = file_get_contents($s);
$s=explode('rating":',$s);
$s=explode(',"rating',$s[1]);
echo $s[0];
But it doesnt work and I don't know why!
I am checking the script out but uhm ye your array contains nothing check it with: print_r($s)
the output is:
Array ( [0] => )
updated
When you show the content it shows:
‹5KOÃ0„ÿJµ'šÄvÞ9U‚.‰³›LÁ¢y`o*UUþ;v ·õÎìÌg3ôÇØj6ãgl—ñáF‡¬©¹Ñ4#ÓH µ†ÏxÛlŽödñ³ÀñKï¥4Óe*€èˆ2¤DÕŠH×U‘zÔ"‡?q°Ó¡5^5i\gÕ’Ü´Ø¡ðÀ×Ùd“žMÌ¡õŸ.ԚЗlÛ„YæJ()/l«€ù…݇>{ÿKí_0_Þa BÔÚR£„{êôè¿æ lx¤­š*.ï§iÙC—…Rb]1“$æ6
so your explode will also be checked to that string.
Code:
$s="http://p.media-imdb.com/static-content/documents/v1/title/tt1520211/ratings%3Fjsonp=imdb.rating.run:imdb.api.title.ratings/data.json";
$s = file_get_contents($s);
/*$s=explode('"rating":',$b);
$s=explode('"rating":',$b[1]);
print_r($s);*/
print($s);
updated:
also check the code with JSONLint
it seems like it has an error
I think you can find more in this question for your answer:
json to php array using file get contents
I assume the PHP.ini setting allow_url_fopen is disabled, which means that remote URIs (ie http(s), etc) can not be opened using the file family functions (fopen,..)
Please also refer to its config value description according to which it is a system wide setting, so I think you can not override it using ini_set().
Alternatively you could use the cURL extension, for details on how to use it please refer to its documentation.
Please run php info to check if the allow_url_fopen is set to ON
php_info();
But use the CURL for getting the content, which simulating an actual web client.
Do not turn on this option, because it's not a good for security purposes

Ajax issues, Invalid JSON

I'am building simple Ajax application (via jquery). I have strange issue. I found where the problem is, but I don't know how to solve it.
This is simple server-side php code:
<?php
require('some.php');
$return['pageContent'] = 'test';
echo(json_encode($return));
?>
On the client side, the error "Invalid JSON" is thrown.
I have discovered that if I delete require function, everything work fine.
Just for information, the "some.php" is an empty php file. There is no error when I open direct php files.
So, conclusion: I cant use require or include function if I want to use ajax?
Use Firebug to see what you're actually getting back during the AJAX call. My guess is that there's a PHP error somewhere, so you're getting more than just JSON back from the call (Firebug will show you that). As for your conclusion: using include/require by itself has absolutely no effect on the AJAX call (assuming there are no errors).
Try changing:
<?php
require('some.php');
$return['pageContent'] = 'test';
echo(json_encode($return));
?>
To:
<?php
$return = array(
'pageContent' => 'test'
);
echo json_encode($return);
?>
The problem might have to do with $return not being declared as an array prior to use.
Edit: Alright, so that might not be the problem at all. But! What might be happening is you might be echoing out something in the response. For example, if you have an error echoing out prior to the JSON, you'd be unable to parse it on the client.
if the "some.php" is an empty php file, why do you require it at all?!
require function throws a fatal error if it could't require the file. try using include function instead and see what happens, if it works then you probably have a problem with require 'some.php';
A require call won't have any effect. You need to check your returned output in Firebug. If using Chrome there is a plugin called Simple REST Client. https://chrome.google.com/extensions/detail/fhjcajmcbmldlhcimfajhfbgofnpcjmb through which you can quickly query for stuff.
Also, it's always good to send back proper HTTP headers with your response showing the response type.
It's most likely the BOM as has been discussed above. I had the same problem multiple times and used Fiddler to check the file in hex and noticed an extra 3 bytes that didn't exist in a prior backup and in new files I created. Somehow my original files were getting modified by Textpad (both in Windows). Although when I created them in Notepad++ I was fine.
So make sure that you have your encoding and codepages set up properly when you create, edit, and save your files in addition to keeping that consistent across OSes if you're developing on windows let's say and publishing to a linux environment at your hosting provider.

PHP Function 'return' not returning

This is a bit of an oddity for me. PHP is my forte, and I can normally figure out any issue I encounter.
I have a custom framework that I have been using for years. I have taken it upon myself to rewrite it, and I'm doing everything essentially the same that I was before. The problem lies in the following construct:
function ModPages_GetPage() {
$page = ModPages_GetPageByName($_GET['page_name']);
if($page != false) {
include(TPL_DIR.'pages/pages.view.php');
} else {
ErrorMessage('Invalid Page', 'The selected page could not be found.');
}
}
function ModPages_GetPageByName($page_name = null) {
$db = new Database;
$query = '
SELECT *
FROM pages
WHERE page_name = "'.CleanStr($page_name).'"
AND page_enabled = "yes"
LIMIT 1
';
$page = $db->GetRow($query);
return $page;
}
This code is being called with 'home' for the value of $_GET['page_name']. The call to ModPages_GetPageByName() is working fine, but the value of $page in ModPages_GetPage() isn't getting set. Matter of fact, any debugging statements thrown in after that call are failing to display anything.
I have display_errors set to on, and error_reporting set to E_ALL. I get a couple notices from my Database class, but that's it.
Running the script at a shell fails to produce any errors. When using strace, I do see the process spits out an 'exit_group(255)'.
This one has me quite baffled. I could sure use some direction on this.
I would think it's your query, shouldn't you just return the page name instead of star? as star (*) would return an array which is probably being passed back as the value? just my guess.
$query = '
SELECT *
FROM pages
WHERE page_name = "'.CleanStr($page_name).'"
AND page_enabled = "yes"
LIMIT 1
';
if you do a print_r on the $page return I would think it should be an array
$page = $db->GetRow($query);
echo "Page:<pre>".print_r($page,true)."</pre><br />\n";
Then maybe return something like this
return $page['page_name_field'];
ok before we get to a solution can we first make sure that before setting the $page variable, first just echo $_GET['page_name'] to see if there is a value being received.
PK
Does your script stop right after your database call, or just doesn't display any output?
If the first is true, then it looks like a fatal error. With E_ALL, it should be displayed, are you sure both display_errors and error_reporting are as you say at that point, and that the GetRow function doesn't alter them in any way? If so, maybe there's something in the Apache error log (PHP errors are sometimes logged there).
If the latter is true I'm thinking about an exception being thrown in a method that is being called, and caught in a higher level function. To check this you can put the database call (ie: the point where things go wrong) inside a try/catch block and see if you reach the catch block.
I would try following:
replace $_GET with $_REQUEST (maybe your form is using POST?)
do a print_r to check contents of your variables.
use mysql_error to view any errors, or print your mysql query in your browser, copy/paste it in phpmyadmin, is it returning anything? error.. data?
something similar happend to me once, my framework was encoded in ANSI and my calling php file was UTF8+BOM... I changed everything to UTF8+BOM and it worked.
try also different browser, I know it might not be a browser problem, but it might be that your script is cached somewhere.
are you using some caching? like eaccelerator?
Are those functions in a class? If so, you will need $page = $this->ModPages_GetPageByName().
Also I would echo out the argument and the sql statment in ModPages_GetPageByName(). This way you can verify that it isn't a SQL error.
I can't say for sure why your code isn't working, but I can make some suggestions that might help in locating the error.
The first thing I notice is you don't check that $db actually contains a valid database. I don't know the details of your Database object but I'm assuming there's some mechanism in there for checking if it's actually connected to the database. You should use that to determine if the database is connected before running queries on it.
$db = new Database ();
if ($db -> isConnected ())
{
$query = 'SELECT * (etc etc etc)';
// ...
}
else
{
// Put some kind of DB connection error notification or throw an exception here
}
Just on a stylistic note, you don't need to store the results of your DB lookup before returning it, unless you're planning on doing some processing on the result before returning it. You can just return the lookup directly. Of course that's just a stylistic choice, but it saves a line or two :)
return ($db->GetRow($query));
After you run your getpage function, I'd strongly recommend var_dump()ing the result. Even if your function returned NULL, you'll still see this in the var_dump. If in doubt, dump it out :). I'd also recommend installing xdebug to make the var_dump output more readable.
$page = ModPages_GetPageByName($_GET['page_name']);
var_dump ($page);
I would also strongly recommending var_dumping your query before you execute just to make absolutely sure that you're running the query you think you're running. Copy and paste the outputted query into sqlyog or phpmyadmin or whatever you use for interactive access to your database and make sure it returns what you think it should return.
Other things to check, is the page you're trying to return actually set page_enabled='yes'? Does the page_enabled column actually store the value as 'yes', or is it a bool or an integer or something else? Is magic quotes enabled or disabled? If they're in one state when you think they're in the other they can cause confusion. Are errors actually being reported to the browser? Add a line at the top of your script that's guaranteed to fail just to make sure, like an attempted foreach on an integer. If you don't see an error, then maybe error reporting isn't configured properly. I know those are obvious questions but I also know how easy it is to overlook the obvious if you're not getting what you expect out of a query.
Are you sure $page is not set, or is it just that your debug instructions don't print anything? Try logging to a file or a database instead; maybe your code triggered output buffering or something like that.
Also, you are calling ModPages_GetPageByName before declaring it. That is usually okay, but might not be in special circumstances (e.g. when the code is wrapped in an if block). Try swapping the two.
Also, check your environment and disable opcode caching and other possible error sources. APC for example can call the old version of the script long after you changed the PHP file.
While some of you have put extra effort into responding to this, nobody has been able to see the full picture, even given the details I have provided. I have been unable to trace the issue back to its source, but have moved on to a different project.

Categories