PHP display alternate page if condition is true - php

I am using the following code to display a 404 page if the user requests a URL which doesn't match an article in the database:
if($articleTitle == "")
{
header('HTTP/1.0 404 Not Found');
readfile('404.php');
exit();
}
readfile properly displays a webpage, but it does not parse PHP code in it. Is there an alternative to readfile that displays a different file but parses PHP in that other file? Since this is a 404, a redirect would be bad practice.

readfile only slurps in raw bytes and spits them out to the client. You want include(), which WILL try to execute any PHP found in the loaded file.

Related

PHP Header what is the use?

I have read a tutorial, and in that tutorial they make a error function.
When the function was called it runs:
<?php
header('HTTP/1.0 404 Not Found');
include('errorpage.php');
exit();
?>
But what is the use of that? Why can't you use header('Location: errorpage.php') or skip the part header('HTTP/1.0 404 Not Found')?
If you use header('Location: errorpage.php') then you are saying "The document you want can be found here". This is a lie.
If you don't include header('HTTP/1.0 404 Not Found') then you are saying "OK, here is the document you asked for" and then displaying an error message. This is a lie.
If the error page is for an attempt from a browser to run a JavaScript, it will try to execute the HTML as JS and throw an error.
If the client is a search engine, it will index the error page as content instead of treating the link as broken. This will give you bad results in searches.
If the client is a downloading tool, it will download the document as a file. If it is going recursively, it could end up following vast numbers of links to error pages on your server and fill up the user's hard disk while eating lots of your bandwidth.
And so on.
In short, if you don't tell the client it is an error then it will treat it as content.

PHP file download issue - stop redirection if file does not exist while using GET method

I have main.php file, on which I have many "sub pages" (there are tabs and you can switch them so http://mydomain.com/main.php address does not change). I receive them dynamically via ajax requests. On one of such "sub page" I have download links. For example
fish
in dwnl.php file I have something like this
// . . . . .
$file =basename($_GET['file']);
if(file_exists($file))
{
// download file
}
else exit;
my problem occurs when file does not exist (i.e. in 'else' block of my dwnl.php file). If users click such link, browser redirects them to http://mydomain.com/dwnl.php?file=... address. How can I forbid such redirection? I would like to do it using PHP (if it is possible). So, what should I do in 'else' block?
In else you can redirect to $_SERVER['HTTP_REFERER'];
This is redirect to your referer page.
Else if possible to check earlier
you can check file_exist and place href if file exists.
One possible solution, depending on the way your script is setup, is to use a header redirect.
<?php
header( "LOCATON: /not-found.php" );
die();
?>
This will redirect the user to whatever page you want. As some other people have already said though, you should be very careful about dealing with file downloads in that way to prevent various exploits. I would sanitize the filename before passing into any functions that grab file contents and also limit the possible download directories to only the locations you absolutely need to download from. Don't trust open_basedir to protect you in any of the above situations, either.
1) You may output a simple html with an error message and with a timeouted meta refresh tag.
Redirect to http://example.com/ after 5 seconds:
<meta http-equiv="refresh" content="5;URL='http://example.com/'">
2) You may use header() to redirect immediatelly without any message:
header("Location: http://site.com/page?var=123");
3) You may set error 404 file not found:
header('HTTP/1.0 404 Not Found', true, 404);

Send 404 header after page load

I'm trying to send a 404 header after the page loads and was wondering if there were any solutions. Essentially, a database is searched to see if the url is valid and corresponds to valid content. If it doesn't, it will "include()" an error.php file.
Is there anyway that I can write an htaccess rule that says, whenever this file is loaded, throw a 404? How else could I send that 404 inside of the error.php file, since it is not the first thing to be displayed?
Call this first on error.php, before outputting any error text.
<?php
header("HTTP/1.0 404 Not Found");
?>
You can always use the header-function, just remember to do that before you output anything else.
I would recomend doing that instead of including another file, and then configure your server to serve an appropiate 404 file.
PHP docs header function

How do I load content from a PHP file (and executing the script) from another PHP file?

I have a PHP script (index.php) that changes the page shown depending on the query part of the URL (using GET). All the links in the page access different "pages" using ?page=pageName and the index.php script loads HTML from text files accordingly (echoing it to the screen).
So, if a user goes to index.php?page=about, my PHP script loads a file called about.php and echoes it in a view container in the browser.
However, I have a big problem: The content I'm loading has PHP scripts inside it, but those scripts aren't executed when echoed using the index.php script. That makes it impossible for me to load a page that contains, say, a directory listing pulled from a MySQL database.
So basically, I want to know if there is any way that I can echo a PHP file onto a page but execute the PHP code inside the file as well.
For clarity, I have attached an annotated screenshot that describes what I mean:
EDIT: Here's the link:
Use if statements to include('about.php') in index.php, and put the echo statements inside about.php. If this doesn't work, please post code examples.
if( $_REQUEST['someQuery'] == 'about' )
{
include('about.php');
}
Using include() will include the content of another PHP script and execute it. If that other PHP script contains functions that produce the output then you will need to invoke them separately.
Please don't start your sentences with conjunctives.
changes the page shown depending on the URL
Doesn't that happen with most web pages?
access different "pages" using ?page=pageName
Oh - you mean by the query part of the URL - a front controller pattern - yeuch!
I can echo a PHP file onto a page but execute the PHP code inside the file as well.
Do you mean you want to see the PHP source code and the output of the code? Or just the output of the code?
In your front controller:
<?php
if (realpath($_REQUEST['page'])!=$_REQUEST['page']) {
header("HTTP/1.1 500 Internal Server Error");
die ("Naughty!");
}
$script=SOME_PATH . $_REQUEST['page'] . ".php";
if (!file_exists($script) || !is_readable($script)) {
header("HTTP/1.0 404 Not Found");
die ("File not found");
}
print "src = <br />";
highlight_file($script);
print "<hr />Output:<br />";
include($script);

Question related to 404 and PHP

So I'm using a single entry point found in a previous question of mine: How to include config.php efficiently?
We all know what 404 errors is, so no explanation needed there. However, when using the single entry point index.php?page=pokemon, it doesn't go to the 404 page when trying to access a page that is non-existent. So how can I solve this problem which would make it more user friendly and direct the visitors to my 404 page so they won't see all the PHP errors?
You should output your own error page (you could just include() a .html file, for example), and set the HTTP status code using the header() function:
header("HTTP/1.0 404 Not Found");
Of course, you must set the header before including the error template.
I assume you do sort of an if / elseif or a switch on the variable $page to figure out which page to display, right?
If so, just add an ELSE resp. default: branch which will display a custom error note
to the user if an unexpected value is passed as $page.
HTH
If you’re actually using user187291’s code, alter it like this:
$page = "home";
if (isset($_GET['page'])) {
$page = $_GET['page'];
}
$file = "$page.php";
if (preg_match('/\W/', $file) || !is_file($file)) {
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);
// print error message
exit;
} else {
include $file;
}
But since you’re using header, you need to make sure that no output has been sent to the client. Otherwise the HTTP header is already sent and you cannot modify it. You can use the output control functions to buffer any output and discard it in case of an error.

Categories