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.8k7 gold badges36 silver badges38 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.5k25 gold badges105 silver badges135 bronze badges
answered Sep 4, 2009 at 19:50
JW.JW.
50.5k36 gold badges114 silver badges142 bronze badges
3
Try this:
<?php
header("HTTP/1.0 404 Not Found");
?>
answered Sep 4, 2009 at 19:36
Ates GoralAtes Goral
137k26 gold badges137 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,6302 gold badges43 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
97.1k20 gold badges76 silver badges81 bronze badges
Standard Apache 404 error looks like this:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
</body></html>
Thus, you can use the following PHP code to generate 404 page that looks exactly as standard apache 404 page:
function httpNotFound()
{
http_response_code(404);
header('Content-type: text/html');
// Generate standard apache 404 error page
echo <<<HTML
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
</body></html>
HTML;
exit;
}
answered Mar 20 at 16:14
Dima L.Dima L.
3,39332 silver badges30 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,9791 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,6563 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
- Главная»
- Уроки»
-
PHP»
- Создаем единую страницу для обработки ошибок
- Метки урока:
- php
- кодинг
- разное
Создаем единую страницу для обработки ошибок
В данном уроке представлено очень простое решение для обработки различных ошибок HTTP, таких как 404, 500 и так далее, в одном файле PHP. Нужно создать массив кодов ошибок и установить правила перенаправления на наш PHP файл. То есть, можно использовать одну страницу для обработки нескольких ошибок.
Перенаправление
В файле .htaccess
вашего сервера нужно установить правила для обработки ошибок. В нашем случае мы будем перенаправлять все ошибки в наш файл errors.php
, который будет формировать страницу HTML для посетителя. Добавляем в файл .htaccess
следующие правила:
ErrorDocument 400 /errors.php ErrorDocument 403 /errors.php ErrorDocument 404 /errors.php ErrorDocument 405 /errors.php ErrorDocument 408 /errors.php ErrorDocument 500 /errors.php ErrorDocument 502 /errors.php ErrorDocument 504 /errors.php
PHP
Теперь создаем файл errors.php,
который должен располагаться в корневом каталоге вашего сервера (так как такое его местоположение установлено в заданных нами выше правилах в файле .htaccess
).
$status = $_SERVER['REDIRECT_STATUS']; $codes = array( 400 => array('400 Плохой запрос', 'Запрос не может быть обработан из-за синтаксической ошибки.'), 403 => array('403 Запрещено', 'Сервер отказывает в выполнении вашего запроса.'), 404 => array('404 Не найдено', 'Запрашиваемая страница не найдена на сервере.'), 405 => array('405 Метод не допускается', 'Указанный в запросе метод не допускается для заданного ресурса.'), 408 => array('408 Время ожидания истекло', 'Ваш браузер не отправил информацию на сервер за отведенное время.'), 500 => array('500 Внутренняя ошибка сервера', 'Запрос не может быть обработан из-за внутренней ошибки сервера.'), 502 => array('502 Плохой шлюз', 'Сервер получил неправильный ответ при попытке передачи запроса.'), 504 => array('504 Истекло время ожидания шлюза', 'Вышестоящий сервер не ответил за установленное время.'), ); $title = $codes[$status][0]; $message = $codes[$status][1]; if ($title == false || strlen($status) != 3) { $message = 'Код ошибки HTTP не правильный.'; } echo '<h1>Внимание! Обнаружена ошибка '.$title.'!</h1> <p>'.$message.'</p>';
Готово!
Конечно, код PHP может формировать и более информативную страницу для пользователя. При формировании разметки стоит учесть рекомендации для страниц, выводящих информацию об ошибках.
5 последних уроков рубрики «PHP»
-
Фильтрация данных с помощью zend-filter
Когда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных.
-
Контекстное экранирование с помощью zend-escaper
Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.
-
Подключение Zend модулей к Expressive
Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.
-
Совет: отправка информации в Google Analytics через API
Предположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке.
-
Подборка PHP песочниц
Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.
(PHP 4, PHP 5, PHP 7, PHP
error_reporting — Sets which PHP errors are reported
Description
error_reporting(?int $error_level
= null
): int
Parameters
-
error_level
-
The new error_reporting
level. It takes on either a bitmask, or named constants. Using named
constants is strongly encouraged to ensure compatibility for future
versions. As error levels are added, the range of integers increases,
so older integer-based error levels will not always behave as expected.The available error level constants and the actual
meanings of these error levels are described in the
predefined constants.
Return Values
Returns the old error_reporting
level or the current level if no error_level
parameter is
given.
Changelog
Version | Description |
---|---|
8.0.0 |
error_level is nullable now.
|
Examples
Example #1 error_reporting() examples
<?php// Turn off all error reporting
error_reporting(0);// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);// Report all PHP errors
error_reporting(E_ALL);// Report all PHP errors
error_reporting(-1);// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);?>
Notes
Tip
Passing in the value -1
will show every possible error,
even when new levels and constants are added in future PHP versions. The
behavior is equivalent to passing E_ALL
constant.
See Also
- The display_errors directive
- The html_errors directive
- The xmlrpc_errors directive
- ini_set() — Sets the value of a configuration option
info at hephoz dot de ¶
14 years ago
If you just see a blank page instead of an error reporting and you have no server access so you can't edit php configuration files like php.ini try this:
- create a new file in which you include the faulty script:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("file_with_errors.php");
?>
- execute this file instead of the faulty script file
now errors of your faulty script should be reported.
this works fine with me. hope it solves your problem as well!
jcastromail at yahoo dot es ¶
2 years ago
Under PHP 8.0, error_reporting() does not return 0 when then the code uses a @ character.
For example
<?php
$a
=$array[20]; // error_reporting() returns 0 in php <8 and 4437 in PHP>=8?>
dave at davidhbrown dot us ¶
17 years ago
The example of E_ALL ^ E_NOTICE is a 'bit' confusing for those of us not wholly conversant with bitwise operators.
If you wish to remove notices from the current level, whatever that unknown level might be, use & ~ instead:
<?php
//....
$errorlevel=error_reporting();
error_reporting($errorlevel & ~E_NOTICE);
//...code that generates notices
error_reporting($errorlevel);
//...
?>
^ is the xor (bit flipping) operator and would actually turn notices *on* if they were previously off (in the error level on its left). It works in the example because E_ALL is guaranteed to have the bit for E_NOTICE set, so when ^ flips that bit, it is in fact turned off. & ~ (and not) will always turn off the bits specified by the right-hand parameter, whether or not they were on or off.
Fernando Piancastelli ¶
18 years ago
The error_reporting() function won't be effective if your display_errors directive in php.ini is set to "Off", regardless of level reporting you set. I had to set
display_errors = On
error_reporting = ~E_ALL
to keep no error reporting as default, but be able to change error reporting level in my scripts.
I'm using PHP 4.3.9 and Apache 2.0.
ecervetti at orupaca dot fr ¶
14 years ago
It could save two minutes to someone:
E_ALL & ~E_NOTICE integer value is 6135
huhiko334 at yandex dot ru ¶
4 years ago
If you get a weird mysql warnings like "Warning: mysql_query() : Your query requires a full tablescan...", don't look for error_reporting settings - it's set in php.ini.
You can turn it off with
ini_set("mysql.trace_mode","Off");
in your script
http://tinymy.link/mctct
kevinson112 at yahoo dot com ¶
5 years ago
I had the problem that if there was an error, php would just give me a blank page. Any error at all forced a blank page instead of any output whatsoever, even though I made sure that I had error_reporting set to E_ALL, display_errors turned on, etc etc. But simply running the file in a different directory allowed it to show errors!
Turns out that the error_log file in the one directory was full (2.0 Gb). I erased the file and now errors are displayed normally. It might also help to turn error logging off.
https://techysupport.co/norton-tech-support/
luisdev ¶
5 years ago
This article refers to these two reporting levels:
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
// Report all PHP errors
error_reporting(-1);
What is the difference between those two levels?
Please update this article with a clear explanation of the difference and the possible use cases.
qeremy ! gmail ¶
8 years ago
If you want to see all errors in your local environment, you can set your project URL like "foo.com.local" locally and put that in bootstrap file.
<?php
if (substr($_SERVER['SERVER_NAME'], -6) == '.local') {
ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);
// or error_reporting(E_ALL);
}
?>
adam at adamhahn dot com ¶
6 years ago
To expand upon the note by chris at ocproducts dot com. If you prepend @ to error_reporting(), the function will always return 0.
<?php
error_reporting(E_ALL);
var_dump(
error_reporting(), // value of E_ALL,
@error_reporting() // value is 0
);
?>
keithm at aoeex dot com ¶
12 years ago
Some E_STRICT errors seem to be thrown during the page's compilation process. This means they cannot be disabled by dynamically altering the error level at run time within that page.
The work-around for this was to rename the file and replace the original with a error_reporting() call and then a require() call.
Ex, rename index.php to index.inc.php, then re-create index.php as:
<?php
error_reporting(E_ALL & ~(E_STRICT|E_NOTICE));
require('index.inc.php');
?>
That allows you to alter the error reporting prior to the file being compiled.
I discovered this recently when I was given code from another development firm that triggered several E_STRICT errors and I wanted to disable E_STRICT on a per-page basis.
chris at ocproducts dot com ¶
6 years ago
The error_reporting() function will return 0 if error suppression is currently active somewhere in the call tree (via the @ operator).
Rash ¶
8 years ago
If you are using the PHP development server, run from the command line via `php -S servername:port`, every single error/notice/warning will be reported in the command line itself, with file name, and line number, and stack trace.
So if you want to keep a log of all the errors even after page reloads (for help in debugging, maybe), running the PHP development server can be useful.
vdephily at bluemetrix dot com ¶
18 years ago
Note that E_NOTICE will warn you about uninitialized variables, but assigning a key/value pair counts as initialization, and will not trigger any error :
<?php
error_reporting(E_ALL);$foo = $bar; //notice : $bar uninitialized$bar['foo'] = 'hello'; // no notice, although $bar itself has never been initialized (with "$bar = array()" for example)$bar = array('foobar' => 'barfoo');
$foo = $bar['foobar'] // ok$foo = $bar['nope'] // notice : no such index
?>
&IT ¶
3 years ago
error_reporting(E_ALL);
if (!ini_get('display_errors')) {
ini_set('display_errors', '1');
}
lhenry at lhenry dot com ¶
3 years ago
In php7, what was generally a notice or a deprecated is now a warning : the same level of a mysql error … unacceptable for me.
I do have dozen of old projects and I surely d'ont want to define every variable which I eventually wrote 20y ago.
So two option: let php7 degrade my expensive SSDs writing Gb/hours or implement smthing like server level monitoring ( with auto_[pre-ap]pend_file in php.ini) and turn off E_WARNING
Custom overriding the level of php errors should be super handy and flexible …
rojaro at gmail dot com ¶
12 years ago
To enable error reporting for *ALL* error messages including every error level (including E_STRICT, E_NOTICE etc.), simply use:
<?php error_reporting(-1); ?>
j dot schriver at vindiou dot com ¶
22 years ago
error_reporting() has no effect if you have defined your own error handler with set_error_handler()
[Editor's Note: This is not quite accurate.
E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR and E_COMPILE_WARNING error levels will be handled as per the error_reporting settings.
All other levels of errors will be passed to the custom error handler defined by set_error_handler().
Zeev Suraski suggests that a simple way to use the defined levels of error reporting with your custom error handlers is to add the following line to the top of your error handling function:
if (!($type & error_reporting())) return;
-zak@php.net]
kc8yds at gmail dot com ¶
14 years ago
this is to show all errors for code that may be run on different versions
for php 5 it shows E_ALL^E_STRICT and for other versions just E_ALL
if anyone sees any problems with it please correct this post
<?php
ini_set('error_reporting', version_compare(PHP_VERSION,5,'>=') && version_compare(PHP_VERSION,6,'<') ?E_ALL^E_STRICT:E_ALL);
?>
fredrik at demomusic dot nu ¶
17 years ago
Remember that the error_reporting value is an integer, not a string ie "E_ALL & ~E_NOTICE".
This is very useful to remember when setting error_reporting levels in httpd.conf:
Use the table above or:
<?php
ini_set("error_reporting", E_YOUR_ERROR_LEVEL);
echo ini_get("error_reporting");
?>
To get the appropriate integer for your error-level. Then use:
php_admin_value error_reporting YOUR_INT
in httpd.conf
I want to share this rather straightforward tip as it is rather annoying for new php users trying to understand why things are not working when the error-level is set to (int) "E_ALL" = 0...
Maybe the PHP-developers should make ie error_reporting("E_ALL"); output a E_NOTICE informative message about the mistake?
Alex ¶
16 years ago
error_reporting() may give unexpected results if the @ error suppression directive is used.
<?php
@include 'config.php';
include 'foo.bar'; // non-existent file
?>
config.php
<?php
error_reporting(0);
?>
will throw an error level E_WARNING in relation to the non-existent file (depending of course on your configuration settings). If the suppressor is removed, this works as expected.
Alternatively using ini_set('display_errors', 0) in config.php will achieve the same result. This is contrary to the note above which says that the two instructions are equivalent.
teynon1 at gmail dot com ¶
11 years ago
It might be a good idea to include E_COMPILE_ERROR in error_reporting.
If you have a customer error handler that does not output warnings, you may get a white screen of death if a "require" fails.
Example:
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
function
myErrorHandler($errno, $errstr, $errfile, $errline) {
// Do something other than output message.
return true;
}$old_error_handler = set_error_handler("myErrorHandler");
require
"this file does not exist";
?>
To prevent this, simply include E_COMPILE_ERROR in the error_reporting.
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
?>
Daz Williams (The Northeast) ¶
14 years ago
Only display php errors to the developer...
<?php
if($_SERVER['REMOTE_ADDR']=="00.00.00.00")
{
ini_set('display_errors','On');
}
else
{
ini_set('display_errors','Off');
}
?>
Just replace 00.00.00.00 with your ip address.
DarkGool ¶
17 years ago
In phpinfo() error reporting level display like a bit (such as 4095)
Maybe it is a simply method to understand what a level set on your host
if you are not have access to php.ini file
<?php
$bit = ini_get('error_reporting');
while ($bit > 0) {
for($i = 0, $n = 0; $i <= $bit; $i = 1 * pow(2, $n), $n++) {
$end = $i;
}
$res[] = $end;
$bit = $bit - $end;
}
?>
In $res you will have all constants of error reporting
$res[]=int(16) // E_CORE_ERROR
$res[]=int(8) // E_NOTICE
...
misplacedme at gmail dot com ¶
13 years ago
I always code with E_ALL set.
After a couple of pages of
<?php
$username = (isset($_POST['username']) && !empty($_POST['username']))....
?>
I made this function to make things a little bit quicker. Unset values passed by reference won't trigger a notice.
<?php
function test_ref(&$var,$test_function='',$negate=false) {
$stat = true;
if(!isset($var)) $stat = false;
if (!empty($test_function) && function_exists($test_function)){
$stat = $test_function($var);
$stat = ($negate) ? $stat^1 : $stat;
}
elseif($test_function == 'empty') {
$stat = empty($var);
$stat = ($negate) ? $stat^1 : $stat;
}
elseif (!function_exists($test_function)) {
$stat = false;
trigger_error("$test_function() is not a valid function");
}
$stat = ($stat) ? true : false;
return $stat;
}
$a = '';
$b = '15';test_ref($a,'empty',true); //False
test_ref($a,'is_int'); //False
test_ref($a,'is_numeric'); //False
test_ref($b,'empty',true); //true
test_ref($b,'is_int'); //False
test_ref($b,'is_numeric'); //false
test_ref($unset,'is_numeric'); //false
test_ref($b,'is_number'); //returns false, with an error.
?>
forcemdt ¶
9 years ago
Php >5.4
Creating a Custom Error Handler
set_error_handler("customError",E_ALL);
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
PHP: пишем собственную страницу обработки ошибок Apache (404 и др.)
У нормального хостера проблема решается очень легко: достаточно написать свой файл .htaccess
и положить его в корневую папку сайта.
Синтаксис нужной нам директивы:
ErrorDocument код-ошибки документ
Примеры:
ErrorDocument 403 /error.html ErrorDocument 404 /bad_urls.php ErrorDocument 500 http://my.server.com/cgi-bin/error
Тремя показанными ошибками, как самыми частыми, и ограничимся. Добавив к файлу .htaccess
директивы, на всякий случай отключающие устаревшие «волшебные кавычки» и явно указывающие кодировку сайта (у нас русскоязычная windows), получим вот что:
AddDefaultCharset windows-1251 php_flag magic_quotes_gpc off php_flag magic_quotes_runtime off php_flag magic_quotes_sybase off ErrorDocument 403 /error.php?e=403 ErrorDocument 404 /error.php?e=404 ErrorDocument 500 /error.php?e=500
Проблемы с созданием файла под именем
.htaccess
?
Пользуйтесь не проводничком и блокнотиком, а нормальным файл-менеджером, например, Far
Пока не умеете с ним работать (там есть и отличные плагины FTP/SFTP для закачки файлов на сайты), нет смысла работать и с хостами
Имейте в виду, что если вы напишете в директиве ErrorDocument
полный адрес скрипта обработки ошибок вида
http://my.server.com/error.php?e=404
вместо /error.php?e=404
, то будет редирект 302 на указанный URL вместо корректной обработки ошибки 404. Ну и неправильный юзвериный адрес исчезнет из адресной строки браузера
Но! При указании относительного адреса обработчика error.php
ссылки, выданные на страницу обработчика как относительные (то есть, <a href="my.php">link<a>
или <a href="/my.php">link<a>
, будут восприниматься скриптом как адреса от неправильного URL. Правильно в этом случае выдавать <a href="http://my.server.com/my.php">link<a>
(где my.server.com
— имя вашего сервера), а эту самую my.server.com
получать из настроек сайта.
Саму обработку для удобства сделаем одним файлом error.php
— не писать же кучу отдельных документов? Наш обработчик будет параметром получать номер ошибки. Файл error.php
, как видно из директивы ErrorDocument
, нужно также скопировать в корневую папку сайта.
Вот пример кода такого обработчика ошибок сервера:
<?php require_once ("functions.php"); $id=get_int('e'); if (empty($e)) { redirect (); } title ("Ошибка $e"); include "header.php"; $emsgs = array ( 403 => 'Сервер не отвечает', 404 => 'Документ не найден', 500 => 'Внутренняя ошибка сервера' ); $emsg = 'Описание ошибки не найдено'; if (array_key_exists($e, $search_array)) $emsg = $emsgs[$e]; echo ' <p>Что-то пошло не так... Сервер вернул код ошибки '.$e.' ('.$emsg.') <p>Инфа для пользователя и ссылки, куда податься, обычный HTML '; if (isset ($_SERVER['REQUEST_URI'])) echo '<p>Вы пытались перейти на адрес : '.request_url().'</p>'; if (isset ($_SERVER['HTTP_REFERER'])) echo '<p>Вы пришли с адреса: '.$_SERVER['HTTP_REFERER'].'</p>'; include "footer.php"; ?>
Здесь
require_once ("functions.php");
подключает гипотетическую библиотеку функций сайта, нам, в общем-то, для примера достаточно трёх.
1. Функция redirect
просто отправляет юзера туда, откуда он пришёл (на случай, если сам error.php
вызван напрямую и без обязательного параметра):
function redirect () { if (isset ($_SERVER['HTTP_REFERER'])) { header('Location: '.$_SERVER['HTTP_REFERER']); } else { header('Location: index.php'); } }
2. Функция get_int
возвращает целое число, полученное из параметра URL-адреса $_GET
с именем $name
или пустую строку, если допустимое число не передано. Функция может выглядеть, например, так:
function get_int($name) { $var=''; if (isset($_GET[$name])) $var = 0 + intval(htmlspecialchars(trim($_GET[$name]))); return $var; }
3. Функция title
сохраняет переданную ей величину в статической переменной, скажем,
function title ($str) { static $title=''; if (!empty($str)) $title=$str; return $title; }
чтобы потом файл, выводящий разметку страницы, мог этой переменной воспользоваться для формирования заголовка окна браузера, допустим, так:
<title><?php echo title(''); ?></title>
(код может быть помещён в файл header.php
— стандартную «шапку» всех страниц сайта). Так что, директивы
include "header.php"; include "footer.php";
как раз подключают стандартные «шапку» и «подвал» сайта.
Наконец, два последних условия позволяют выяснить, куда юзер хотел попасть и откуда он пришёл,
при желании, любую из выдаваемых строк можно сделать ссылкой средствами HTML.
Ах, да, часто в качестве ссылки на текущий адрес лепят просто $_SERVER['REQUEST_URI']
, забывая, что это
имя скрипта, начиная от корневой директории виртуального хоста
но никак не полный путь.
Функция request_url
как раз и пытается грамотно получить на PHP текущий полный URL-адрес страницы, с учётом того, что соединение может быть не по 80 порту и не по http
, а по https
. Вот эта волшебная функция, считаем, что она там же, в functions.php
:
function request_url() { $result = ''; $port = 80; if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']=='on')) { $result .= 'https://'; $port = 443; } else $result .= 'http://'; $result .= $_SERVER['SERVER_NAME']; if ($_SERVER['SERVER_PORT'] != $port) $result .= ':'.$_SERVER['SERVER_PORT']; return $result.$_SERVER['REQUEST_URI']; }
Что у нас вышло можно увидеть, например, щёлкнув по этой несуществующей ссылке
на страницу моего блога.
19.02.2015, 14:50 [14344 просмотра]
К этой статье пока нет комментариев, Ваш будет первым
Introduction: Custom 404 Error Page in PHP
Every website gets the occasional, frustrating Error 404: Not Found. And if you have your own website, you may wish to customize these error pages. Thankfully, it’s not that hard to do. Your error pages may be of any extension you want. Usually, they are written in SHTML. But SHTML isn’t very dynamic in terms of what can be done with it. So I went over to PHP for my error pages. The coding wasn’t hard either. So let’s begin.
Step 1: Requirements
If you have a website, your hosing server should have PHP installed. If not, ask your server’s admin if they would be kind enough to install it. If you are just screwing around wasting time, you need some type of emulator. If you’re on Windows, use easyPHP for this. If you’re on Linux and can spare the resources, get: apache2 and php (for Ubuntu, sudo apt-get install apache2 php). If you’re on mac, I have no idea what you can use.
Once you meet these requirements, go to the next step.
Step 2: .htaccess
As stated on the cover page, your custom error page(s) can have any extension you want. But you can’t use it if your server isn’t told to use it. This is where .htaccess comes in. .htaccess is a file named, well, «.htaccess». This file can be used to configure your site to certain degrees. What we will do is go ahead and point the 404 error to 404.php (which, ironically, doesn’t exist yet). This will be a hidden file (every file that begins with a dot is a hidden file). So make sure you can view hidden files. In this file, write the following code and save it:
ErrorDocument 404 /404.php
And while you’re at it, if you feel like it:
ErrorDocument 400 /400.php
ErrorDocument 401 /401.php
ErrorDocument 403 /403.php
ErrorDocument 404 /404.php #Don't re-add this line
ErrorDocument 500 /500.php
Step 3: 404.php
And the actual error page. I’m going to ignore the whole «let’s follow standards» thing I usually do. The reason I chose PHP for the error page is because you can figure out the source of the error to an extent; you can see if the missing page was typed in the address bar, if it was a link on your site, or if it was a link on a different site. This is achieved by parsing a server variable. You can also parse a couple other server variables and see exactly what was put into the address bar. For this ible, we will only grab the requested page and the referrer, if any.
<?php echo $_SERVER['REQUEST_URI']; ?> does not exist, sorry.
The line above will tell the visitor that the page they want, along with the page’s path (preceded with a slash), does not exist. It’s helpful to tell the specific page because the hyperlink they followed, if they followed, may not reflect the page’s path. The next code will grab if there was a referrer and who it was.
<?php
if(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])){
$refuri = parse_url($_SERVER['HTTP_REFERER']); // use the parse_url() function to create an array containing information about the domain if($refuri['host'] == "your-domain.com"){
//the link was on your site
}
else{ //the link was on another site. $refuri['host'] will return what that site is
} } else{
//the visitor typed gibberish into the address bar
}
?>
On my site, I told the user one of three things to do as per the code. If the referrer was my site, email me and let me know. If the referrer was on a different site, email them and let them know. If they types randomly in the address bar, stop doing that.
<?php
if(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])){
$refuri = parse_url($_SERVER['HTTP_REFERER']); // use the parse_url() function to create an array containing information about the domain
if($refuri['host'] == "cutlery-in-the-toaster.com"){
echo "You should email fork@cutlery-in-the-toaster.com and tell me I have a dead link on this site.";
}
else{
echo "You should email someone over at " . $refuri['host'] . " and let them know they have a dead link to this site.";
}
}
else{
echo "If you got here from Angola, you took a wrong turn at Catumbela. And if you got here by typing randomly in the address bar, stop doing that. You're filling my error logs with unnecessary junk.";
}
?>
Step 4: Testing
First, go to your site like normal. It should show up normally. To test if your .htaccess is being read, insert random junk anywhere inside it and save it. Reloading the page should give a 500 error. If not, make sure your site is set up to use .htaccess files (I just had to edit my server’s config files to get it to work). If it still don’t work, try deleting all the blank spaces and reinserting them.
Else, undo the junk and re-save it. Now try to visit a non-existent page. You should see your 404 page. Add a few dead links on your site and try to follow them. You should end up with the same 404 page but with different content. Add a dead link to another website and the 404 page will have different content.
Step 5: Files
Here are the files used in this ible. Edit as desired/required.