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.
Related
I am trying to run a server locally using ngrok to use a Twilio phone number to receive calls, but when I run ngrok http 3000 and put the url it generated the error below appears.
What can it be? All the files are giving this problem.
Erro:
<?php
// Create a route that will handle Twilio webhook requests, sent as an
// HTTP POST to /voice in our application
require_once '../vendor/autoload.php';
require_once 'Curl.class.php';
require_once './utils/Utils.php';
include '/core/DigitalLockApi.class.php';
const baseUrl = 'https://digital-lock-api-node.paymobi.com.br/';
function logText($title, $content)
{
$logfile = fopen("./log.txt", "a");
fwrite($logfile, "\n" . $title);
fwrite($logfile, "\n" . date("Y-m-d H:i:s"));
fwrite($logfile, "\n" . print_r($content, true));
fwrite($logfile, "\n" . "-----------------------------------");
fclose($logfile);
}
function initErrorsLog()
{
$log_file = "errors.log";
ini_set("log_errors", true);
ini_set('error_log', $log_file);
}
use Twilio\TwiML\VoiceResponse;
// Use the Twilio PHP SDK to build an XML response
$response = new VoiceResponse();
initErrorsLog();
if (array_key_exists('Digits', $_POST)) {
$cpf = $_POST['Digits'];
$cpfString = (string) $cpf;
if(validateCPF($cpfString)) {
$response->redirect("./password.php?cpf=$cpf");
} else {
$response->redirect('./invalidCpf.php');
}
} else {
$gather = $response->gather(['numDigits' => '100', 'timeout' => '4']);
$gather->play("https://digital-lock-api.azurewebsites.net/ura/assets/audios/insertCpf.mp3");
// If the user doesn't enter input loop
$response->redirect('./cpfNull.php');
}
// Render the response as XML in reply to the webhook request
header('Content-Type: text/xml');
echo $response;
Debugging line by line I found out that what was breaking the code was the
include '/core/DigitalLockApi.class.php';
It was not finding this import
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.
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 have a php soap webservice which I've created with using NuSOAP. I use the file 'test.php' to test it in the browser as 'http://www.mydowmain.com:8080/webservice/5/test.php'.
My code:
webservice.php
<?php
require_once('../lib/nusoap.php');
$server = new nusoap_server();
$server ->configureWSDL('server', 'urn:server'); //this line causes to 'no result'
$server ->wsdl->schemaTargetNamespace = 'urn:server'; //this line causes to 'no result'
$server -> register('getData');
function getData ()
{
$items = array(array("item1"),array("item2"));
return $items;
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server ->service($HTTP_RAW_POST_DATA);
?>
test.php
<?php
require_once('../lib/nusoap.php');
$client = new nusoap_client("http://www.mydowmain.com:8080/webservice/5/webservice.php?wsdl");
$result = $client ->call('getData');
print_r($result);
?>
Problem:
If I remove these lines
$server ->configureWSDL('server', 'urn:server');
$server ->wsdl->schemaTargetNamespace = 'urn:server';
it shows me the result fine. Otherwise I get a blank screen, get nothing. But I really need to configure the WSDL.
How can I edit the webservice.php so that the WSDL will be configured and I can get the result array on the test.php ?
To see error information about client you can add this :
$result = $client->call('getData');
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2>' . $err;
// At this point, you know the call that follows will fail
exit();
}
else
{
echo $result;
}
After that, in the server.php, maybe the register needs more information about the return value.
$server->register('getData',
array("response"=>"xsd:string"),
'http://www.mydowmain.com:8080'
);
Try changing this:
$server ->wsdl->schemaTargetNamespace = 'urn:server';
Into this:
$server ->wsdl->schemaTargetNamespace = $namespace;
and define $namespace on top of it. That did the trick for me.
This is my code of my NuSOAP webservice:
require_once("lib/nusoap.php");
$namespace = "http://localhost:8080/Testservice/service.php?wsdl";
$server = new soap_server();
$server->configureWSDL("TestService");
$server->wsdl->schemaTargetNamespace = $namespace;
I am running a problem with exporting a Google Docs (spreasheet) to xls file and save to our own server.
After successfully uploaded a file to Google Docs but somehow getting the 401 error message when I do the download.
Fatal error: Uncaught exception 'Zend_Gdata_App_HttpException' with message 'Expected response code 200, got 401
<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
Here is our PHP code and hope someone could help me to point out what went wrong.
Any thoughts would be highly received.
<?php
// set credentials for ClientLogin authentication
$google_user = 'xxxxx'; // Your google account username
$google_pass = 'xxxxx'; // Your google account password
$service = Zend_Gdata_Docs::AUTH_SERVICE_NAME;
$httpClient = Zend_Gdata_ClientLogin::getHttpClient($google_user, $google_pass,$service);
$docs = new Zend_Gdata_Docs($httpClient);
// Uploading file to Google Docs works perfectly as below
//$newDocumentEntry = $docs->uploadFile('test.txt', 'order-123456','text/plain', Zend_Gdata_Docs::DOCUMENTS_LIST_FEED_URI);
$path = "/var/www/vhosts/googledocs";
$docsQuery = new Zend_Gdata_Docs_Query();
$docsQuery->setTitle("My Spreadsheet Name");
$docsQuery->setTitleExact(false);
$feed = $docs->getDocumentListFeed($docsQuery);
foreach ($feed->entries as $entry) {
$docID = $entry->getId();
$docTitle = $entry->getTitle();
if($entry->getTitle() == "My spreadsheet File Name"){
$strURL = $entry->content->getSrc() . '&exportFormat=xls&format=xls';
$data = $docs->get($strURL);
file_put_contents($path."test.xls", $data);
}
}
?>
UPDATE - 23/05/2012
We finally got it working by tweaking the code as below: It would be useful for someone !
foreach($feed as $entry):
if($entry->getTitle() == 'My Spreadsheet File Name'){
$path = "/var/www/vhosts/regustouchstone.com/subdomains/docs/httpdocs/googledocs";
$strURL = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=".basename($entry->id)."&exportFormat=xls&format=xls";
try{
$data = $service->get($strURL)->getBody();
$fp = fopen($path."/test.xls", "w+");
fwrite($fp, $data);
fclose($fp);
}catch(Zend_Exception $e) {
echo "<br /><br /> ERROR <br />";
echo $e->getMessage();
}
}
endforeach;
Is $strUrl correctly and consistently encoded, e.g. are all '&' being encoded as '&'?
Also, if the server for the download link is http://spreadsheets.google.com (as opposed to http://docs.google.com) you might need to authenticate to the Spreadsheet service:
$spreadsheetClient = Zend_Gdata_ClientLogin::getHttpClient($google_user, $google_pass, Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME);
$spreadSheetService = new Zend_Gdata_Spreadsheets($spreadsheetClient);
...
// download the spreadsheet
$data = $spreadSheetService->get($strURL);
We have a solution as below:
foreach($feed as $entry):
if($entry->getTitle() == 'My Spreadsheet File Name'){
$path = "/var/www/vhosts/regustouchstone.com/subdomains/docs/httpdocs/googledocs";
$strURL = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=".basename($entry->id)."&exportFormat=xls&format=xls";
try{
$data = $service->get($strURL)->getBody();
$fp = fopen($path."/test.xls", "w+");
fwrite($fp, $data);
fclose($fp);
}catch(Zend_Exception $e) {
echo "<br /><br /> ERROR <br />";
echo $e->getMessage();
}
}
endforeach;