Send 404 header after page load - php

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

Related

Getting 302 redirects when testing website on pingdoms and others

I am not able to identify how and where it is happening. When i run a test on pingdom, every 3 out of 5 times it will show in the result that my website www.filliplingua.com is redirected to "/". I am giving the link to the reults below:
http://tools.pingdom.com/fpt/#!/bpgda9/www.filliplingua.com
It is a joomla website. I even reset my .htaccess. And turned off redirect plugin in joomla and cleared all kinds of caches. Still it is showing. Can u please help me find out how to solve is.
If the redirect is originating from PHP it's programmed with the header() function, and that function will throw a warning if the output has already started, because the first output will send the HTTP headers.
PHP Manual about header():
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
So what you can do in index.php is start the file with any output, like echo "here";
and this will trigger a warning when the script is trying to redirect, the redirect will fail, and in the error description (in the log or on the page, depending on your error-reporting settings) you will be able to see what file the redirect originates from. From there, you will probably figure out why it tries to redirect.
Good luck!

How to show custom 404 error page if dynamic URL is entered wrong without changing url address in browser

I have a page "errors.php" which contains header, footer, sidebar and is beautifully decorated. In my .htaccess file, i have - ErrorDocument 404 /errors.php.
Now if someone goes to a file or directory which does not exist, for e.g. www.mywebsite.com/nofile, he is seeing beautiful 404 errors page. It's fine
The problem is - I have rewrite rule in .htaccess which turns www.mywebsite.com/view?id=1 into www.mywbsite.com/view/this-is-seo-url-page. This fine and working. Now I want if someone type wrong url then show him 404/errors, for e.g. www.mywebsite.com/view/this-is-wrong-url
In view.php, I have this-
<?php
include('header.php');
//make a database query and fetch data from tables
//To check write or wrong url, I am doing this
if ($row['friendly_url'] != $_GET['id']) {
header("HTTP/1.1 404 Not Found");
include('./errors.php');
exit();
}
include('sidebar.php);
include('footer.php');
This is working fine but since errors.php also contain header.php file, I am getting header already sent errors. So I want solution something like I am redirecting user to errors.php page but in browser address bar URL remain same as user enters. If I do header(location...) then url in browser gets changed to new destination.
This will not be resolved using PHP, but with logic. You need to determine from the URL wether the page is correct or not before any output is sent to the browser, and then set the headers and include the right files accordingly.
Read URL
Determine if the URL is valid
If valid:
include('header.php');
include('page.php);
include('sidebar.php);
include('footer.php');
If NOT valid
Set 404 header
include('header.php');
include('error.php);
include('sidebar.php);
include('footer.php');
This logic allows you to set headers() and include includes() based on logicical decisions made at the top of the script - keeping your URL the same
In your example, if your include('header.php'); includes any output, then your header("HTTP/1.1 404 Not Found"); will fail anyway, as you cannot send any output before the headers.
my goodness! I solved it with "include_once();".
Actually as I said above in my question that I have used - include('header.php'); in both files i.e. in view.php and in errors.php. So when errors.php page is triggered when visitors are in view.php, the two headers.php are conflicting and causing many issues such as header already sent, session/db host/db name already declared blah.. blah...
So in page errors.php, I changes include('header.php'); to include_once('header.php');. Now when errors.php is triggered only one header.php work other one is ignored and thus everything goes fine.
Some may think why I do not remove the line "include('header.php');" totally from errors.php if it is conflicting. If I remove this line totally then assume if 404 errors is triggered because of wrong static url to files/directory in my root then my errors.php will appear to visitors without header which will break other functions of the page.
Hope it is clear what I mean.

php move user to 404 page after typing invalid url

I'm designing a website but I know if the user enters a wrong character into my url, a not found page will open for him . and I know it can be a way to hack my website. What should I do for that? for example if the user enters a ' into my url like this:
http://example.com/article.php?id=585'
He move to a not found page which I have designed it or move to the first page or the last page he was in.
Thanks.
You have to take 2 things into consideration:
Handling non-existent files
Handling non-existent article ids
Here's how to handle each case:
1) Create an .htaccess file and place it in your website root folder:
RewriteEngine on
ErrorDocument 404 /error.php # change this to your own 404 file path
2) Open the articles.php file and add this to the top (right after checking if your ID exists)
if(!valid_id($id)) {
//if you have php 5.3- use this
header('HTTP/1.1 404 Not Found');
//if you have php 5.4+ use this
//http_response_code(404);
include('error.php'); //change this path to your own 404 file
die();
}
Obviously, valid_id() is just a function example.
You will have to create a custom 404 page. So when your website doesn't get that page, it will show your custom page.
Try this link for custom page.
By the way from id=585'(apostophe after 585), I mean you want to prevent sql injection. Right? Just sanitise the input, that is, check if id is valid for not. You can find a lot of tutorial for that, just google it.
P.S : Believe me, It would take a lot more then a 404 Page to hack your server
just use this:
Open the articles.php file and add this to the top (right after checking if your ID exists)
if(!valid_id($id)) {
header('location:error.php'); exit();//change this path to your own 404 file
}
valid_id() is just a checking function example.

If $_SERVER['HTTP_REFERER'] was 404 Page Not Found

In PHP is there any way to catch a 404 not found?
If a user ends up on a 404, I want them to be redirected to a known page, but to display something different if it is due to a 404 error.
Something like
if($_SERVER['HTTP_REFERER'] == 404){
echo("You've been redirected!");
}
Thanks in advance
PHP is only given the path to the page that referred you to the current page, it can't retrieve the status code for that page.
You shouldn't need to redirect the page when the page specified doesn't exist. In Apache you can specify the ErrorDocument to be a PHP file, just append a query string to the file such as ErrorDocument /index.php?error=404 so that your PHP file knows the page being requested doesn't exist. This way you can display the error straight to the user on the same page and the URL isn't lost. You don't need session or server variables, just a $_GET['error'] to check if there is an error code provided to the page.
Or, you can specify a pre-built document that is just a 404 error page, such as an ErrorDocument my404error.html, which will be displayed without any server-side processing for the page which is not found.

PHP or htaccess make dynamic url page to go 404 when item is missing in DB

Typical scenario:
DB items are displaied in page http://...?item_id=467
User one day deletes
the item
Google or a user
attempts to access http://...?item_id=467
PHP diggs into DB and sees items does not exist anymore, so now PHP must tell
Google/user that item is not existing via a 404 header and page.
According to this answer I undertstood there is no way to redirect to 404 Apache page via PHP unless sending in code the 404 header + reading and sending down to client all the contents of your default 404 page.
The probelm: I already have an Apache parsed custom 404.shtml page, so obvioulsy I would like to simply use that page.
But if i read an shtml page via PHP it won't be parsed by Apache anymore.
So what do you suggest me to do?
Is there maybe some trick I could use palying with htaccess too?
Thanks,
Hmm. Two ideas come to mind:
Redirect to the 404 page using header("Location:...") - this is not standards-compliant behaviour though. I would use that only as a last straw
Fetch and output the Apache-parsed SHTML file using file_get_contents("http://mydomain.com/404.shtml"); - also not really optimal because a request is made to the web server but, I think, acceptable in most cases.
I doubt there is anything you can do in .htaccess because the PHP script runs after any rewrite rules have already been parsed.
IF you are using apache mod_php, use virtual('/404.shtml'); to display the parsed shtml page to your user.
I was trying to do this exact same thing yesterday.
Does Pekka's file_get_contents/include result in a 404 status header being sent? Perhaps you need to do this before including the custom error page?
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
You can test using this Firefox extension.
I was looking exactly for something like you needed, so you have a page:
http://example.com/page?item_id=456
and if later you want that if item is missing you are redirected to:
http://example.com/page_not_found?item_id=456
In reality I found it is much more maintainable solution to just use the original page as 404 page.
<?php
$item = findItem( $_GET['item_id']);
if($item === false){
//show 404 page sending correct header and then include 404 message
header( $_ENV['SERVER_PROTOCOL'].' 404 Not Found', true );
// you can still use $_GET['item_id'] to customize error message
// "maybe you were looking for XXX item"
include('somepath/missingpage.php');
return;
}
//continue as usual with normal page
?>
So if item is no longer in the DB, the 404 page is showed but you can provide custom items in replace or error messages.

Categories