I am currently having issues with my going into an infinite loading state and hitting a 505 Gateway when using file_get_contents for reading the response of an API and parsing the JSON.
Here is the code:
<?php
try {
while(true) {
$url = 'http://floodcrm.net/api.php?key=MY_API_KEY_GOES_HERE&method=get_invite';
$jsonData = file_get_contents($url);
$json = json_decode($jsonData,true);
echo $json['code'];
if(#file_get_contents($url))
{
break;
}
sleep(2);
}
}catch (Exception $e) {
echo $e->getMessage();
}
?>
It can work fine, but after a while the site will just die again.
Really hope I can have some help with this.
Related
Trying to access data from a local API that outputs in JSON data, but I just keep getting:
file_get_contents(/var/www/html/api/api.php?action=stats&user=testplayer): failed to open stream: No such file or directory
Code:
<?php
error_reporting(-1);
ini_set("display_errors", 1);
include 'functions.php';
if(isset($_GET['action']))
{
header('Content-Type: application/json');
try
{
switch($_GET['action'])
{
case 'stats':
if(!isset($_GET['user']))
throw new Exception('Insufficient information : Username');
$user = $_GET['user'];
$url = htmlspecialchars_decode("/var/www/html/api/api.php?action=stats&user=$user");
$response = file_get_contents("$url");
$data = json_decode($response);
echo $data;
break;
}
}
catch(Exception $e)
{
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(array('result' => 'error', 'cause' => $e->getMessage()));
}
}
?>
Is it not possible to pass ? and &s through file_get_contents?
You can't process the php code if you are reading the file contents.
update the $url like this:
$url = htmlspecialchars_decode($_SERVER["SERVER_NAME"] . "/api/api.php?action=stats&user=$user") ;
This will make the request to your apache server instead of reading the file contents.
I have the following request to an API:
$url = "{{correctURLishere}}";
$response = json_decode(file_get_contents($url), true);
$name = $response["title"];
}
The This should bring back the value from they key "title" in this json response. But instead, the error I get is
file_get_contents(url): failed to open stream: HTTP request failed!
HTTP/1.1 402
I know the error is because I am only allowed 150 requests a day and have exceeded this amount but can someone help me to echo "No more requests allowed" instead of the error?
I have tried the following but it wont work:
if(json_decode(file_get_contents($url), true)) {
$response = json_decode(file_get_contents($url), true);
$name = $response["title"];
}
Could anyone tell me how to help with the error? Thanks
try to use try catch section, for example
try{
if(json_decode(file_get_contents($url), true)) {
$response = json_decode(file_get_contents($url), true);
$name = $response["title"];
}
}catch(Exception $e){
print_r($e);
echo '<br>';
echo $e->getMessage();
}
for your referrence: https://www.php.net/manual/en/language.exceptions.php
I am calling some web services, using SoapClient. I am looking for a mechanism which will help me to display some errors to user, whenever web services goes offline or down.
As I have to wait for some time(15 sec) before displaying any errors to user. I am adding connection_timeout in SoapClient like this, for timeout.
$this->client = new SoapClient($clienturl,array('trace' => 1,
'exceptions'=> 1,
'connection_timeout'=> 15)); //$clienturl is webservice url
Also in top section of page, I have added this line,
ini_set("default_socket_timeout", 15); // 15 seconds
After specific timeout interval I am getting different SOAP-ERROR like this,
SOAP-ERROR: Parsing WSDL: Couldn't load from $clienturl
So I am looking for an error handler which will handle these SOAP-ERROR so as to display those in human-readable format to user like "Server is down, Try again after some time." Or Is there any way to handle timeout errors?
You can put it in a try/catch
try {
$time_start = microtime(true);
$this->client = new SoapClient($clienturl,array('trace' => 1,
'exceptions'=> 1,
'connection_timeout'=> 15
));
} catch (Exception $e) {
$time_request = (microtime(true)-$time_start);
if(ini_get('default_socket_timeout') < $time_request) {
//Timeout error!
} else {
//other error
//$error = $e->getMessage();
}
}
This is what I am using for soapClien connection in php
set_error_handler('error_handler');
function connectSoapClient($soap_client){
while(true){
if($soap_client['soap_url'] == ''){
trigger_error("Soap url not found",E_USER_ERROR);
sleep(60);
continue;
}
try{
$client = #new SoapClient($soap_client['soap_url'],array("trace" => 1,"exceptions" => true));
}
catch(Exception $e){
trigger_error("Error occured while connection soap client<br />".$e->getMessage(),E_USER_ERROR);
sleep(60);
continue;
}
if($client){
break;
}
}
return $client;
}
function error_handler($errno, $errstr, $errfile, $errline){
if($errno == E_USER_ERROR){
$error_time = date("d-m-Y H:i:s");
$errstr .= "\n
############################### Error #########################################\n
Error No: $errno
Error File: $errfile
Line No: $errline
Error Time : $error_time \n
##############################################################################
";
mail($notify_to,$subject,$errstr);
}
}
I have some Apache Thrift (v.0.6.1) test application with perl-server and php-client.
The behaviour I cannot explain: If we call server-method with invalid argument we see the error in server-output, but php-client stays waiting the response infinitely.
Here are the sources of server:
sub new {
my $classname = shift;
my $self = {};
return bless($self,$classname);
}
sub DateToTimestamp
{
my ($self, $date) = #_;
my $result = CommonAPI::DateToTimestamp($date);
return $result;
}
eval {
my $handler = new RPCHandler;
my $processor = new RPCPerformanceTest::RPCPerformanceTestProcessor($handler);
my $serversocket = new Thrift::ServerSocket(9091);
my $forkingserver = new Thrift::ForkingServer($processor, $serversocket);
print "Starting the server...\n";
$forkingserver->serve();
print "done.\n";
}; if ($#) {
if ($# =~ m/TException/ and exists $#->{message}) {
my $message = $#->{message};
my $code = $#->{code};
my $out = $code . ':' . $message;
die $out;
} else {
die $#;
}
}
and client:
try {
$socket = new TSocket($server_host, $server_port);
$transport = new TBufferedTransport($socket, 1024, 1024);
$protocol = new TBinaryProtocol($transport);
$client = new RPCPerformanceTestClient($protocol);
$transport->open();
$start = microtime(true);
$result = $client->DateToTimestamp('071/26/2011 01:23:45');
var_dump($result);
} catch (Exception $e) {
echo 'Exception: <b>' . $e->getMessage() . '</b>';
}
Why is this happening? Is it my fault? Is it expected behavour?
The Thrift PHP library is a bit broken. You need to manually set the timeouts
E.g.
$socket = new TSocket('host', 9095);
$socket->setSendTimeout(60000);
$socket->setRecvTimeout(60000)
This happens often with protocols that do not supply message length: a client sends more data then the server expects and waits for the server to receive the data. The server receives some of the data, tries to parse it and fails. Now the server-side of the protocol is in errorneous state. If it continues to read the data, it may block. Most probably, the server-side has sent you some error response and is waiting at the same time for the client to receive the response, but that will never happen too.
This is my guess. The best strategy IMHO is to set a time-out for both client and server sockets.
I'm trying to create a page that displays current results from CA Lottery using PHP. I've used XML before, but am having issues with SOAP. I found this page, but its not a lot of help.
I've put together the code below, and was able to get it to return an object. But I can't get it to feed in the results I need. Any help would be amazing.
try {
$options = array(
'soap_version'=>SOAP_1_1,
'exceptions'=>true,
'trace'=>1,
'cache_wsdl'=>WSDL_CACHE_NONE
);
$client = new SoapClient('http://services.calottery.com/CALotteryService.asmx?WSDL', $options);
} catch (Exception $e) {
echo "<p>Exception Error!</p>";
echo $e->getMessage();
}
echo '<p>Connection: Success;</p>';
try {
$response = $client->GetCurrentGameInfo();
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
$x = simplexml_load_string("<?xml version=\"1.0\"?>".$response->GetCurrentGameInfoResult->any);
var_dump($x);
Try this
var_dump($response);
$x = simplexml_load_string("<?xml version=\"1.0\"?>".$response->GetCurrentGameInfoResult->any);
var_dump($x);
at the end of your script. Kind of odd, but calottery is returning a fragment of XML in the response that needs to be further processed ( the simplexml_load_string ).