My file .htaccess handles all requests from /word_here to my internal endpoint /page.php?name=word_here. The PHP script then checks if the requested page is in its array of pages.
If not, how can I simulate an error 404?
I tried this, but it didn’t result in my 404 page configured via ErrorDocument in the .htaccess showing up.
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
Am I right in thinking that it’s wrong to redirect to my error 404 page?
asked Sep 4, 2009 at 19:29
2
The up-to-date answer (as of PHP 5.4 or newer) for generating 404 pages is to use http_response_code:
<?php
http_response_code(404);
include('my_404.php'); // provide your own HTML for the error page
die();
die() is not strictly necessary, but it makes sure that you don’t continue the normal execution.
answered Jan 11, 2017 at 14:28
![]()
bladeblade
11.3k7 gold badges36 silver badges37 bronze badges
2
What you’re doing will work, and the browser will receive a 404 code. What it won’t do is display the «not found» page that you might be expecting, e.g.:
Not Found
The requested URL /test.php was not found on this server.
That’s because the web server doesn’t send that page when PHP returns a 404 code (at least Apache doesn’t). PHP is responsible for sending all its own output. So if you want a similar page, you’ll have to send the HTML yourself, e.g.:
<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
include("notFound.php");
?>
You could configure Apache to use the same page for its own 404 messages, by putting this in httpd.conf:
ErrorDocument 404 /notFound.php
Kzqai
22.4k24 gold badges104 silver badges134 bronze badges
answered Sep 4, 2009 at 19:50
JW.JW.
50.1k36 gold badges114 silver badges141 bronze badges
3
Try this:
<?php
header("HTTP/1.0 404 Not Found");
?>
answered Sep 4, 2009 at 19:36
Ates GoralAtes Goral
136k26 gold badges135 silver badges190 bronze badges
2
Create custom error pages through .htaccess file
1. 404 — page not found
RewriteEngine On
ErrorDocument 404 /404.html
2. 500 — Internal Server Error
RewriteEngine On
ErrorDocument 500 /500.html
3. 403 — Forbidden
RewriteEngine On
ErrorDocument 403 /403.html
4. 400 — Bad request
RewriteEngine On
ErrorDocument 400 /400.html
5. 401 — Authorization Required
RewriteEngine On
ErrorDocument 401 /401.html
You can also redirect all error to single page. like
RewriteEngine On
ErrorDocument 404 /404.html
ErrorDocument 500 /404.html
ErrorDocument 403 /404.html
ErrorDocument 400 /404.html
ErrorDocument 401 /401.html
answered Mar 30, 2016 at 10:34
![]()
Irshad KhanIrshad Khan
5,5162 gold badges42 silver badges39 bronze badges
1
Did you remember to die() after sending the header? The 404 header doesn’t automatically stop processing, so it may appear not to have done anything if there is further processing happening.
It’s not good to REDIRECT to your 404 page, but you can INCLUDE the content from it with no problem. That way, you have a page that properly sends a 404 status from the correct URL, but it also has your «what are you looking for?» page for the human reader.
answered Sep 4, 2009 at 19:50
EliEli
96.3k20 gold badges75 silver badges81 bronze badges
try putting
ErrorDocument 404 /(root directory)/(error file)
in .htaccess file.
Do this for any error but substitute 404 for your error.
![]()
StackedQ
3,9011 gold badge27 silver badges41 bronze badges
answered May 20, 2018 at 19:41
![]()
In the Drupal or WordPress CMS (and likely others), if you are trying to make some custom php code appear not to exist (unless some condition is met), the following works well by making the CMS’s 404 handler take over:
<?php
if(condition){
do stuff;
} else {
include('index.php');
}
?>
answered Jan 28, 2019 at 19:38
![]()
Mike GodinMike Godin
3,5663 gold badges27 silver badges29 bronze badges
Immediately after that line try closing the response using exit or die()
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit;
or
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
die();
answered May 25, 2018 at 4:22
4
try this once.
$wp_query->set_404();
status_header(404);
get_template_part('404');
answered Mar 31, 2020 at 4:24
![]()
1
mjt at jpeto dot net ¶
13 years ago
I strongly recommend, that you use
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
instead of
header("HTTP/1.1 404 Not Found");
I had big troubles with an Apache/2.0.59 (Unix) answering in HTTP/1.0 while I (accidentially) added a "HTTP/1.1 200 Ok" - Header.
Most of the pages were displayed correct, but on some of them apache added weird content to it:
A 4-digits HexCode on top of the page (before any output of my php script), seems to be some kind of checksum, because it changes from page to page and browser to browser. (same code for same page and browser)
"0" at the bottom of the page (after the complete output of my php script)
It took me quite a while to find out about the wrong protocol in the HTTP-header.
Marcel G ¶
12 years ago
Several times this one is asked on the net but an answer could not be found in the docs on php.net ...
If you want to redirect an user and tell him he will be redirected, e. g. "You will be redirected in about 5 secs. If not, click here." you cannot use header( 'Location: ...' ) as you can't sent any output before the headers are sent.
So, either you have to use the HTML meta refresh thingy or you use the following:
<?php
header( "refresh:5;url=wherever.php" );
echo 'You'll be redirected in about 5 secs. If not, click <a href="wherever.php">here</a>.';
?>
Hth someone
Dylan at WeDefy dot com ¶
15 years ago
A quick way to make redirects permanent or temporary is to make use of the $http_response_code parameter in header().
<?php
// 301 Moved Permanently
header("Location: /foo.php",TRUE,301);// 302 Found
header("Location: /foo.php",TRUE,302);
header("Location: /foo.php");// 303 See Other
header("Location: /foo.php",TRUE,303);// 307 Temporary Redirect
header("Location: /foo.php",TRUE,307);
?>
The HTTP status code changes the way browsers and robots handle redirects, so if you are using header(Location:) it's a good idea to set the status code at the same time. Browsers typically re-request a 307 page every time, cache a 302 page for the session, and cache a 301 page for longer, or even indefinitely. Search engines typically transfer "page rank" to the new location for 301 redirects, but not for 302, 303 or 307. If the status code is not specified, header('Location:') defaults to 302.
mandor at mandor dot net ¶
16 years ago
When using PHP to output an image, it won't be cached by the client so if you don't want them to download the image each time they reload the page, you will need to emulate part of the HTTP protocol.
Here's how:
<?php// Test image.
$fn = '/test/foo.png';// Getting headers sent by the client.
$headers = apache_request_headers(); // Checking if the client is validating his cache and if it is current.
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($fn))) {
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 304);
} else {
// Image not cached or cache outdated, we respond '200 OK' and output the image.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 200);
header('Content-Length: '.filesize($fn));
header('Content-Type: image/png');
print file_get_contents($fn);
}?>
That way foo.png will be properly cached by the client and you'll save bandwith. :)
php at ober-mail dot de ¶
3 years ago
Since PHP 5.4, the function `http_response_code()` can be used to set the response code instead of using the `header()` function, which requires to also set the correct protocol version (which can lead to problems, as seen in other comments).
bebertjean at yahoo dot fr ¶
14 years ago
If using the 'header' function for the downloading of files, especially if you're passing the filename as a variable, remember to surround the filename with double quotes, otherwise you'll have problems in Firefox as soon as there's a space in the filename.
So instead of typing:
<?php
header("Content-Disposition: attachment; filename=" . basename($filename));
?>
you should type:
<?php
header("Content-Disposition: attachment; filename="" . basename($filename) . """);
?>
If you don't do this then when the user clicks on the link for a file named "Example file with spaces.txt", then Firefox's Save As dialog box will give it the name "Example", and it will have no extension.
See the page called "Filenames_with_spaces_are_truncated_upon_download" at
http://kb.mozillazine.org/ for more information. (Sorry, the site won't let me post such a long link...)
tim at sharpwebdevelopment dot com ¶
4 years ago
The header call can be misleading to novice php users.
when "header call" is stated, it refers the the top leftmost position of the file and not the "header()" function itself.
"<?php" opening tag must be placed before anything else, even whitespace.
nospam at nospam dot com ¶
6 years ago
<?php// Response codes behaviors when using
header('Location: /target.php', true, $code) to forward user to another page:$code = 301;
// Use when the old page has been "permanently moved and any future requests should be sent to the target page instead. PageRank may be transferred."$code = 302; (default)
// "Temporary redirect so page is only cached if indicated by a Cache-Control or Expires header field."$code = 303;
// "This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource and is not cached."$code = 307;
// Beware that when used after a form is submitted using POST, it would carry over the posted values to the next page, such if target.php contains a form processing script, it will process the submitted info again!
// In other words, use 301 if permanent, 302 if temporary, and 303 if a results page from a submitted form.
// Maybe use 307 if a form processing script has moved.
?>
yjf_victor ¶
7 years ago
According to the RFC 6226 (https://tools.ietf.org/html/rfc6266), the only way to send Content-Disposition Header with encoding is:
Content-Disposition: attachment;
filename*= UTF-8''%e2%82%ac%20rates
for backward compatibility, what should be sent is:
Content-Disposition: attachment;
filename="EURO rates";
filename*=utf-8''%e2%82%ac%20rates
As a result, we should use
<?php
$filename = '中文文件名.exe'; // a filename in Chinese characters$contentDispositionField = 'Content-Disposition: attachment; '
. sprintf('filename="%s"; ', rawurlencode($filename))
. sprintf("filename*=utf-8''%s", rawurlencode($filename));header('Content-Type: application/octet-stream');header($contentDispositionField);readfile('file_to_download.exe');
?>
I have tested the code in IE6-10, firefox and Chrome.
sk89q ¶
14 years ago
You can use HTTP's etags and last modified dates to ensure that you're not sending the browser data it already has cached.
<?php
$last_modified_time = filemtime($file);
$etag = md5_file($file);
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: $etag");
if (@
strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||
trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
header("HTTP/1.1 304 Not Modified");
exit;
}
?>
David ¶
5 years ago
It seems the note saying the URI must be absolute is obsolete. Found on https://en.wikipedia.org/wiki/HTTP_location
«An obsolete version of the HTTP 1.1 specifications (IETF RFC 2616) required a complete absolute URI for redirection.[2] The IETF HTTP working group found that the most popular web browsers tolerate the passing of a relative URL[3] and, consequently, the updated HTTP 1.1 specifications (IETF RFC 7231) relaxed the original constraint, allowing the use of relative URLs in Location headers.»
ben at indietorrent dot org ¶
10 years ago
Be aware that sending binary files to the user-agent (browser) over an encrypted connection (SSL/TLS) will fail in IE (Internet Explorer) versions 5, 6, 7, and 8 if any of the following headers is included:
Cache-control:no-store
Cache-control:no-cache
See: http://support.microsoft.com/kb/323308
Workaround: do not send those headers.
Also, be aware that IE versions 5, 6, 7, and 8 double-compress already-compressed files and do not reverse the process correctly, so ZIP files and similar are corrupted on download.
Workaround: disable compression (beyond text/html) for these particular versions of IE, e.g., using Apache's "BrowserMatch" directive. The following example disables compression in all versions of IE:
BrowserMatch ".*MSIE.*" gzip-only-text/html
dev at omikrosys dot com ¶
13 years ago
Just to inform you all, do not get confused between Content-Transfer-Encoding and Content-Encoding
Content-Transfer-Encoding specifies the encoding used to transfer the data within the HTTP protocol, like raw binary or base64. (binary is more compact than base64. base64 having 33% overhead).
Eg Use:- header('Content-Transfer-Encoding: binary');
Content-Encoding is used to apply things like gzip compression to the content/data.
Eg Use:- header('Content-Encoding: gzip');
chris at ocproducts dot com ¶
6 years ago
Note that 'session_start' may overwrite your custom cache headers.
To remedy this you need to call:
session_cache_limiter('');
...after you set your custom cache headers. It will tell the PHP session code to not do any cache header changes of its own.
shutout2730 at yahoo dot com ¶
14 years ago
It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to.
This redirects to 2.html since the second header replaces the first.
<?php
header("location: 1.html");
header("location: 2.html"); //replaces 1.html
?>
This redirects to 1.html since the header is sent as soon as the echo happens. You also won't see any "headers already sent" errors because the browser follows the redirect before it can display the error.
<?php
header("location: 1.html");
echo "send data";
header("location: 2.html"); //1.html already sent
?>
Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren't sent until the output buffer is flushed.
<?php
ob_start();
header("location: 1.html");
echo "send data";
header("location: 2.html"); //replaces 1.html
ob_end_flush(); //now the headers are sent
?>
jp at webgraphe dot com ¶
19 years ago
A call to session_write_close() before the statement
<?php
header("Location: URL");
exit();
?>
is recommended if you want to be sure the session is updated before proceeding to the redirection.
We encountered a situation where the script accessed by the redirection wasn't loading the session correctly because the precedent script hadn't the time to update it (we used a database handler).
JP.
David Spector ¶
1 year ago
Please note that there is no error checking for the header command, either in PHP, browsers, or Web Developer Tools.
If you use something like "header('text/javascript');" to set the MIME type for PHP response text (such as for echoed or Included data), you will get an undiagnosed failure.
The proper MIME-setting function is "header('Content-type: text/javascript');".
mzheng[no-spam-thx] at ariba dot com ¶
14 years ago
For large files (100+ MBs), I found that it is essential to flush the file content ASAP, otherwise the download dialog doesn't show until a long time or never.
<?php
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
?>
razvan_bc at yahoo dot com ¶
5 years ago
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>
this example is pretty good BUT in time you use "exit" the parser will still work to decide what's happening next the "exit" 's action should do ('cause if you check the manual exit works in others situations too).
SO MY POINT IS : you should use :
<?php
header
('Location: http://www.example.com/');
die();?>
'CAUSE all die function does is to stop the script ,there is no other place for interpretation and the scope you choose to break the action of your script is quickly DONE!!!
there are many situations with others examples and the right choose for small parts of your scrips that make differences when you write your php framework at well!
Thanks Rasmus Lerdorf and his team to wrap off parts of unusual php functionality ,php 7 roolez!!!!!
Angelica Perduta ¶
2 years ago
I made a script that generates an optimized image for use on web pages using a 404 script to resize and reduce original images, but on some servers it was generating the image but then not using it due to some kind of cache somewhere of the 404 status. I managed to get it to work with the following and although I don't quite understand it, I hope my posting here does help others with similar issues:
header_remove();
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
// ... and then try redirecting
// 201 = The request has been fulfilled, resulting in the creation of a new resource however it's still not loading
// 302 "moved temporarily" does seems to load it!
header("location:$dst", FALSE, 302); // redirect to the file now we have it
scott at lucentminds dot com ¶
13 years ago
If you want to remove a header and keep it from being sent as part of the header response, just provide nothing as the header value after the header name. For example...
PHP, by default, always returns the following header:
"Content-Type: text/html"
Which your entire header response will look like
HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Content-Type: text/html; charset=UTF-8
Connection: close
If you call the header name with no value like so...
<?php
header
( 'Content-Type:' );?>
Your headers now look like this:
HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Connection: close
Vinay Kotekar ¶
8 years ago
Saving php file in ANSI no isuess but when saving the file in UTF-8 format for various reasons remember to save the file without any BOM ( byte-order mark) support.
Otherwise you will face problem of headers not being properly sent
eg.
<?php header("Set-Cookie: name=user");?>
Would give something like this :-
Warning: Cannot modify header information - headers already sent by (output started at C:wwwinfo.php:1) in C:wwwinfo.php on line 1
Cody G. ¶
12 years ago
After lots of research and testing, I'd like to share my findings about my problems with Internet Explorer and file downloads.
Take a look at this code, which replicates the normal download of a Javascript:
<?php
if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
header("Content-type: text/javascript");
header("Content-Disposition: inline; filename="download.js"");
header("Content-Length: ".filesize("my-file.js"));
} else {
header("Content-type: application/force-download");
header("Content-Disposition: attachment; filename="download.js"");
header("Content-Length: ".filesize("my-file.js"));
}
header("Expires: Fri, 01 Jan 2010 05:00:00 GMT");
if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
header("Cache-Control: no-cache");
header("Pragma: no-cache");
}
include("my-file.js");
?>
Now let me explain:
I start out by checking for IE, then if not IE, I set Content-type (case-sensitive) to JS and set Content-Disposition (every header is case-sensitive from now on) to inline, because most browsers outside of IE like to display JS inline. (User may change settings). The Content-Length header is required by some browsers to activate download box. Then, if it is IE, the "application/force-download" Content-type is sometimes required to show the download box. Use this if you don't want your PDF to display in the browser (in IE). I use it here to make sure the box opens. Anyway, I set the Content-Disposition to attachment because I already know that the box will appear. Then I have the Content-Length again.
Now, here's my big point. I have the Cache-Control and Pragma headers sent only if not IE. THESE HEADERS WILL PREVENT DOWNLOAD ON IE!!! Only use the Expires header, after all, it will require the file to be downloaded again the next time. This is not a bug! IE stores downloads in the Temporary Internet Files folder until the download is complete. I know this because once I downloaded a huge file to My Documents, but the Download Dialog box put it in the Temp folder and moved it at the end. Just think about it. If IE requires the file to be downloaded to the Temp folder, setting the Cache-Control and Pragma headers will cause an error!
I hope this saves someone some time!
~Cody G.
Anonymous ¶
13 years ago
I just want to add, becuase I see here lots of wrong formated headers.
1. All used headers have first letters uppercase, so you MUST follow this. For example:
Location, not location
Content-Type, not content-type, nor CONTENT-TYPE
2. Then there MUST be colon and space, like
good: header("Content-Type: text/plain");
wrong: header("Content-Type:text/plain");
3. Location header MUST be absolute uri with scheme, domain, port, path, etc.
good: header("Location: http://www.example.com/something.php?a=1");
4. Relative URIs are NOT allowed
wrong: Location: /something.php?a=1
wrong: Location: ?a=1
It will make proxy server and http clients happier.
Refugnic ¶
12 years ago
My files are in a compressed state (bz2). When the user clicks the link, I want them to get the uncompressed version of the file.
After decompressing the file, I ran into the problem, that the download dialog would always pop up, even when I told the dialog to 'Always perform this operation with this file type'.
As I found out, the problem was in the header directive 'Content-Disposition', namely the 'attachment' directive.
If you want your browser to simulate a plain link to a file, either change 'attachment' to 'inline' or omit it alltogether and you'll be fine.
This took me a while to figure out and I hope it will help someone else out there, who runs into the same problem.
bMindful at fleetingiamge dot org ¶
19 years ago
If you haven't used, HTTP Response 204 can be very convenient. 204 tells the server to immediately termiante this request. This is helpful if you want a javascript (or similar) client-side function to execute a server-side function without refreshing or changing the current webpage. Great for updating database, setting global variables, etc.
header("status: 204"); (or the other call)
header("HTTP/1.0 204 No Response");
nobileelpirata at hotmail dot com ¶
15 years ago
This is the Headers to force a browser to use fresh content (no caching) in HTTP/1.0 and HTTP/1.1:
<?PHP
header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );
?>
jamie ¶
14 years ago
The encoding of a file is discovered by the Content-Type, either in the HTML meta tag or as part of the HTTP header. Thus, the server and browser does not need - nor expect - a Unicode file to begin with a BOM mark. BOMs can confuse *nix systems too. More info at http://unicode.org/faq/utf_bom.html#bom1
On another note: Safari can display CMYK images (at least the OS X version, because it uses the services of QuickTime)
er dot ellison dot nyc at gmail dot com ¶
7 years ago
DO NOT PUT space between location and the colon that comes after that ,
// DO NOT USE THIS :
header("Location : #whatever"); // -> will not work !
// INSTEAD USE THIS ->
header("Location: #wahtever"); // -> will work forever !
hamza dot eljaouhari dot etudes at gmail dot com ¶
4 years ago
// Beware that adding a space between the keyword "Location" and the colon causes an Internal Sever Error
//This line causes the error
7
header('Location : index.php&controller=produit&action=index');
// While It must be written without the space
header('Location: index.php&controller=produit&action=index');
ASchmidt at Anamera dot net ¶
4 years ago
Setting the "Location: " header has another undocumented side-effect!
It will also disregard any expressly set "Content-Type: " and forces:
"Content-Type: text/html; charset=UTF-8"
The HTTP RFCs don't call for such a drastic action. They simply state that a redirect content SHOULD include a link to the destination page (in which case ANY HTML compatible content type would do). But PHP even overrides a perfectly standards-compliant
"Content-Type: application/xhtml+xml"!
cedric at gn dot apc dot org ¶
12 years ago
Setting a Location header "returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set". If you are sending a response to a POST request, you might want to look at RFC 2616 sections 10.3.3 and 10.3.4. It is suggested that if you want the browser to immediately GET the resource in the Location header in this circumstance, you should use a 303 status code not the 302 (with the same link as hypertext in the body for very old browsers). This may have (rare) consequences as mentioned in bug 42969.
Я решил перенести большую часть файлов со старого сайта на новый. И у меня возник вопрос — «А не обвинит ли меня Yandex в использовании неуникальных статей?», т.к. у меня одни и те же материалы будут на разных страницах.
Я написал письмо в службу поддержки yandex, и мне пришло письмо, в котором сообщалось, что переживать не надо. Единственно, настоятельно желательно, чтобы я каким-то способом закрыл старые странички от индексирования (через robots.txt, вызов ошибки 404 или перенаправление) и удалил странички из базы по адресу http://webmaster.yandex.ru/delurl.xml. Удалять по указанному адресу желательно, чтобы быстрее прекратилась индексация страниц.
По некоторым причинам я предпочел способ вызова ошибки 404. Ошибка 404 вызывается в том случае, если ресурс на который идет ссылка не обнаружен. И тут я обнаружил, что у меня то и нет вызова этой ошибки, т.е. какие бы данные пользователь не ввел бы на старом сайте, что-то все равно выводится. Такая ситуация на мой взгляд не допустима, и я пошел с ней бороться.
Мой сайт написан был на php, поэтому я очень быстро нашел команду для вызова ошибки 404. Она имеет вид:
header("HTTP/1.0 404 Not Found");
exit;
Казалось бы все просто, но нет же. Никак эти две команды не хотели работать. Тогда я почитал дополнительно материал и выяснил, что header() должна вызываться до отправки любого другого вывода. Т.е. она должна быть исключительно самой первой при выводе, поэтому ее нельзя использовать внутри require_once().
Но как оказалось существуют три замечательные функции, которые позволяют решить эту проблему:
-
ob_start() — задает начало области, которую надо поместить в буфер, я поместил ее самой первой при выводе.
- ob_end_flush() — окончание задания буфер и сразу вывод. Т.е. первые две функции задают область, которую сначала нужно вывести в буфер, а потом сразу вывести.
- ob_end_clean() — очищает буфер, и следующая команда как бы выводится самой первой.
С использованием этих команд организация вызова ошибки 404 выглядит следующим образом:
- Самая первая команда — ob_start()
- Далее идет основное содержание, которое пока копируется в буфер.
- Проверка на предмет вызова ошибки 404. Например, проверка наличия определенного значения. Если после проверки имеются причины вызвать ошибку, то задается код:
ob_end_clean() ; header("HTTP/1.0 404 Not Found"); exit;Тем самым будет выдано сообщение об ошибке и осуществлен выход.
- Выводим содержимое буфера командой ob_end_flush(). Идея в том, что если была вызвана ошибка, то сюда не попадем. Если ошибки не было, то выводим буфер.
Далее в файле .htaccess можно указать файл, который будет сопоставляться ошибке 404, но это уже совершенно другая история…
20.01.2021
Марат
1723
0
php | header | 404 |
header 404. Как отправить на сервер заголовок header 404.
Ошибка отправки заголовка header 404. Все темы с примерами!
Всё о header(«HTTP/1.0 404 «)
- Код php заголовка 404
- Ошибка отправки header 404
- Для чего отправлять header 404, видео
- Пример отправки header 404
- Проверить попал ли в header 404
- Скачать можно здесь
Код php заголовка 404
Для того, чтобы отправить заголовок на сервер header 404 надо написать вот такую строчку:
header(«HTTP/1.0 404 «);
Естественно, что отправка 404 на сервер с помощью header должна осуществляться в самом верху страницы.
ВНИМАНИЕ! ЭТО ВАЖНО!
В самом верху страницы — это значит, что никакого, символа, ни точки, ни пробела ни переноса — вообще ничего, если у вас есть впереди php код, то код должен быть таким:
<?
здесь может быть сколько угодно кода php //
НО! — никакого echo, print_r, var_dump и других выводящих функций!
header(«HTTP/1.0 404 «);
exit ;//
используется в том случае, если требуется остановить выполнение ниже идущего кода.
?>
Ошибка отправки header 404
Если вы отправите заголовок header 404, как показано ниже, то вы получите ошибку отправки header 404:
<?
здесь код
?>
<br> Привет мир
<?
header(«HTTP/1.0 404 «);
?>
Пример ошибки отправки header 404:
Если перед отправкой заголовка header 404 будет выводящий код, то получите ошибку.
Давайте сделаем ошибку отправки header 404 специально!!
Поместим какой-то текст произвольного содержания, перед отправкой header 404 :
echo ‘Здесь текст, который выводится ранее, чем header 404’;
header(«HTTP/1.0 404 «);
Посмотрим это на скрине:
Вывод ошибки отправки header 404
Здесь текст, который выводится ранее, чем header 404
Warning: Cannot modify header information — headers already sent by (output started at
путь/page/php/header/001_header_404.html:3) in
путь/page/php/header/001_header_404.html on line 4
Вывод ошибки отправки header 404 на странице
Для чего отправлять header 404
Чтобы не гадать — по какой из причин вам может понадобится использовать отправку заголовка header 404 -приведу собственную причину использования header 404.
На нашем сайте используется единая точка входа, — по всем запросам в адресной строке… будут перенаправляться на ту страницу, на которую настроена переадресация!
И даже те, страницы, которые не существуют… все равно будут перенаправляться… на главную.
Вот как раз для такого случая…
Естественно, что ничего не понятно!
Я делал специальное видео, где использовал приведенный код!
Видео — использование header 404
Друзья!
Мне очень нужны подписчики!
Пожалуйста подпишись на Дзене!
Заранее спасибо!
Пример отправки header 404
Для того, чтобы разобраться в том, как работает отправка заголовка header 404 нам потребуется какая-то страница, которая не существует!
Вообще любая!
Например такая :
У вас должна открыться такая страница 404 (несколько тем посвятили теме 404)

Но где здесь отправленный header 404 через php!? Этот скрин я вам привел специально — если вы захотите, то сделал отдельный архив -> сложил 404 через php + задний фон второй вариант 404 через php
И теперь, чтобы увидеть, где заголовок надо -> нажимаем ctrl + U
Нажмите, чтобы открыть в новом окне.

Проверить попал ли в header 404
Как проверить правильно ли был отправлен заголовок с помощью header 404!?
Если у вас возникли проблемы с пониманием того, что происходит заголовками, то существует огромное количество сайтов, которые могут показать всё, что вы отправляете!
Выбрал первый попавший… https://bertal.ru/ — заходим на сайт в вставляем в адресную строку свой адрес страницы.
Нажмите, чтобы открыть в новом окне.
P.S.
Вообще… после случая с санкциями… пошел посмотреть, а что вообще творится со страницами на моем другом сайте и обнаружил, что робот проиндексировал папки(директории) – как отдельные страницы – и описанная тема… как раз востребована была там.
Можете не благодарить, лучше помогите!
Название скрипта :php header 404
COMMENTS+
BBcode
In this tutorial, we are going to show you how to send a “404 Not Found” header using PHP.
This can be especially useful in cases when you need to display a 404 message if a particular database record does not exist.
By sending a 404 HTTP status code to the client, we can tell search engines and other crawlers that the resource does not exist.
To send a 404 to the client, we can use PHP’s http_response_code function like so.
//Send 404 response to client. http_response_code(404) //Include custom 404.php message include 'error/404.php'; //Kill the script. exit;
Note that this function is only available in PHP version 5.4 and after.
If you are using a PHP version that is older than 5.4, then you will need to use the header function instead.
//Use header function to send a 404 header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404); //Include custom message. include 'errors/404.php'; //End the script exit;
In the code above, we.
- Send the response code to the client.
- We include a PHP file that contains our custom “404 Not Found” error. This file is not mandatory, so feel free to remove it if you want to.
- We then terminated the PHP script by calling the exit statement.
If you run one of the code samples above and check the response in your browser’s developer tools, then you will see something like this.
Request URL:http://localhost/test.php Request Method:GET Status Code:404 Not Found Remote Address:[::1]:80 Referrer Policy:no-referrer-when-downgrade
Note the Status Code segment of the server’s HTTP response. This is the 404 header.
When should I use this?
In most cases, your web server will automatically handle 404 errors if a resource does not exist.
However, what happens if your script is dynamic and it selects data from your database? What if you have a dynamic page such as users.php?id=234 and user 234 does not exist?
The file users.php will exist, so your web server will send back a status of “200 OK”, regardless of whether a user with the ID 234 exists or not.
In cases like this, we may need to manually send a 404 Not Found header.
Why isn’t PHP showing the same 404 message as my web server?
You might notice that your web server does not serve its default “404 Not Found” error message when you manually send the header with PHP.

The default message that Apache displays whenever a resource could not be found.
This is because, as far as the web server is concerned, the file does exist and it has already done its job.
One solution to this problem is to make sure that PHP and your web server display the exact same 404 message.
For example, with Apache, you can specify the path of a custom error message by using the ErrorDocument directive.
ErrorDocument 404 /errors/404.php
The Nginx web server also allows you to configure custom error messages.
Website error pages are perhaps one of the most overlooked pieces of a fully rounded website. Not only are they important but they give you the opportunity to have a little fun. Although many web developers rely on server logs to keep an eye out for hits on error pages, I’m going to take a different approach by using a PHP generated email. In addition, we will spice up the design a bit, add basic navigation and link to the website sitemap.
About Error Pages


The most common error page — the one in which you are most likely to be familiar with — is the «404 Not Found page». More people encounter this type of error page than any other. Other common error messages you may have come across are 500 Internal Server Error, 400 Bad Request or 403 Forbidden. Wondering what the number is for? It simply refers to the HTTP code.


Default error pages are quite boring (as you can see above) and offer no purpose to visitors other than letting them know some boring error happened. For these reasons, it is a great idea to provide custom pages for the most common errors encountered. This tutorial will only cover two: the «404 Not Found» and «403 Forbidden».
Check for custom error page support
First, check to make sure your hosting provider allows you to use your own error pages. Almost all of them do, and most of them even provide a configuration area within your control panel to help you quickly create the pages. In this tutorial we will configure an Apache web server (the most common). This is easier than you might think.
Configure .htaccess
Next, connect to your server via FTP or control panel and navigate to the document root directory (usually www or public_html) which contains your website files. We will be looking for the .htaccess file. It is sometimes hidden so make sure you are viewing all files including hidden ones. If your server doesn’t have one, you can create one using any text editor. Make sure to make a backup of the .htaccess file if your server already has one.
Add the following lines to your .htaccess file:
1 |
ErrorDocument 404 /error/404.php |
2 |
ErrorDocument 403 /error/403.php |
The first half (ErrorDocument 404) is telling the server we are going to define the location of the 404 error document. The second half defines the actual location of the error document. In this case we will put it in the «error» directory and call them 404.php and 403.php, respectively.
Now save the .htaccess file and upload it to the document root directory.
Design the Custom Error Pages
It is best to stay with the same design as your website already uses so that you don’t confuse your visitors and risk losing them. You should also include helpful elements such as a polite error message, suggested links, a search feature, or a link to your sitemap. These features will depend on the level of content your website provides and what you feel will be most helpful.


As you can see below, the 404 Not Found page for Nettuts+ has stated the error and emphasized the search feature by including it in the body beneath the error message. You could take this a step further by including a short list of links to possible pages which might encourage the visitor to continue exploring more of the site (keep it simple and short though) -or even a humorous image (every one likes laughing right?). For small websites it may be a good idea to include a visible sitemap as well.


Here is something I put together for this tutorial that you can use for your website as well (included in the download above). It’s very simple so you will be able to put the content of it directly into your existing website template. As you can see, I attempted to include a little bit of a humorous element while also stating the error politely and including some options to help the visitor either find what they were looking for or continue browsing the website.


You’ll notice it does not specify the HTTP error code in the body of the page. Instead I chose to only use the error code in the title of the page. The reason for this is to keep things as simple and user friendly as possible. Most people don’t care what 404 or 403 means, they want to know what’s going on in plain English. For people who want the error code, it is still available via the title.
If you want to see some really great 404 designs visit:
- http://www.smashingmagazine.com/2009/01/29/404-error-pages-reloaded-2/
- http://www.smashingmagazine.com/2007/08/17/404-error-pages-reloaded/
- http://www.smashingmagazine.com/2007/07/25/wanted-your-404-error-pages/
- http://blogof.francescomugnai.com/2008/08/the-100-most-funny-and-unusual-404-error-pages/
The Auto-Mailer PHP and Why We Will Use Email Notification
This is the part of the tutorial in which some web guru’s might argue with. You can use your web server’s logs to check for error pages and much, much more. Why do I choose email notifications?
- I don’t want to log into my server every day and dig through all that extra information.
- I am available by email almost literally all day, the fastest way to reach me is email (or twitter). With this in mind, I want to know about 404 and 403 errors fairly quick so email is best.
- An increasing number of people are starting websites, while most of those people know almost nothing about web hosting let alone server logs. These people will only be running small sites; so email is ideal.
- Being notified right away allows me to quickly take action if a website of mine is being «harvested» (ThemeForest templates), if someone is attempting to access something restricted repeatedly or if I have a broken link somewhere.
So with all that said, let’s get on with the code shall we!
The Code
First, we will create a file named error-mailer.php which will be used to collect information about our visitor and send the email. Once you have created the file we will start by specifying our email and email settings.
1 |
<?php
|
2 |
|
3 |
# The email address to send to
|
4 |
$to_email = 'YOUR-EMAIL@DOMAIN.com'; |
5 |
|
6 |
# The subject of the email, currently set as 404 Not Found Error or 403 Forbidden Error
|
7 |
$email_subject = $error_code.' Error'; |
8 |
|
9 |
# The email address you want the error to appear from
|
10 |
$from_email = 'FROM-EMAIL@DOMAIN.COM'; |
11 |
|
12 |
# Who or where you want the error to appear from
|
13 |
$from_name = 'YourDomainName.com'; |
Then we will collect information about our visitor such as IP address, requested URI, User Agent, etc. The following code will collect that information.
1 |
# Gather visitor information
|
2 |
$ip = getenv ("REMOTE_ADDR"); // IP Address |
3 |
$server_name = getenv ("SERVER_NAME"); // Server Name |
4 |
$request_uri = getenv ("REQUEST_URI"); // Requested URI |
5 |
$http_ref = getenv ("HTTP_REFERER"); // HTTP Referer |
6 |
$http_agent = getenv ("HTTP_USER_AGENT"); // User Agent |
7 |
$error_date = date("D M j Y g:i:s a T"); // Error Date |
Now we will write the script to email the information to us with the details specified earlier.
1 |
# Send the email notification
|
2 |
require_once('phpMailer/class.phpmailer.php'); |
3 |
$mail = new PHPMailer(); |
4 |
|
5 |
$mail->From = $from_email; |
6 |
$mail->FromName = $from_name; |
7 |
$mail->Subject = $email_subject; |
8 |
$mail->AddAddress($to_email); |
9 |
$mail->Body = |
10 |
"There was a ".$error_code." error on the ".$server_name." domain". |
11 |
"nnDetailsn----------------------------------------------------------------------". |
12 |
"nWhen: ".$error_date. |
13 |
"n(Who) IP Address: ".$ip. |
14 |
"n(What) Tried to Access: http://".$server_name.$request_uri. |
15 |
"n(From where) HTTP Referer: ".$http_ref. |
16 |
"nnUser Agent: ".$http_agent; |
17 |
|
18 |
$mail->Send(); |
19 |
|
20 |
?>
|
We are using the phpMailer class to do this as demonstrated by Jeffrey via the ThemeForest blog to create a nice AJAX contact form. This version of the phpMailer class is for PHP 5/6 so if your server is running PHP 4 you will need to use the corresponding version by downloading it here.
404.php and 403.php Error Pages
The last thing we need to do is customize the error pages we designed earlier by sending the proper headers and set the $error_code variable by inserting the following code at the beginning of each page respectively (separated by ——-).
1 |
<?php
|
2 |
|
3 |
header("HTTP/1.0 404 Not Found"); |
4 |
$error_code = '404 Not Found'; // Specify the error code |
5 |
require_once('error-mailer.php'); // Include the error mailer script |
6 |
|
7 |
?>
|
8 |
------- |
9 |
<?php
|
10 |
|
11 |
header("HTTP/1.0 403 Forbidden"); |
12 |
$error_code = '403 Forbidden'; // Specify the error code |
13 |
require_once('error-mailer.php'); // Include the error mailer script |
14 |
|
15 |
?>
|
What we are doing here first is setting the correct HTTP header to return 404 Not Found and 403 Forbidden, respectively. When search engines accidentally land on this page we want to make sure they know what kind of page it is, instead of thinking that it’s a normal web page named 404.php or 403.php.
Then we specify the error code to be used in the mailer script and include the mailer script so it can do its work. This way if we make a change to the mailer script, we only need to edit one file instead of two or more (if you setup additional custom error pages).
Conclusion
There you have it! Your own custom error pages that are search engine friendly, and let you know via email when you’ve had a visitor as well as all the information you will need to fix any problems. A few last things to consider:
- Internet Explorer requires error pages that are at least 512 byes in size (if you use the example files you’ll be fine)
- High traffic websites have the potential to generate A LOT of emails so make sure you setup some sort of email filter for these error notifications so they don’t flood your inbox. I use Gmail so I just have a label and filter setup for these emails.
Did you find this post useful?
![]()
I’m a freelance designer and web developer, an author and reviewer at ThemeForest.net, a writer for the ThemeForest blog and occasionally net.tutsplus.com. When I actually manage to get away from the computer, I’m hiking, watching movies or spending time with my girlfriend in sunny Las Vegas. – View my web.appstorm.net posts here.
За последние 24 часа нас посетили 8783 программиста и 829 роботов. Сейчас ищут 368 программистов …
Страница 1 из 2
-

anempadest
Активный пользователь- С нами с:
- 17 янв 2012
- Сообщения:
- 42
- Симпатии:
- 0
Думаю, что тема о том как программно вызвать ошибку 404 поднималась уже давно. Но ответа на свой вопрос ни на этот форуме, ни в поисковых системах я не нашёл.
Нужно вызвать ошибку 404.
Вот мой .htaccsess.
-
ErrorDocument 404 /error/404.php
-
RewriteCond %{REQUEST_FILENAME} !-f
-
RewriteCond %{REQUEST_FILENAME} !-d
А это мой INDEX.PHP, который собирает сайт.
-
$url = $_SERVER[‘REQUEST_URI’];
-
$path = empty($url) ? ‘show’ : $url;
-
$path = ‘include/’ . $path . ‘.php’;
-
header($_SERVER[‘SERVER_PROTOCOL’] . ‘ 404 Not Found’, TRUE);
-
header(«Status: 404 Not Found»);
-
//include(‘error/404.php’);
Вот именно с таким кодом на экране появляется просто пустая страница. Если закомментить exit() и раскомментить include(‘error/404.php’), то на экране появляется моя настроенная страничка с извещением об ошибке 404, но сервер извещения об ошибке 404 не получает.
Как побороть?
-

Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
Покажи поисковые запросы. Тема отлично гуглится и яндексится.
-

anempadest
Активный пользователь- С нами с:
- 17 янв 2012
- Сообщения:
- 42
- Симпатии:
- 0
Да, топиков на эту тему создано не мало. Но ответа нет. Или, скажем, так, у меня не получается. Прошу помочь.
А какие поисковые запросы показать?
-

Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
Поисковые запросы по которым ты не находишь нужного материала. Ну теперь еще и ссылки по которым не написано ответа.
-

anempadest
Активный пользователь- С нами с:
- 17 янв 2012
- Сообщения:
- 42
- Симпатии:
- 0
Цели у меня две:
1) Получать сообщения об отсутствующих страницах.
2) Показать поисковому боту, что страницы нет.Первую задачу я решил.
-
$title = «Страница не найдена»;
-
$description = «Страница не найдена»;
-
$keywords = «страница не найдена»;
-
$body = «<html><head><title>Ошибка 404</title>»;
-
$body .= «<style>table {border-collapse: collapse;}table td {border: 1px silver solid;padding: 5px;vertical-align:top;}</style>»;
-
$body .= «</head><body>»;
-
$body .= «<h1>Ошибка 404</h1><table>»;
-
$a[‘REQUEST_URI’] = $_SERVER[‘REQUEST_URI’];
-
$a[‘QUERY_STRING’] = $_SERVER[‘QUERY_STRING’];
-
$a[‘HTTP_REFERER’] = $_SERVER[‘HTTP_REFERER’];
-
$a[‘HTTP_USER_AGENT’] = $_SERVER[‘HTTP_USER_AGENT’];
-
$a[‘REQUEST_TIME’] = date(‘Y-m-d H:i:s’, $_SERVER[‘REQUEST_TIME’]);
-
$a[‘REMOTE_ADDR’] = $_SERVER[‘REMOTE_ADDR’];
-
foreach ($a as $key => $value) {
-
$body .= «<tr><td>$key</td><td>$value</td></tr>»;
-
$body .= «</table></body></html>»;
-
$headers = «Content-type: text/html; charset=utf-8»;
-
$answer = mail($to, $subject, $body, $headers);
-
<h1>Страница не найдена</h1>
-
<p>Запрашиваемая страница ‘<? echo $_SERVER[‘REQUEST_URI’]; ?>‘ не найдена!</p>
Но меня больше беспокоит, как показать поисковому боту, что страница больше не существует.
Нет, можно, конечно, в HTACCESS явно прописать, что данная страница отсутствует. Но я хочу реализовать такой функционал через ErrorDicument и ошибку 404.
— Добавлено —У меня не работает:
http://aermolenko.ru/2012/02/vy-zov-oshibki-404-sredstvami-php/
http://searchengines.guru/showthread.php?t=798697
http://www.cyberforum.ru/php/thread799441.htmlА здесь решения так и не нашли:
http://www.programmersforum.ru/showthread.php?t=105783&page=2Больше не хочу копировать сюда всю выдачу Яндекса
https://yandex.ua/search/?text=вызвать ошибку 404&from=os&clid=1836588&lr=143 -

Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
Ну. На первой странице выдачи есть тот самый заголовок, который нужно отправить. И первая же ссылка рассказывает об личном опыте — попытку затолкать заголовок после того как началась отдача тела.
Кстати на почту отправлять — не самая хорошая идея. -

anempadest
Активный пользователь- С нами с:
- 17 янв 2012
- Сообщения:
- 42
- Симпатии:
- 0
Свой INDEX.PHP я выложил. По-вашему, я заталкиваю заголовок после начала выведения?В чём ошибка и какие есть варианты лучше?
-

Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
Ошибка в идее. Есть ботнеты, которые занимаются перебором популярных дырявых адресов. На каждый хит от бота ты будешь получать письмо. У меня не так давно на одном сайте было аж 16 тысяч хитов в несуществующие страницы за одну неделю. Это бы создало почтовый трафик объемом чуть более чем 2000 писем в сутки. На изучение такого небольшого объема корреспонденции ушло бы какое-то время. И это только по урлам одного сайта. А другую почту когда читать? Это раз.
Два: а что тебе эти письма дадут-то? У тебя есть есть журнал сервера, в котором пишется урл и статус ответа. Даже когда ты статус устанавливаешь в пхп — вебсервер все равно его видит и может успешно положить в журнал. Анализируй журналы раз в [период], если уж очень нужно.
Ну и третье. Если ты удаляешь существующий элемент, то намного лучше организовать некоторое хранилище, в которое веб-сервер сходит без участия пхп-машины. Если там что-то найдет — ответит скорбью по убитому ресурсу — 404 или 410. А если не найдет — запустит пхп-машину и та уже другими алгоритмами будет разрешать запрос.
— Добавлено —
Сделай запрос к несуществующей странице и загляни в журнал веб-сервера. Если там на этот хит стоит статус 404 то всё ты сделал правильно. -

anempadest
Активный пользователь- С нами с:
- 17 янв 2012
- Сообщения:
- 42
- Симпатии:
- 0
А я о том и говорю! Сервер не видит ошибку! Поэтому в журнале пусто.
-

Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
Может убрать ErrorDocument ?
-

anempadest
Активный пользователь- С нами с:
- 17 янв 2012
- Сообщения:
- 42
- Симпатии:
- 0
Попробовал — не помогло. В журнале ошибок ничего нет.
-

Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
Давай полную конфигурацию хоста. Будем пробовать у себя сэмулировать.
-

anempadest
Активный пользователь- С нами с:
- 17 янв 2012
- Сообщения:
- 42
- Симпатии:
- 0
-

Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
Это вся конфигурация веб-сервера, которая может влиять на разрешение запроса. Весь каталог /etc/apache2, какие-то тонкие примеси, если такие есть. И естественно конфиг самого виртуального хоста.
-

anempadest
Активный пользователь- С нами с:
- 17 янв 2012
- Сообщения:
- 42
- Симпатии:
- 0
При всём моём уважении, ваш метод решения моей проблемы напоминает мне случай из анекдота, когда мужик пришёл в магазин за туалетной бумагой, а продавец потребовал его принести в магазин унитаз, чтобы туалетную бумагу правильно подобрать.
Я думаю, вам достаточно будет знать, что если из .HTACCESS убрать это:
-
RewriteCond %{REQUEST_FILENAME} !-f
-
RewriteCond %{REQUEST_FILENAME} !-d
то ошибка 404 вызывается и запись в журнале ошибок на сервере создаётся.
Свои htaccess и index.php я вам дал. Воссоздать мой случай вы сможете. Если вы повторите мою конфигурацию и скажете, что у вас ошибка 404 вызывается, тогда я изменю своё мнение.
-

Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
Да, но нет. Ты пришел сюда с аксесом, в который роутишь все запросы в индекс-пхп. И внутри этого индекса ты разруливаешь есть ресурс или нет ресурс. Код у тебя вполне рабочий. Почему не работает — мне отсюда не видно. И я хотел на своем хосте поднять аналог твоего и поближе рассмотреть логику конфигурации. Ты же просто тупо убрал правила рерайтера, которые сваливают все отсутствующие ресурсы на индекс-пхп. И естественно у веб-сервера нет кандидатов и на разрешение запроса и он выкидывает статус 404. «Решение» кардинально меняет условие задачи. Ну если тебе так норм, то ок. Пример с унитазом тут вообще не в кассу.
-

anempadest
Активный пользователь- С нами с:
- 17 янв 2012
- Сообщения:
- 42
- Симпатии:
- 0
ОК. Ты можешь создать на своём хостинге сайт, в который поместишь мой index.php и .htaccsess?
Если у тебя заработает ошибка 404, то скажи.
Не нужно копаться в настройках сервера. Просто залей на свой пустой хостинг мои два файла и проверь.Цель — чтобы сервер выдал ошибку 404.
-

anempadest
Активный пользователь- С нами с:
- 17 янв 2012
- Сообщения:
- 42
- Симпатии:
- 0
Скажу больше.
Я в index.php оставил только это:-
header($_SERVER[‘SERVER_PROTOCOL’] . ‘ 404 Not Found’, TRUE);
-
header(«Status: 404 Not Found»);
Сервер ошибку 404 не выдал.
-

Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
-

anempadest
Активный пользователь- С нами с:
- 17 янв 2012
- Сообщения:
- 42
- Симпатии:
- 0
Думаю, вместо кейсов было бы красивее прописать это в виде ассоциативного массива…
Ну и что, что ты мне показал красивую страничку? Мне, как ТС, ты помог? Или только сам выпендрился?
Запись об ошибке 404 у тебя в журнале ошибок на сервере создалась?
Страничка с ошибкой у тебя вывелась сервером через ErrorDocument или через INCLUDE в INDEX.PHP?
Процедуру HEADER() ты запускал? Она сработала?Тут на форуме есть другие специалисты по запуску ошибки 404?
-

Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
Ты на логику работы с заголовками смотри, а не на стиль программирования. Тебе дали рабочий пример.Ну ты поменял на переправе условия задачи поэтому мне честно наплевать помог я тебе или не помог. Я сделал рабочий скрипт, который показывает страницу, сопровождая её выбранным статусом.Прилагаю фрагмент журнала веб-сервера (айпишники скрыл):
-
0.0.0.0 — — [26/Jul/2016:00:39:14 +0300] «GET /ru.php/59329/ HTTP/1.0» 404 5648 «-» «Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/50.0.2661.102 Chrome/50.0.2661.102 Safari/537.36» 508 5793
-
0.0.0.0 — — [26/Jul/2016:00:40:01 +0300] «GET /ru.php/59329/?status=400 HTTP/1.0» 400 5652 «http://lab.ganzal.com/ru.php/59329/» «Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/50.0.2661.102 Chrome/50.0.2661.102 Safari/537.36» 565 5799
-
0.0.0.0 — — [26/Jul/2016:00:40:04 +0300] «GET /ru.php/59329/?status=403 HTTP/1.0» 403 5648 «http://lab.ganzal.com/ru.php/59329/?status=400» «Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/50.0.2661.102 Chrome/50.0.2661.102 Safari/537.36» 576 5793
-
0.0.0.0 — — [26/Jul/2016:00:40:04 +0300] «GET /ru.php/59329/?status=403 HTTP/1.0» 403 5648 «http://lab.ganzal.com/ru.php/59329/?status=400» «Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/50.0.2661.102 Chrome/50.0.2661.102 Safari/537.36» 576 5793
-
0.0.0.0 — — [26/Jul/2016:00:40:11 +0300] «GET /ru.php/59329/?status=404 HTTP/1.0» 404 5648 «http://lab.ganzal.com/ru.php/59329/?status=403» «Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/50.0.2661.102 Chrome/50.0.2661.102 Safari/537.36» 576 5793
-
0.0.0.0 — — [26/Jul/2016:00:40:11 +0300] «GET /ru.php/59329/?status=404 HTTP/1.0» 404 5648 «http://lab.ganzal.com/ru.php/59329/?status=403» «Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/50.0.2661.102 Chrome/50.0.2661.102 Safari/537.36» 576 5793
-
0.0.0.0 — — [26/Jul/2016:00:54:59 +0300] «GET /ru.php/59329/ HTTP/1.0» 404 5648 «-» «Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36» 475 5793
-
0.0.0.0 — — [26/Jul/2016:00:57:25 +0300] «GET /ru.php/59329/ HTTP/1.0» 404 5648 «-» «Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0» 364 5793
-
0.0.0.0 — — [26/Jul/2016:00:57:41 +0300] «GET /ru.php/59329/?status=404 HTTP/1.0» 404 5648 «http://lab.ganzal.com/ru.php/59329/» «Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36» 532 5793
-
0.0.0.0 — — [26/Jul/2016:01:12:37 +0300] «GET /ru.php/59329/ HTTP/1.0» 404 5648 «-» «Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36» 458 5793
-
0.0.0.0 — — [26/Jul/2016:02:54:10 +0300] «GET /ru.php/59329/ HTTP/1.0» 404 5648 «-» «Mozilla/5.0 (Windows NT 5.1; rv:43.0) Gecko/20100101 Firefox/43.0» 398 5793
-
0.0.0.0 — — [26/Jul/2016:03:09:28 +0300] «GET /ru.php/59329/ HTTP/1.0» 404 5648 «-» «Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36» 475 5793
-
0.0.0.0 — — [26/Jul/2016:03:25:29 +0300] «GET /ru.php/59329/ HTTP/1.0» 404 5648 «-» «Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41» 482 5793
-
0.0.0.0 — — [26/Jul/2016:03:25:36 +0300] «GET /ru.php/59329/?status=503 HTTP/1.0» 503 5668 «http://lab.ganzal.com/ru.php/59329/» «Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41» 539 5823
-
0.0.0.0 — — [26/Jul/2016:03:25:37 +0300] «GET /ru.php/59329/?status=502 HTTP/1.0» 502 5652 «http://lab.ganzal.com/ru.php/59329/?status=503» «Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41» 550 5799
-
0.0.0.0 — — [26/Jul/2016:03:25:37 +0300] «GET /ru.php/59329/?status=500 HTTP/1.0» 500 5672 «http://lab.ganzal.com/ru.php/59329/?status=502» «Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41» 550 5829
-
0.0.0.0 — — [26/Jul/2016:03:25:38 +0300] «GET /ru.php/59329/?status=410 HTTP/1.0» 410 5638 «http://lab.ganzal.com/ru.php/59329/?status=500» «Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41» 550 5778
-
0.0.0.0 — — [26/Jul/2016:03:25:39 +0300] «GET /ru.php/59329/?status=404 HTTP/1.0» 404 5648 «http://lab.ganzal.com/ru.php/59329/?status=410» «Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41» 550 5793
-
0.0.0.0 — — [26/Jul/2016:03:25:40 +0300] «GET /ru.php/59329/?status=403 HTTP/1.0» 403 5648 «http://lab.ganzal.com/ru.php/59329/?status=404» «Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41» 550 5793
-
0.0.0.0 — — [26/Jul/2016:03:25:40 +0300] «GET /ru.php/59329/?status=404 HTTP/1.0» 404 5648 «http://lab.ganzal.com/ru.php/59329/?status=403» «Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41» 550 5793
-
0.0.0.0 — — [26/Jul/2016:03:25:41 +0300] «GET /ru.php/59329/?status=400 HTTP/1.0» 400 5652 «http://lab.ganzal.com/ru.php/59329/?status=404» «Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41» 550 5799
-
0.0.0.0 — — [26/Jul/2016:03:27:24 +0300] «GET /ru.php/59329/ HTTP/1.0» 404 5648 «-» «Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36» 655 5793
-
0.0.0.0 — — [26/Jul/2016:03:31:13 +0300] «GET /ru.php/59329/?status=404 HTTP/1.0» 404 5648 «http://lab.ganzal.com/ru.php/59329/?status=400» «Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41» 550 5793
-
0.0.0.0 — — [26/Jul/2016:03:31:13 +0300] «GET /ru.php/59329/?status=403 HTTP/1.0» 403 5648 «http://lab.ganzal.com/ru.php/59329/?status=404» «Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41» 550 5793
-
0.0.0.0 — — [26/Jul/2016:03:31:14 +0300] «GET /ru.php/59329/?status=400 HTTP/1.0» 400 5652 «http://lab.ganzal.com/ru.php/59329/?status=403» «Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41» 550 5799
-
0.0.0.0 — — [26/Jul/2016:09:46:40 +0300] «GET /ru.php/59329/ HTTP/1.0» 404 5648 «-» «Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36» 475 5793
Если ты внимательно прочитаешь код, то увидишь конструкцию, которая подсвечивает синтаксис самого файла. То есть весь код, который ты видишь на страничке — и есть код, который обработал запрос. Рекурсия.Почитай выше про самоподсвечивание синтаксиса и изучи внимательно исходный код. Там есть функция header()? Нашел? Ответил себе на вопрос?Рад что не помог тебе. Ну хоть развлекся. Про унитазы послушал от опытного человека.
-

anempadest
Активный пользователь- С нами с:
- 17 янв 2012
- Сообщения:
- 42
- Симпатии:
- 0
Рад, что помог тебе выпендриться. Но мне ты не помог. Знаю, что модераторов критиковать нельзя, но я сомневаюсь, что ты правильно понимаешь своё предназначение на форуме. И кстати. Раздел называется «Для новичков».
Надеюсь, я свою проблему решу. А тебе — минус в карму. -

Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
Ты пришел сюда с вопросом — я начал тебе помогать. Как мы выяснили, решение легко гуглится. Копипаст и всё работает.
Ты поменял условия задачи — я продолжил тебе помогать. Как мы выяснили, тебе не очень-то нужен был рерайтер, а без него — веб-сервер работает сам как нужно.
Я попросил конфу сервера — ты мне рассказал про унитазы. Имея немногим больший опыт работы с веб-серверами, я вполне мог найти причину, по которой не работает решение из пункта один.
Ты предложил челендж — я его принял и написал сценарий, который принимает гет-параметром код статуса и показывает тебе страничку с этим статусом. Ты можешь открыть инструменты разработчика и покликав по ссылкам убедиться, что статус ровно такой, какой нужен. Но ты вместо этого зацепился за свич вместо ассоциативного массива, не увидел вызова функции хидер, и не понял как этот сценарий работает. Тем не менее, я показал, что вполне возможно отвечать ровно тем статусом, который ты хочешь. Там ведь меняется только значение одной переменной.
Потом ты усомнился с журналированием статуса веб-сервером — я предоставил тебе логи. Видно, что были люди, которые прокликали по разным статусами. И веб-сервер записал лог именно с тем статусом, который видно в урле. Ты же (подозреваю что в 9:46 было твое посещение) просто разок открыл страницу. Сомневаюсь, что у тебя в этот момент были открыты инструменты разработчика, и что ты смог заметить, что браузеру пришел ответ со статусом 404. Ты поспешил как можно быстрее начать рассказывать мне про синтаксис.Сомневаюсь, что твои претензии хоть сколько-нибудь обоснованы. Ну либо ты вечная обиженка, поэтому с тобой невозможно вести конструктивный диалог.
Удачи тебе с решением твоей проблемы.
-

anempadest
Активный пользователь- С нами с:
- 17 янв 2012
- Сообщения:
- 42
- Симпатии:
- 0
Послушай, Сергей.
Я не исключаю, что в PHP мои познания малы, технологию работы веб-серверов я вообще не знаю. Одним словом, я — новичок. Поэтому задаю вопрос и вообще веду себя так, как могу.Мой вопрос не меняется. Я не могу найти ответ уже больше недели. Процедура HEADER() на моём сервере ошибку 404 не выдаёт.
Конфигурацию сервера я дать тебе не могу: я просто не знаю, где и как её брать. По сложности исполнения твоей просьбы для меня это сравнимо с принесением в магазин унитаза, если я хочу купить всего-то туалетную бумагу. И главное — я не понимаю, зачем. Сейчас, кстати, задал вопрос в службу поддержки — ищут.
Про твой красивый файл с ошибками… В качестве достаточного ответа на свой вопрос я бы принял одну фразу «Вызывай HEADER не в INDEX.PHP, а в файле 404.PHP». То, что у тебя на сервере процедура HEADER выполнилась, я не сомневался. И для меня нет никакой пользы от того, что у тебя всё работает правильно, потому что у меня твой копи-паст не работает.
Моё замечание по ассоциированному массиву — это мой ответ на твою ненужную мне красоту в предоставленном файле генерации ошибок.
Моя проблема не решена.
Страница 1 из 2
Генерация ошибки 404 средствами PHP
Что такое страница 404
Страница 404 является страницей, которая должна показываться пользователю вместо страницы, на которую он ссылается, но которой уже нет (или, и не было). Вместе с этой страницей, WEB сервер должен передавать заголовок страницы 404.
Зачем нужна страница 404
Генерировать страницу 404 необходимо, во-первых для того чтобы сообщить пользователю об отсутствии запрашиваемой страницы, и во-вторых, отправляемый заголовок сообщит поисковым системам о том, что запрашиваемой страницы не существует, и они не будут индексировать подобные страницы.
Какая должна быть страница 404
Данная страница должна чётко и ясно указать пользователю, что запрашиваемая страница не найдена. Страница 404 должна быть выполнена в общем стиле сайта, чтобы посетитель сразу, визуально понимал, на каком сайте он находится. Эта страница должна быть не только в общем стиле сайта, но и содержать всю навигацию, для того чтобы посетитель мог самостоятельно выполнить поиск нужной информации. И как было сказано выше, в заголовке страницы WEB сервер должен передавать данные об этой странице (404).
Как отправить заголовок страницы 404 средствами PHP
Сделать это можно при помощи функции header:
header(«HTTP/1.0 404 Not Found»);
или можно вот так:
header($_SERVER[‘SERVER_PROTOCOL’].» 404 Not Found»);
Последний пример более универсален, так как определяет версию протокола автоматически, используя элемент суперглобального массива $_SERVER.
Не забываем оставлять комментарии и отзывы, нам важно ваше мнение!
А еcли статья Вам очень понравилась и Вы считаете, что она достойна внимания. Тогда просто поделитесь ею, в социальной сети: