PHP: Wating for JSON to load completly before decoding it - php

I´m requesting an API like so (Domain is NSFW):
$external_videoid = "ph57fbb82bd33ab";
$string = file_get_contents("http://www.pornhub.com/webmasters/video_by_id?id=".$external_videoid."&thumbsize=big");
$json = json_decode($string, true);
$title = $json["video"]["title"];
echo $string;
But I can´t retrieve any data. $title is empty. The echo gives me:
<html><head>[...]<bodyonload="go()">Loading...</body>[...]</html>
Which might indicate that the JSON I want to retrieve is somehow loading, I guess. Seems pretty clear to me. It seems like file_get_contents has to wait for the site to load. What can I do?
APPEND: Sometimes the request works. Sometimes it doesn´t.

Your code works for me, $title echos as:
I Feel Myself Creature Comforts 1
(lol)
I suppose the connection was ACTUALLY loading when you tried it. The json returns some highly "entertaining" information haha, especially the tags (NSFW obviously)
Be aware pornhub has an API(!): http://www.hubtraffic.com/

Use this code.
$v= "ph57fbb82bd33ab";
$url="http://www.example.com/sample/param?id=".$v;
$data = file_get_contents($url);
$characters=json_decode($data, true);
echo $characters['video']['title'];

Related

Get a Json string from a public URL using php

Ok, i thinked i was able to do this easily but i cant figure how.
I have tried in many ways i found here and in other pages but nothing works; i spent two days with this, but i finally decided to register here and ask.
So here is my karma:
http://api.bitcoinvenezuela.com/DolarToday.php?json=yes
That url generates this json:
{"_antibloqueo":{"mobile":"https://dt.wordssl.net","video":"","corto_alternativo":"https://bit.ly/venezuela911","enable_iads":"","enable_admobbanners":"ca-app-pub-8212448379596570/1946229161","enable_admobinterstitials":"","alternativo":"68747470733a2f2f64626d7a647431663034653531632e636c6f756466726f6e64742e6e6574","alternativo2":"68747470733a2f2f64626d7a647431663034653531632e636c6f756466726f6e64742e6e6574","notifications":"https://d3c134ru0r3b0g.cloudfront.net","resource_id":"33504 A"},"_labels":{"a":"DOLARTODAY","a1":"DOLAR CUCUTA","b":"IMPLICITO","c":"DICOM","d":"DOLAR BITCOIN","e":"DIPRO"},"_timestamp":{"epoch":"1513837984","fecha":"Diciembre 21, 2017 02:33 AM","fecha_corta":"Dic 21, 2017","fecha_corta2":"Dic 2017","fecha_nice":"Diciembre 21, 2017","dia":"Jueves","dia_corta":"Jue"},"USD":{"transferencia":121205.72,"transfer_cucuta":121205.72,"efectivo":10330.84,"efectivo_real":122608.7,"efectivo_cucuta":122608.7,"promedio":121205.72,"promedio_real":11311,"cencoex":10,"sicad1":94496.22,"sicad2":11311,"bitcoin_ref":94496.22,"localbitcoin_ref":94496.22,"dolartoday":121205.72},"EUR":{"transferencia":143581.51,"transfer_cucuta":143581.51,"efectivo":12259.61,"efectivo_real":145502.19,"efectivo_cucuta":145502.19,"promedio":143581.51,"promedio_real":13422.76,"cencoex":11.87,"sicad1":112138.66,"sicad2":13422.76,"dolartoday":143581.51},"COL":{"efectivo":0.023,"transfer":0.023,"compra":0.023,"venta":0.02},"GOLD":{"rate":1265.9},"USDVEF":{"rate":10.02959},"USDCOL":{"setfxsell":2820,"setfxbuy":2740,"rate":3606,"ratecash":2825,"ratetrm":3005.76,"trmfactor":0.2,"trmfactorcash":0.06},"EURUSD":{"rate":1.18672},"BCV":{"fecha":"1513569600","fecha_nice":"Diciembre 18, 2017","liquidez":"100.643.049.794","reservas":"9.742.000"},"MISC":{"petroleo":"56,14","reservas":"9,7"}}*
I need read the json it generates to get the bolded values (only 2 values i need from there); I have tried with curl, file_get_contents, and many other ways, but nothing works.
Basically, I can not understand WHY this code do not works:
<?php
$url = 'http://api.bitcoinvenezuela.com/DolarToday.php?json=yes';
$obj = json_decode(file_get_contents($url), true);
echo $obj;
?>
I get a warning:
Warning: file_get_contents(http://api.bitcoinvenezuela.com/DolarToday.php?json=yes): failed to open stream: Connection timed out in /home/u704982448/public_html/lbapi.php on line 3
Any idea what is happening here? Where is the fail?
EDIT: Looks like the problem here is that my server ip is blocked. Any workaround for this?
Thanks to everyone.
You are trying to print an array in echo statement so its an error.
<?php
$url = 'http://api.bitcoinvenezuela.com/DolarToday.php?json=yes';
$obj = json_decode(file_get_contents($url), true);
echo "<pre>";
print_r($obj);
?>
Regarding connection timeout you need to check IP block etc
It works fine for me.
I tested it on my webpage and it worked fine.
Just needed to replace echo with var_dump().
http://www.hoppvader.nu/Mail/test.php
$url = 'http://api.bitcoinvenezuela.com/DolarToday.php?json=yes';
$obj = json_decode(file_get_contents($url), true);
var_dump($obj);
To echo the two values you need you use this code:
echo $obj["_timestamp"]["epoch"];
echo $obj["USD"]["transferencia"];
Seems to be a connection problem on server side. Maybe there is some firewall configured or the server has no connection to the internet etc...
You should try the following, log in into server and try to run:
curl http://api.bitcoinvenezuela.com/DolarToday.php?json=yes
This command would basically try to reach the url and print the output.
If you have the same timeout issue here then you have the proof that the error is independent of your php script.

URL not executed in file_get_contents();

I need to execute a URL in back-end, when ever the page executes, for this I am using file_get_contents(); but sadly it is not processing the url requested, please help me, pardon me if I am wrong, thank you.
.PHP
<?php
$url="http://www.foo.in/bound/bound.php?phone_no=".$from_id."&api_key=xxxxxxxxxxxxxxxxxxxx &bound_version=2&extra_data=<response><dial record='true' limittime='1000' timeout='30' moh='default' >".$to_id."</dial></response>";
$data = file_get_contents($url);
?>
I resolved out the solution there was a gap in URL there was space after api_key and extra_data not encoded, btw thanks for support.
.PHP
$url="http://www.foo.in/bound/bound.php?phone_no=".$from_id."&api_key=xxxxxxxxxxxxxxxxxxxxx=2&extra_data=".urlencode("<response><dial record='true' limittime='1000' timeout='30' moh='default' >".$to_id."</dial></response>");
$data = file_get_contents($url);
echo $data;

PHP Variables not passing to url correctly from API

I'm trying to use the Premium URL Shortener script from codecanyon, I have asked for support but they seem to be a little busy, so the response time is not to quick.
The issue I have is when the API sends the request to the url shortener script with the following shortened query for example purposes:
$short = "http://myurl/api?api=MYAPI&format=text&url=http://myfullwebsite.com/email/quote.php?fullname=$fullname&address=$address&emailaddress=$emailaddress";
Although the variables are being placed in the script correctly using echo function at the end of the script after the api request is sent shows they are correctly inserted like so:
http://myurl/api?api=MYAPI&format=text&url=http://myfullwebsite.com/email/quote.php?fullname=Dan Smith&address=12 Main Street, London&emailaddress=dan#smith.com
However if I click the shortened url provided to me from the script I only get the following url string appear in the browser:
http://myfullwebsite.com/email/quote.php?fullname=Dan
It seems as soon as there is a space or even if there is no second name such as Dan Smith and only Dan is the available name, it will not even apply the second ampersand or & sign.
I have tried to use urlecode() but still no joy and I've been pulling my hair out for the last 3 days!
As a novice beginner it has been somewhat difficult to try and achieve the end result and it seems unreachable so I would appreciate any kind help or advice if possible, Maybe I'm missing something so simple?
I've thought of having the url query build from an array of variables but as a novice I've tried one way and failed so not sure if I have done it wrong.
Here is my full api code where I have tried both with SESSION and GET but that is not the problem as the end result echos to the browser with the variables there.. it's only when you follow the shortened url link that you see they're missing.
<?php
session_start();
$fullname = htmlspecialchars($_GET["fullname"]);
$address = htmlspecialchars($_GET["address"]);
$postcode = htmlspecialchars($_GET["postcode"]);
$emailaddress = htmlspecialchars($_GET["emailaddress"]);
$short = "http://myurl/api?api=MYAPI&format=text&url=http://ukhomesurveys.co.uk/email/quote.php?fullname=$fullname&address=$address&emailaddress=$emailaddress";
echo $short;
// Using Plain Text Response
$api_url = $short;
$res= #file_get_contents($api_url);
if($res){
echo $res;
}
?>
Hope I covered everything and hope I have not confused anyone. Thanks.
I think the good choice here is to encode your query with base64 and then pass it to the shortener. In your http://myfullwebsite.com/email/quote.php you just decode the query and use it. The standart PHP functions are base64_encode and base64_decode.
Did you try to encode URI using rawurlencode?
$url = rawurlencode('http://myfullwebsite.com/email/quote.php?fullname=Dan Smith&address=12 Main Street, London&emailaddress=dan#smith.com');

Receiving Gzipped POST requests

I'm sending POST requests to a page that as the following code :
$post = json_decode(file_get_contents('php://input'), true);
$text=$post['text'];
echo gettype($text);
echo $text;
When i'm sending strings under 260 or so bytes, it works fine. But for higher sizes, it just prints NULL. I believe that strings >260b get automatically gzipped with the software I use. How can I retrieve the data I want ?
PS : I'm really new to php
Use
$_POST['text'];
instead of:
post['text'];
Edit: misread question, can you try this:
var_dump(json_decode(file_get_contents('php://input'), true));
and post the output here so we know what the return looks like?

Passing variables through GET for a file_get_contents - a different way

I have information stored in a session. But was I just found out, sessions don't work when you do file_get_contents().
So after some searching I thought of using this technic:
$cart = base64_encode(serialize($_SESSION['cart']));
I pass my session cart, serialize it and encode it. I then pass it into the file_get_contents.
$url = "http://www.domain.com/pdf_order.php?cart=".$cart;
$html = file_get_contents($url);
In the URL that it gets, I have this:
$cart = unserialize(base64_decode($_GET['cart']));
But I don't get anything.
I can print out the GET cart and I have an encoded string, but then I can't do anything with it.
Any help, much appreciated.
UPDATE
When I echo the URL I get this
http://www.domain.com/pdf_order.php?cart=YTozOntzOjc6Imdhcm1lbnQiO2E6MTp7aTowO2E6Nzp7czo0OiJ0eXBlIjtzOjU6IlNoaXJ0IjtzOjY6ImFjY2VzcyI7czozOiJ5ZXMiO3M6MzoiaWREIjtpOjEwNDtzOjY6ImZhYnJpYyI7YToyOntzOjQ6InR5cGUiO2E6Mzp7czo4OiJkYl92YWx1ZSI7czo0OiJiZXN0IjtzOjExOiJwcmV0dHlfbmFtZSI7czoxNToiSSB3YW50IHRoZSBiZXN0IjtzOjM6InR4dCI7czoxNDY6IjEwMCUgQ290dG9uPGJyIC8+SWYgeW91IHdhbnQgdGhlIGJlc3QsIHdlJ2xsIGdpdmUgdGhlIGJlc3QuICBDb3R0b24gaXMgdGhlIG1vc3QgY29tZm9ydGFibGUgZmFicmljIGFuZCBpcyBhIGZhYnJpYyB0aGF0IGJyZWF0aHMuLi55b3UnbGwgZW5qb3kgaXQuIjt9czo1OiJwcmljZSI7aTo5MDt9czozOiJpZFMiO3M6MjoiNTIiO3M6OToicXR5X1NoaXJ0IjtzOjE6IjQiO3M6NDoicXR5XyI7czoxOiI0Ijt9fXM6MzoiaWRBIjtzOjg6IjExMTExMTUxIjtzOjExOiJhY2Nlc3NvcmllcyI7YTo0OntpOjA7YTo0OntzOjM6ImlkQSI7czoxOiIxIjtzOjQ6Im5hbWUiO3M6ODoiU2xpbSB0aWUiO3M6MzoicXR5IjtzOjE6IjQiO3M6NToicHJpY2UiO3M6NToiMjcuOTkiO31pOjE7YTo0OntzOjM6ImlkQSI7czoxOiIyIjtzOjQ6Im5hbWUiO3M6ODoiU2xpbSB0aWUiO3M6MzoicXR5IjtpOjE7czo1OiJwcmljZSI7czo1OiIyNy45OSI7fWk6MjthOjQ6e3M6MzoiaWRBIjtzOjE6IjMiO3M6NDoibmFtZSI7czo4OiJTbGltIHRpZSI7czozOiJxdHkiO2k6MTtzOjU6InByaWNlIjtzOjU6IjI3Ljk5Ijt9aTozO2E6NDp7czozOiJpZEEiO3M6MToiNCI7czo0OiJuYW1lIjtzOjg6IlNsaW0gdGllIjtzOjM6InF0eSI7aToxO3M6NToicHJpY2UiO3M6NToiMjcuOTkiO319fQ==
Check out How to post data in PHP using file_get_contents? it's pretty much doing what you want to do, by creating a stream.
I'm guessing you can still put $_SESSION variables in there too.
If you are working on same server as www.domain.com then why do you need to use file_get_contents() to get some data or do some processing . Use direct calls.

Categories