Why doesn't file_get_contents work? - php

Why does file_get_contents not work for me? In the test file code below, it seems that everyone's examples that I've searched for all have this function listed, but it never gets executed. Is this a problem with the web hosting service? Can someone test this code on their server just to see if the geocoding array output actually gets printed out as a string? Of course, I am trying to assign the output to a variable, but there is no output here in this test file....
<html>
<head>
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</head>
<body>
<?
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>

Check file_get_contents PHP Manual return value. If the value is FALSE then it could not read the file. If the value is NULL then the function itself is disabled.
To learn more what might gone wrong with the file_get_contents operation you must enable error reporting and the display of errors to actually read them.
# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);
You can get more details about the why the call is failing by checking the INI values on your server. One value the directly effects the file_get_contents function is allow_url_fopen. You can do this by running the following code. You should note, that if it reports that fopen is not allowed, then you'll have to ask your provider to change this setting on your server in order for any code that require this function to work with URLs.
<html>
<head>
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</head>
<body>
<?php
# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>', $url, '</p>';
$jsonData = file_get_contents($url);
echo '<pre>', htmlspecialchars(substr($jsonData, 128)), sprintf(' ... (%d)', strlen((string)$jsonData)), '</pre>';
# Output information about allow_url_fopen:
if (ini_get('allow_url_fopen') == 1) {
echo '<p style="color: #0A0;">fopen is allowed on this host.</p>';
} else {
echo '<p style="color: #A00;">fopen is not allowed on this host.</p>';
}
# Decide what to do based on return value:
if ($jsonData === FALSE) {
echo "Failed to open the URL ", htmlspecialchars($url);
} elseif ($jsonData === NULL) {
echo "Function is disabled.";
} else {
echo '<pre>', htmlspecialchars($jsonData), '</pre>';
}
?>
</body>
</html>
If all of this fails, it might be due to the use of short open tags, <?. The example code in this answer has been therefore changed to make use of <?php to work correctly as this is guaranteed to work on in all version of PHP, no matter what configuration options are set. To do so for your own script, just replace <? or <?php.

If PHP's allow_url_fopen ini directive is set to true, and if curl doesn't work either (see this answer for an example of how to use it instead of file_get_contents), then the problem could be that your server has a firewall preventing scripts from getting the contents of arbitrary urls (which could potentially allow malicious code to fetch things).
I had this problem, and found that the solution for me was to edit the firewall settings to explicitly allow requests to the domain (or IP address) in question.

If it is a local file, you have to wrap it in htmlspecialchars like so:
$myfile = htmlspecialchars(file_get_contents($file_name));
Then it works

Wrap your $adr in urlencode().
I was having this problem and this solved it for me.

//JUST ADD urlencode();
$url = urlencode("http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false");
<html>
<head>
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</head>
<body>
<?php
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>

The error may be that you need to change the permission of folder and file which you are going to access. If like GoDaddy service you can access the file and change the permission or by ssh use the command like:
sudo chmod 775 file.jpeg
and then you can access if the above mentioned problems are not your case.

Related

php not working properly in mail()

I am trying to send the information as a mail to the admin
Below is the mail code and I am reading this using file_get_contents() in another file.
<!doctype html>
<?php
require_once("mysqlconnect.php");
session_start();
?>
<html>
<head>
<link rel="stylesheet" href="css/mail.css">
</head>
<body>
<table border="2">
<?php
$q="select * from profile where mobile=2147483647";
$result=mysqli_query($conn,$q);
while($row = mysqli_fetch_assoc($result))
{
foreach($row as $key=>$value)
{
if($key=="Email")
echo"<tr><th>$key</th><td><a href='mailto:$value; target='_blank'>$value</td></tr>";
else
echo"<tr><th>".str_replace('_',' ',$key)."</th> <td>$value</td></tr>";
}
}
?>
</table>
</body>
</html>
<?php
session_destroy();
?>
The result of this code in the mail is the PHP code itself..
$value) { if($key=="Email") echo"
$key $value
"; else echo"
".str_replace('_',' ',$key)." $value
"; } } ?>
file_get_contents returns the content of a file as string. It does not executes the code inside it.
To use the HTML from a php file you can use php's buffer.
Like this:
ob_start();
include('file_path_here');
$HTML = ob_get_clean();
This will store the output of the file in the $HTML variable.
file_get_contents literally reads in a file as a string. If you're reading in a PHP file using that method, it'll literally return the code, which is what you're getting.
If you want to send HTML as an e-mail, use something like a template system (sitecrafting.com/blog/top-5-php-template-engines) or build a string and pass it onto the mail() function.
PHP documentation: file_get_contents

How can I rewrite this PHP function to extract data from an external website/source

I have this PHP function that pulls/extracts data from xml elements and displays them on my webpage. However it is only working when used with a local path. not from any external sources. Here is the code.
Index.php
<html>
<body>
<?php
include('render_xml_to_html.php');
// The internal path. DOES work.
render_xml_data('example.xml');
?>
</body>
</html>
Example.xml
<eveapi version="2"><currentTime>2014-05-08 03:34:23</currentTime>
<result>
<serverOpen>True</serverOpen>
<onlinePlayers>24957</onlinePlayers>
</result>
<cachedUntil>2014-05-08 03:35:58</cachedUntil>
</eveapi>
The function - render_xml_to_html.php
<?php
function render_xml_data($path_to_xml_file){
if (!file_exists($path_to_xml_file)){
return;
}else{
$chars_to_replace = array('[\r]','[\n]','[\t]');
$xmlstring = trim(preg_replace($chars_to_replace, '', file_get_contents($path_to_xml_file)));
}
$xml = new SimpleXMLElement($xmlstring);
foreach ($xml->result as $record) {
echo '<div class="record">'."\n";
echo '<h3>'.$record->onlinePlayers.'</h3>'."\n";
echo '</div><!--end record-->'."\n";
}
}
?>
The above code works as is. My issue is when I try to pull this info from the realtime .xml file on the hosts server. That url is:
https://api.eveonline.com/server/ServerStatus.xml.aspx/
When I replace example.xml with the above link it fails to work. So the following doe not work. Where I link to an external path rather than a local.
<?php
include('render_xml_to_html.php');
// The external path DOES NOT WORK
render_xml_data('https://api.eveonline.com/server/ServerStatus.xml.aspx/');
?>
Thanks in advance!
You can just use file_get_contents on this one, it can get the job done. Consider this example:
$url = 'https://api.eveonline.com/server/ServerStatus.xml.aspx/';
// access the url and get that file
$contents = file_get_contents($url);
// convert it to an xml object
$contents = simplexml_load_string($contents);
echo "<div class='record'>Number of Online Players: ".$contents->result->onlinePlayers."</div>";
Sample Output:
Number of Online Players: 23893

Why are the html-tags inside <noscript> shown as text

I have a noscript part:
<noscript>
<h1><?php echo $php_title; ?></h1>
<div><?php echo $php_abstract; ?></div>
</noscript>
When I try this in a .html file (with the php tags removed, of course) it works as expected, but when in a .php file I get this visible output in the browser (i.e. the is not treated as an html tag):
<h1>Stephen Porges "The Polyvagal Theory"</h1>
I do not set any special headers with PHP:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once 'HTTP/Request2.php';
$url = "https://api.zotero.org/groups/56508/items/3B6TR25A?format=atom&content=json";
$r = new HTTP_Request2($url, HTTP_Request2::METHOD_GET);
$r->setConfig(array(
'ssl_verify_peer' => FALSE,
'ssl_verify_host' => FALSE
));
try {
$response = $r->send();
if ($response->getStatus() == 200) {
$body = $response->getBody();
$xml = new SimpleXMLElement($body);
$php_content = $xml->content;
$php_json = json_decode($php_content);
$php_title = $php_json->title;
$php_abstract = $php_json->abstractNote;
}
} catch (HttpException $ex) {
echo $ex;
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
The document is returned as text/html according to the browser.
I use Chrome and there is maybe a bug here, but it seems strange that it works ok in .html but not .php if that is the reason.
Any idea of what is going on here?
This is an issue with chrome where it is not rendered the first time the browser loads the page with JavaScript disabled. If you refresh the page after it shows plain text, it should be rendered properly.
This issue has already been reported:
https://code.google.com/p/chromium/issues/detail?id=235158
One person from that website suggested a workaround of using something like:
<div id="noscript">What was in the noscript-tag ..... </div>
<script type="text/javascript">
document.getElementById('noscript').style.display="none";
// rest of script
</script>
Therefore, it would only hide the elements if JavaScript is enabled.
I wouldn't say that it is that big of a deal. For example, Stack Overflow uses <noscript> tags regardless and the same occurs.

Reading a php file from another php file

I currently have a php file that I'm using as a template but I need it to read in data from another php file that I'm using for the page content. I'm doing it this way to save on code and time, however it doesn't appear to be working. I have done a test with shorter amounts of code but it still isn't working. they are both .php files.
Code -
<html>
<head>
<title></title>
</head>
<body>
<?php
$temp = 'test-2.php';
$file = fopen($temp, 'r');
$cont = fread($file, filesize($temp));
print $cont;
fclose($file);
?>
</body>
test-2.php
<?php
echo 'hello world';
?>
just use <?php include('test-2.php'); ?> surely that'll do what you want?

get a text file using php and send the string to javascript

Ok, what I am trying to do is make a javascript loop of images, but first I have to get a list of the images. In javascript there is no way to directly grab this text file... http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt but it can be done eaisly in php, I am currently gettung the txt file using php, but the javascript cannot read the variable. How can I make javascript be able to read this variable. Here is what I have...
<?php
$file = "http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt"; //Path to your *.txt file
$contents = file($file);
$string = implode($contents);
echo $string;
?>
<script type="text/javascript">
function prnt() {
var whatever = "<?= $string ?>";
alert(whatever);
}
</script>
You can use echo or print to write to the page in PHP.
var whatever = "<?php echo $string; ?>";
Although, if the file has line breaks in it, you will need to remove those.
Make it a bit more interesting: go ahead and split the fields and use JSON encoding. It should read directly in javascript without needing to call JSON.parse() on the client.
<?php
$lines = file_get_contents('http://...');
$lines = explode("\n",trim($lines));
foreach ($lines as &$line) {
$line = preg_split('/,? /',$line);
}
$js = json_encode($lines);
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
var dar = <?php echo $js; ?>;
</script>
</body>
</html>
You should also consider using a local proxy to cache the results of that file if you plan to run this frequently and especially if you are going to serve it up on a public web server somewhere. Store the file locally as "noaa_data.txt" and have a second script on a cron job (12 hours or something):
<?php
file_put_contents("/var/www/noaa_data.txt",file_get_contents("http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt"));
?>

Categories