file_get_contents doesn't respond - php

I'm trying to get a JSON string from a page in my Laravel Project. Using this:
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
return View::make('adventuretime.marceline')
->with('json', $json)
->with('title', 'ICE KING')
->with('description', 'I am the Ice King')
->with('content', 'ice king');
But since I'm only using a localhost, I think this doesn't work that's why it doesn't output anything. I want to know what is the proper way for it to be flexible and be able to get the JSON string with any $url value using php?

Looking at the comments above, it is possible that the $url you are using is not valid, check it out by pointing your browser there and see what happens.
If you are sure that the $url is fine, but you still get the 404 Not Found error - verify that you have proper Laravel routing defined for that address. If the routes are fine, maybe you forgot to do
composer dump-autoload
after making modifications in your routes.php. If so, try the above and refresh the browser to see if it helps.
Furthermore, bear in mind that using your current function, you can submit only GET requests. What is more, this function might not be available for fetching remote urls, on some hosting servers due to security reasons. If you still want to use it, it'd be good to check
if($json !== FALSE)
before you process the $json response. If the file_get_contents fails it will return false.
Reffering to the part of your question
what is the proper way for it to be flexible and be able to get the JSON string with any $url
I'd suggest using cURL, as a standard and convenient way to fetch remote content. Using cURL you have better control over the process of sending the http request and receiving the "answer" it returns. Personaly, in my Laravel 4 apps I often use this package jyggen/curl. You can read the docs for it here: jyggen docs
If you are not satisfied with cURL and you want greater control try Guzzle As the authors state, Guzzle is a PHP HTTP client & framework for building RESTful web service clients.

Related

PHP HTTP client not able to resolve web page

I am trying to use a Http client to store the HTML from a web page. The following code snippet shows how I have configured the Http client, it uses php-http/guzzle6-adapter.
I know from my tests that the client works properly when pointed at other webpages.
<?php
require_once(__DIR__.'/vendor/autoload.php');
use Http\Adapter\Guzzle6\Client as GuzzleAdapter;
use GuzzleHttp\Psr7\Request;
$config = [
'verify' => false,
'timeout' => 2
];
$adapter = GuzzleAdapter::createWithConfig($config);
$request = new Request('GET', 'https://workingwithchildren.wa.gov.au/');
// Returns a Psr\Http\Message\ResponseInterface
$response = $adapter->sendRequest($request);
echo $response->getBody();
?>
However page I am trying to resolve https://workingwithchildren.wa.gov.au/ returns the following error, no matter what I do.
The requested URL was rejected. Please consult with your administrator.
Your support ID is: 9283834035315018727
I pointed my browser at the website and used Chrome Developer Tools to examine the Request/Response data being exchanged. The screenshot below shows the Response data my browser received.
I noticed that the site is setting cookies that seem to relate to security and CPFS and I would imagine these cookies are what are stopping my client from resolving the web page successfully. But I don't know how to fix this. I'd imagine this is a problem others have faced before. Any help would be much appreciated.
For anyone experiencing a similar problem the solution I found was to, as the commenter Scuzzy suggested, add User-Agent data to my guzzle config.

Bittrex API With PHP

I'm trying to set up a bot for bittrex by using the bittrex api. I previously tried using python but had a hard time as the documentation was in php(https://bittrex.com/Home/Api), so I decided to switch to php. Im trying to create the bot but having a hard time starting. I pasted the initial code:
$apikey='xxx';
$apisecret='xxx';
$nonce=time();
$uri='https://bittrex.com/api/v1.1/market/getopenorders?
apikey='.$apikey.'&nonce='.$nonce;
$sign=hash_hmac('sha512',$uri,$apisecret);
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$obj = json_decode($execResult);
And according to this video: (sorry I had to add space because it doesn't allow me to post more than 2 links with low rep)
https:// youtu.be/K0lDTK3D-74?t=5m30s
It should return this: (Same as Above)
http:// i.imgur.com/jCoAUT9.png
But when I try place the same thing in a php values, with my own api key and secret I just get a blank webpage with nothing on it. This is what my php file looks like(API key and secret removed for security reasons):
http://i.imgur.com/DYYoY0g.png
Any idea why this could be happening and how I could fix it?
Edit: No need for help anymore. I decided to go back to python and try to do it there and finally made it work :D
The video you're working from has faked their results. Their code doesn't do anything with the value of $obj, so I wouldn't expect anything to show up on the web page. (And definitely not with the formatting they show.)
If you're unfamiliar enough with PHP that this issue wasn't immediately apparent to you, this is probably a sign that you should step back and get more familiar with PHP before you continue -- especially if you're going to be running code that could make you lose a lot of money if it isn't working properly.
You need to echo your $obj or at least var_dump() it to see the content on a webpage.

API request works from local machine, not on server

I have an interesting situation when calling the Shopify API. I use the standard procedure for calling the url and get the data, like this:
define('SHOPIFY_SHOP', 'myteststore.myshopify.com');
define('SHOPIFY_APP_API_KEY', 'xxxx');
define('SHOPIFY_APP_PASSWORD', 'yyy');
$shop_url = 'https://'.SHOPIFY_APP_API_KEY.':'.SHOPIFY_APP_PASSWORD.'#'.SHOPIFY_SHOP;
$response = Requests::get($shop_url.'/admin/products.json');
And I correctly get the response, parse the data and all works great. Now, when I put it to the actual server (Ubuntu 12.04), I noticed a weird message from the Spotify API:
[API] Invalid API key or access token (unrecognized login or wrong password)
I tried creating a new app, but still its the same. So the same file and the same set works on my machine, but not on the server. (only difference in the file is the path to requests library, require_once './Requests/library/Requests.php'; for Linux and require_once '..\Requests\library\Requests.php'; for Windows) As stated, I use the requests library and I assume there has to be some trick where the library (or something else) rewrites the URl and it doesn't get to Shopify correctly.
I tried using CURL with the URL directly, and it works that way as well. Can anyone point me what might be causing this?
Update: I moved to another library which solved the issue, but would like to know what was causing this since I had great experience with Requests up to this point.
I'm starting to use the same lib, and I stumbled upon something relevant right after finding this question:
https://github.com/rmccue/Requests/issues/142#issuecomment-147276906
Quoting relevant part:
This is an intentional part of the API design; in a typical use case,
you won't necessarily need data sent along with a request. Building
the URL for you is just a convenience.
Requests::get is a helper function designed to make GET requests
lightweight in the code, which is why there's no $data parameter
there. If you need to send data, use Requests::request instead
$response = Requests::request( 'http://httpbin.org/get', $headers, $data, Requests::GET, $options );
// GET is the default for type, and $options can be blank, so this can be shortened:
$response = Requests::request( 'http://httpbin.org/get', $headers, $data );
I couldn't figure why is this happening, it appears the Requests library is stripping the parameters from GET requests, so I moved to unirest library and this solved the issue.

How can I do this in PHP / http post?

I have been given API documentation which I don't quite get as there is no URL to connect up to?
http://support.planetdomain.com/index.php?_m=downloads&_a=viewdownload&downloaditemid=14&nav=0
I'd prefer doing this in PHP..
How can I run a 10 iteration loop, doing a check if domain is available, if it's response is available, then perform the register command and exit the script (using the code provided in thd documentation).
Thank you.
For the basics, I suggest using cURL to access resources by HTTP POST.
I put this into a function:
function api_call($url,$data,$timeout=20)
{
$response=false;
$ch=curl_init($url);
curl_setopt_array($ch,array(CURLOPT_RETURNTRANSFER=>true,CURLOPT_NOBODY=>false,CURLOPT_TIMEOUT=>$timeout,CURLOPT_FORBID_REUSE=>1,CURLOPT_FRESH_CONNECT=>1,CURLOPT_POST=>true));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//this is an array containing the data you're sending them - an associative array describing which call.
//data example:
//array('operation'=>'user.verify','admin.username'=>'you','admin.password'=>'pass','reseller.id'=>'xxx')
$response=curl_exec($ch);
$status_code=intval(curl_getinfo($ch,CURLINFO_HTTP_CODE));
curl_close($ch);
return array('status'=>$status_code,'url'=>$url,'data'=>$response);
}
However, you need to supply a URL. Lucanos noted in the comments it is "api.planetdomain.com/servlet/TLDServlet".
http://support.planetdomain.com/index.php?_m=knowledgebase&_a=viewarticle&kbarticleid=77
by the way, I only use cURL for GET requests, so I might be missing some details on how to do a POST right. I tried to fill it in, though.
You ask "How can I run a 10 iteration loop, doing a check if domain is available, if it's response is available, then perform the register command and exit the script (using the code provided in thd documentation)."
Well, here's some pseudocode mixed with valid PHP. I don't know the domainplanet API as you know, so this will NOT work as is but it should give you a decent idea about it.
for($i=0;$i<10;$i++)
{
//set up the domain check call
$domains=array('futunarifountain.co.uk','megahelicopterunicornassaultlovepageant.ly');
$domain_check_call=array('domain.name'=>$domains[$i]);
$domain_info=api_call($dp_base_url,$domain_check_call);
$info=json_decode($domain_info,true);//IF they use JSON and not XML or something
if($info['domain']['status']=='available')
{
$register_call=something();//make the API calls to register the domain, similar to the above
if($register_call['success']){ exit();/*or whatever*/ }
}
}
Hope that helps get you on the right track.

USPS API Returning 501 NOT IMPLEMENTED

I am attempting to utilize the USPS API to do some address verification/validation.
I'm sending this XML to http://testing.shippingapis.com/ShippingAPITest.dll:
<AddressValidateRequest%20USERID="xxxxx"><Address ID="0"><Address1></Address1><Address2>6406 Ivy Lane</Address2><City>Greenbelt</City><State>MD</State><Zip5></Zip5><Zip4></Zip4></Address></AddressValidateRequest>
This is the same XML that is shown in their documentation for test requests. However, I always get an HTML (instead of XML) response that is a 501 Not Implmented error. Anyone familiar with this API know what might be going on? I'm using curl (in php) to make the request
UPDATE: When I make the request by typing the url into a browser with get params, it seems to work fine, but i get the error mentioned above using php/curl or just curl from the command line.
UPDATE: If I use file_get_contents with the url, I get a 400 bad request error - but if i urlencode, it works great - solution accepted.
Not familiar with the API, but:
Do you need the %20 after AddressValidateRequest? Does it work when that is replaced by a space?
Also, do you need to use CURL? Could you just use fopen() or file_get_contents() and then use the GET parameters which you mention work OK?

Categories