How to get JSON in response - php

When I debug a site via Chrome browser I get JSON response. But when I try to do this via PHP I get an error message.
failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found
Thanks for any help.
For example:
Things to do in Chrome:
Go to page: http://gruper.pl/warszawa and on the bottom you will see a button "Wiecej ofert". After click you will see in a debug:
http://gruper.pl/DataProvider.php?cityId=51&categoryId=0&mainNaviId=1&showBTile=true&page=1
and response:
[{"ID_PAGE":"59199","ID_CITY":"3952","main_city":"3952","date_start":"2014-02-23 18:00:00","date_end":"2014-03-01 23:59:00","price".....
Is there any possibility to get the same in PHP?
My code is:
<?php
$url = 'http://gruper.pl/DataProvider.php?cityId=51&categoryId=0&mainNaviId=1&showBTile=true&page=1';
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
"Accept:application/json\r\n" .
"Accept-Encoding:gzip,deflate,sdch\r\n" .
"X-Requested-With:XMLHttpRequest\r\n",
'method' => 'GET'
),
);
$context = stream_context_create($options);
$result = (file_get_contents($url, false, $context));
?>
<html>
<head>
<meta charset="UTF-8">
</head>
</html>

It looks like that URL will return a 404 HTTP status code unless these headers are set:
X-Requested-With: XMLHttpRequest
Referer: http://gruper.pl/warszawa
So this will work:
<?php
$url = 'http://gruper.pl/DataProvider.php?cityId=51&categoryId=0&mainNaviId=1&showBTile=true&page=1';
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "X-Requested-With: XMLHttpRequest\r\n" .
"Referer: http://gruper.pl/warszawa"
)
);
$context = stream_context_create($options);
$result = (file_get_contents($url, false, $context));
echo $result;
?>

Related

Receive PHP code with an POST request

I need to send a POST request to another file called global.php, for this I try this code below:
$url = 'global.php';
$data = array('stack' => 'overflow');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
This is the global.php file that should process the request:
if(isset($_POST['stack'])){
echo 'exists';
}else{
echo 'error';
}
The problem is that instead of the command var_dump ($ result); show exists, it shows the PHP code? how can I solve this problem?
And why when I try to do the same thing using ajax it returns me the text exists and not PHP code?
You should use full url, to process php file through server.
$url = 'http://YOURURL.com/global.php';
AJAX call is made from browser, to absolute URL, thats why You are getting desired response.

php script to read and save web page contents not working on some sites

I have a very simple script that works perfectly on most sites but not the main site I want it to work with - the code below accesses a sample site perfectly. However when I use it on a site I want to access http://www.livescore.com I get an error
This works.
<?php
$url = "http://www.cambodia.me.uk";
$page = file_get_contents($url);
$outfile = "contents.html";
file_put_contents($outfile, $page);
?>
This does not work.....
<?php
$url = "http://www.livescore.com";
$page = file_get_contents($url);
$outfile = "contents.html";
file_put_contents($outfile, $page);
?>
and gives the following error
Warning: file_get_contents(http://www.livescore.com)
[function.file-get-contents]: failed to open stream: HTTP request
failed! HTTP/1.0 404 Not Found in C:\Program Files
(x86)\EasyPHP-5.3.8.1\www\Livescore\attempt-1-read-page.php on line 3
Thanks for any assistance
In common case you can just say to file_get_contents to follow redirects:
$context = stream_context_create(
array(
'http' => array(
'follow_location' => true
)
)
);
$html = file_get_contents('http://www.example.com/', false, $context);
This site tries to analyze User-agent http header, and fails if it's not found. Try to add some user-agent header:
<?php
$context = stream_context_create(
array(
'http' => array(
'header' => "User-agent: chrome",
'ignore_errors' => true,
'follow_location' => true
)
)
);
$html = file_get_contents('http://www.livescore.com/', false, $context);
echo substr($html, 0, 200)."\n";
Most likely www.livescore.com is doing a hidden redirect which file_get_contents is too basic to catch.
Do you have lynx installed on your server?
$page= shell_exec("lynx -source 'http://www.livescore.com'");
lynx is a full browser and can 'bypass' certain redirects.

PHP to connect to remote Parse MongoDB; cURL works on command line but PHP file_get_contents doesn't

I am working with a Wordpress site with CPanel and a MySQL database. I want to be able to read data from a MongoDB held on Parse.com. Eventually, I want to change Wordpress's login.php script to search through the MongoDB and create users if necessary.
I am having lots of trouble connecting to the database.
Here is my php script:
<?php
$url = 'http://mercury.example.com:2234/parse/login';
$data = array('username' => 'username', 'password' => 'password');
$appID = "X-Parse-Application-Id: parseAppID";
$restKey = "X-Parse-REST-API-Key: praseRESTapiKey";
$session = "X-Parse-Revocable-Session: 1";
$contentType = "Content-Type: application/json";
$context = array(
'http'=> array(
"method" => "GET",
"header" => $appID . $restKey . $session . $contentType,
"content" => http_build_query($data)));
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);
var_dump($result);
?>
The errors I am receiving are:
Notice: file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded in C:\wamp\www\parseDB.php on line 26
Warning: file_get_contents(http://mercury.example.com:2234/parse/login): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in C:\wamp\www\parseDB.php on line 26
From my understanding, the 403 error means the web server is returning the "forbidden" status code.
I am testing my php script on localhost using WAMP. A colleague of mine tried to run a similar command on Bash and received a response. (I broke it out so it is easier to read).
curl -X GET
-H "X-Parse-Application-Id: parseAppID"
-H "X-Parse-REST-API-Key: parseRESTapiKey"
-H "X-Parse-Revocable-Session: 1"
-G --data-urlencode 'username=username' --data-urlencode 'password=password'
http://mercury.example.com:2234/parse/login
I have been stuck on this for 2 days so far, and I have no idea what is going on. I appreciate all the help I can get.
EDIT
Here is my final solution:
$url = 'http://mercury.example.com:3432/parse/login';
$data = array('username' => 'USERNAME', 'password' => 'PASSWORD!');
$context = array(
'http'=> array(
'method' => "GET",
'header' => "X-Parse-Application-Id: APPID\r\n" .
"X-Parse-REST-API-Key: RESTAPIKEY\r\n" .
"X-Parse-Revocable-Session: 1" .
"Content-Type: application/json\r\n",
'content' => http_build_query($data)
)
);
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);
var_dump($result);
?>
Look at the stream_content_create example at http://php.net/manual/en/function.stream-context-create.php which explains how to pass headers properly. At this time, you slam each header together without any line feeds which will make them look like concatenated string:
X-Parse-Application-Id: parseAppIDX-Parse-REST-API-Key: praseRESTapiKeyX-Parse-Revocable-Session: 1Content-Type: application/json
Hint - add \r\n after each header line.
Instead of file_get_contents you could also use curl methods.

how to request addDelegates ? 415 error

may I need to access to the emailsettings api with POST action in php.
But i always get this error :
failed to open stream: HTTP request failed! HTTP/1.0 415 Unsupported Media Type
Here is my code:
public function addDelegates($account,$delegates,$domain,$tokken) {
foreach ($delegates as $key => $value) {
sleep(5);
$url = "https://apps-apis.google.com/a/feeds/emailsettings/2.0/".$domain."/".$account."/delegation";
$requestXML = '<?xml version="1.0" encoding="utf-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006">
<apps:property name="address" value="' . $value . '" />
</atom:entry>';
$requestHeaders = array(
'Content-type: application/xml+atom',
'Accept: application/xml+atom',
sprintf('Content-Length: %d', strlen($requestXML))
);
$context = stream_context_create(
array(
'http' => array(
'method' => 'POST',
'header' => implode("\r\n", $requestHeaders),
'content' => $requestXML,
)
)
);
$responseXML = file_get_contents($url, false, $context);
}
I saw that this error means that i may send wrong content type. But i tried application/json, application/xml, text/xml etc..
Nothing is precised about what data we have to send in emailSettings api doc :/
Thanks in advance .
I think content type in your posted code is not correct. change content-type to "application/atom+xml" instead of application/xml+atom. This should resolve your 415 error.

passing headers into file_get_contents() for a json request

I need to pass these headers into the $context variable, i tried using putting the values into an array and then passing it into stream_context_create() function but i get http warnings from the file_getcontents function
$prod_id = 4322;
$tnxRef = "RT45635276GHF76783AC";
$mackey = "ADECNH576748GH638NHJ7393MKDSFE73903673";
$agent = $_SERVER['HTTP_USER_AGENT'];
$hash = hash('SHA512', $prod_id.$txnRef.$mackey);
$headers = array(
'http'=>(
'method'=>'GET',
'header'=>'Content: type=application/json \r\n'.
'$agent \r\n'.
'$hash'
)
)
stream_context_create($headers)
$url_returns = file_get_contents("https://test_server.com/test_paydirect/api/v1/gettransaction.json?productid=$prod_id&transactionreference=$txnRef&amount=$amount", false, $context);
$json = json_decode($url_returns, true);
Error:
[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request`
Thats the error i get, can somebody please help with a definitive example.
You have several errors in your code.
The server returns 400 Bad Request, because your code would result in this incorrect HTTP request:
GET /test_paydirect/api/v1/gettransaction.json?productid=4322&transactionreference=RT45635276GHF76783AC&amount= HTTP/1.1
Host: test_server.com
Content: type=application/json
$agent
$hash
The errors are:
Variable expressions are not evaluated within single quotes
$amount is not set in your code example
The header is Content-Type: and not Content: type=
All headers (agent, hash) must have their corresponding name
Here is an example that should work:
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'agent' => $agent,
'header' => "Content-Type: application/json\r\n"
. "X-Api-Signature: $hash"
)
)
);
Please note: X-Api-Signature is just an example - it depends on the API you are using how the API key header is named and how the hash is calculated. You should find this information in the Docs of your API!

Categories