php/html file is not displayed by server - php

I am extremely knew to working with databases and servers and just downloaded MAMP. I have a website I made in html and css and want to inject a php script to it. I have saved the file in .php and when I navigate to it from the localhost port on my browser, none of the html is displayed. It only shows a blank white page. There is probably a really obvious answer but I've been searching google for an hour and haven't found a solution.
This is the php script. It is wrapped in a tag everything else in the document is html.
<?PHP
$filelocation = "Text.txt";
if (!file_exists($filelocation)) {
echo "Couldn't find datafile, please contact the administrator.";
}
else {
$newfile = fopen($filelocation,"r");
$content = fread($newfile, filesize($filelocation));
fclose($newfile);
}
$content = stripslashes($content):
$content = htmlentities($content):
$content = nl2br($content);
echo $content;
?>

Most likely there's an error in your PHP code and it can't be parsed. Check the server logs to see what the error message is.
That seems to be valid PHP at a glance.
You could read the file more easily by doing...
$content = file_get_contents($filelocation);
but that's incidental.
Turn on Error reporting in your php.ini file and then restart your webserver. This should give more detailed error information. You should also check your server error logs as there's usually something in there too.
Are you getting an HTTP 500 response code with the blank page? Also, are you sure the file in question actually has any contents?

You have two syntax errors in your code:
$content = stripslashes($content):
$content = htmlentities($content):
They must end with semicolon
$content = stripslashes($content);
$content = htmlentities($content);
Besides that, your errors are likely catched and written to logs as said by others.

Most probably you have a php / php syntax error.
On the first line of your .php file write the following:
<?php error_reporting(E_ALL); ?>
this should make the interpreter to show you the errors you have.
Also, more details about your problem won't hurt.

Related

How to process PHP code in a text string, to prevent it from being seen as text?

I'm using the Redactor editor in a custom built CMS. Redactor has an option, phpTags, which when set to true allows PHP code to be entered and saved as part of the content.
The issue is that this PHP code is being seen as text, not PHP code, and is being escaped rather than being processed.
For example, if I enter this in the editor:
<?php echo date('Y'); ?>
Instead of the year being displayed, the code is commented out in the page's markup, like so:
<!--?php echo date('Y'); ?-->
How can I prevent this from happening? To make sure the PHP code is processed/interpreted as such by the server?
I should probably mention that there are a lot of people using this CMS, so there's no way to know what PHP code may be added in advance.
Perhaps
<!-- <?php echo date('Y') ?> -->
You can't change PHP's opening/closing tags like you are, not without a recompile of PHP. If you want to hide php's output, then surround the entire php code block with html comment tags.
PHP won't care about the html comments. It couldn't care at all what it's embedded in. You could stuff a PHP code block into the middle of a .jpg file and it'd still execute, as long as the webserver's configured to run .jpg files through the PHP interpreter.
To fix this issue I took the content I was previously just displaying via echo, and saved it to a temporary file.
Then I turned on output buffering, included that temporary file in the PHP script, and grabbed its contents via ob_get_contents().
This allowed me to display the content with all the PHP within having been parsed. Here's the code for reference:
// Create path to temporary file
$tmpPath = '/temp.php';
// Set file variable to null for error checking
$tmpFile = NULL;
// Try creating the temporary file
if ( $tmpFile = fopen($tmpPath, 'w') ) {
if ( fwrite($tmpFile, $postContent) === FALSE ) {
// Do something if the file can't be written to
} else {
// Close file
fclose($tmpFile);
}
}
// Start output buffereing
ob_start();
// Include the temporary file created above
include $tmpPath;
// Save buffered contents to a variable
$content = ob_get_contents();
// End output buffering
ob_end_clean();
// Display content
echo $content;
I appreciate the various comments to my question, as it helped prod me in the right direction to getting this figured out.

How to log errors for move_uploaded_file to a file

I have some code that uploads a file, its the exact same code i had working on another server but its not working on this new server
// Move the file into the new folder
move_uploaded_file($_FILES["file"]["tmp_name"],'./img/myfolder/1/'. $_FILES["file"]["name"]);
I know i can use:
if(move_uploaded_file($_FILES["file"]["tmp_name"],'./img/myfolder/1/'. $_FILES["file"]["name"])){
echo "success";
} else{
echo "failure";
}
However i have 2 problems, the script is not ran directly from the page, another application which i dont have access to source code to calls that page and sends the image. So i cant do any in page errors i need to log the errors to a file.
The 2nd problem and the main issue is i am not sure how to find out what the error is. Is there an error code i can pull if the else statement is called. I have set it to 777 for the folders and subfolders just for testing purposes to rule out permission issues, ill fix that after getting the problem resolved before pushing to production.
Also i checked the apache server error.log file and it shows nothing
Here i would do something like this.
$debug_file = _DIR_.'/debug.txt';
$source = $_FILES["file"]["tmp_name"];
$dest = './img/myfolder/1/'. $_FILES["file"]["name"];
if(! #move_uploaded_file($source,$dest) ){
file_put_contents( $debug_file, "ERROR[ ".date('Y-m-d H:i:s')." ] Could not move[ $source ] to[ $dest ]\n", FILE_APPEND);
exit();
}
Then when you have the source and dest paths you can make sure they actually exist in the right places.
-note- the # sign will suppress the normal PHP warning for failing to move the file, but as we are logging it our self, this just prevents it from getting in the way.
Also I put an exit in, I'm assuming its a requirement of this script to have the file to work properly, and that way it's enough just to fail, no need to check for success.
Most likely, the file path is wrong
Also you could even output buffer the php error as well like this,
ob_start();
$moved = move_uploaded_file($source,$dest);
$message = ob_get_clean();
if(!$moved){
file_put_contents( $debug_file, "ERROR[ ".date('Y-m-d H:i:s')." ] Could not move[ $source ] to[ $dest ] PHP message[ $message ]", FILE_APPEND);
exit();
}
Output buffing works wonders on scripts ran in the background,
http://php.net/manual/en/function.ob-get-clean.php

file_get_contents() not able to fetch data?

I searched several posts similar to this but could not find an answer. I am probably missing out something small.
I am trying to read JSON contents from a URL as shown by my code:
$uri = "http://worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710";
echo "URI: [$uri] <br/>";
$file = file_get_contents($uri);
$error = error_get_last();
echo $error['message'];
If I open the URL in a browser, I can see the JSON contents of it. But the above mentioned code does not work. $file has a value of false. The error message is:
file_get_contents(http://worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710) [function.file-get-contents]: failed to open stream: No such file or directory.
Any suggestions? NOTE: my allow_url_fopen is set to 1 if it matters.
Edit:
Here is the entire PHP file.
http://pastebin.com/zCKEP9kG
Also, there is an fopen() in the code which opens an http file just fine.
I don't see anything wrong with the code, mate - it runs fine locally on my setup and I can get the file, and can do whatever I like with it.
Try it running on a different host - may be your php.ini is messed up and is messing up the script as well.. Or may be you've got problem with some other spot of the source.. may be if you shared the entire file source, or at least a bigger chunk of it..
Cheers!
Check this code, i think you can proceed further with this now --
<?php
$json_url = "http://worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
#ascii-lime
its for #ascii-lime--
Check this (Edit#2)
Try This :
<?php
header('Content-Type: application/json');
$json = file_get_contents('http://worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710');
echo $json;
?>

PHP - file_get_contents() automatically echoes to the HTML page

I have a page on a remote server with the following line:
$contents = file_get_contents($search_url);
which automatically echoes $contents to the HTML page no matter what I do. It's as if I have done the following:
$contents = file_get_contents($search_url);
echo $contents;
What could be causing PHP to do this? Is there any configuration item that needs changing?
It might be worth taking a look at this bit of your code. If you comment it out, does the same thing still happen?
<?php if (isset($debug) && isset($ret_value)):?>
<pre>
<?php print_r($ret_value) ?>
</pre>
<?php endif; ?>
This does appear to echo what you have previously fetched in the file_get_contents().
It was a STUPID bug - the variable $contents is being used in the included file as well as in the function it is included from. This caused the issue - nothing wrong with file_get_contents!

PHP flat file download counter

I got this freely available php-script to track download statistics. Simple really, it just count downloads and pass it on to a log file and another script uses that log file to display a top 10 list. So it's exactly what I need so I would really like to make this script work. But it doesn't. Of course. I have limited knowledge in php (but have learned a lot since encountering this script!). According to the author, it has been tested on Apache- and php-versions similar to mine, without problems. So I have been hesitant to actually change any code. I have tried to chmod logfile and/or whole subdirectory to 666 and 777 with no success.
My own poor detective work leads nowhere and I have really tried. So I resort to the one thing I usually never do, to ask for help.
The link should have the form:
<a href=http://www.yoursite.com/downloader/download.php?number=1&file=filename.zip>
download.php follows below:
$number = $_GET['number'];
$file = $_GET['file'];
$logfile = "ROOT DIRECTORY PATH/logfile.txt";
$array[dir_1] = "URL PATH/DOWNLOADFILESFOLDER";
$download = "dir"."_"."$number";
if ($array[$download]) {
$fp = fopen($logfile,'r');
while (!feof($fp))
{
$data[] = chop(fgets($fp,4096));
}
fclose($fp);
$fp = fopen($logfile,"w");
if (flock($fp,LOCK_EX)) {
// list and split each filename and number of downloads
foreach ($data as $lines){
list($downloads,$filename,$realname) = split("\|",$lines);
// check if file already exists and add one more download if it does
if ($filename == $file){
$downloads++;
}
if ($filename <> ""){
fputs($fp,"$downloads|$filename|$realname\r\n");
}
}
flock($fp,LOCK_UN);
}
fclose($fp);
header("Location: $array[$download]/$file");
}
However one part of the script doesn't make sense to me; where does it obtain the filename and the realname so it can be put into the logfile if the file never has been downloaded before? The list() function and the array of the directory boggles my mind a bit. Though it seems logical.
If someone catches some fundamental error or have some tips on how I can continue, it would be highly appreciated.
PS. I am trying to track pdf-files if that helps.
UPDATE! By kind suggestion I ran error reporting and got an error. The faulty scripts had an error in it that I removed. I ran error checking again and only got "Notices" about undefined variables. I changed the error reporting to
error_reporting(E_ALL ^ E_NOTICE);
After that, no errors at all.
You have to change these:
$logfile = "ROOT DIRECTORY PATH/logfile.txt";
$array[dir_1] = "URL PATH/DOWNLOADFILESFOLDER";
To your actual paths.
Next time, turn on error reporting so you can know when stuff throw errors. One way to do this is adding the following line to the top of your script:
error_reporting(-1) // will show all errors
See: http://php.net/manual/en/function.error-reporting.php

Categories