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.
2
Answers
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.
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.
This logic allows you to set
headers()
and includeincludes()
based on logicical decisions made at the top of the script – keeping your URL the sameIn your example, if your
include('header.php');
includes any output, then yourheader("HTTP/1.1 404 Not Found");
will fail anyway, as you cannot send any output before the headers.