创建动态404页面

时间:2018-08-13 19:30:11

标签: php

我有一个404页面,我正在使用php输出页面URL。我的页面以error.php的形式保存在服务器上,服务器应该能够对用户说“抱歉错误不存在。”

当前,我的代码仅显示大写的页面名称,不带扩展名。如果用户转到domain.com/error.php很好,但是如果用户输入了类似domain.com/abutus之类的内容,我需要服务器说Sorry Abtus does not exist.

这就是我正在使用的:

<?php
$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$page = basename($_SERVER['PHP_SELF']); // Get script filename without any path information
$url = str_replace( array( '.php', '.htm', '.html' ), '', $page ); // Remove extensions
$page = str_replace( array( '.php', '.htm', '.html' ), '', $url); // Remove extensions
$page = str_replace( array('-', '_'), ' ', $page); // Change underscores/hyphens to spaces
$page = ucwords( $page ); // uppercase first letter of every word
$url = ucwords( $url ); // uppercase first letter of every word

?>

<p class="404">Sorry, <?php echo ucfirst(substr($x=substr($_SERVER['PHP_SELF'],0,strrpos($_SERVER['PHP_SELF'],'.')),strrpos($x,'/')+1)) ; ?> does not exist.</p>

我只需要根据用户输入的URL进行此更新,然后显示该更新而不是文件名即可。这比为每个可能的错误创建和存储新页面要容易得多。我不想浪费服务器空间,所以理想的是更新一个动态页面。

我无法找到与此相关的任何信息,因此我们将不胜感激。

UPDATE

<?php
$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$page = basename($_SERVER['REQUEST_URI']); // Get script filename without any path information
$url = str_replace( array( '.php', '.htm', '.html' ), '', $page ); // Remove extensions
$page = str_replace( array( '.php', '.htm', '.html' ), '', $url); // Remove extensions
$page = str_replace( array('-', '_'), ' ', $page); // Change underscores/hyphens to spaces
$page = ucwords( $page ); // uppercase first letter of every word
$url = ucwords( $url ); // uppercase first letter of every word

?>

<p class="404">Sorry, <?php echo ucfirst(substr($x=substr($_SERVER['REQUEST_URI'],0,strrpos($_SERVER['REQUEST_URI'],'.')),strrpos($x,'/')+1)) ; ?> does not exist.</p>

我添加了新代码。如果用户访问mydomain.com/url,则不会回显,但会访问mydomain.com/url.php

UPDATE 2

<?php
$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$page = basename($_SERVER['REQUEST_URI']);
?>

<p>Sorry, <?php echo ucfirst(substr($x=substr($_SERVER['REQUEST_URI'],0,strrpos($_SERVER['REQUEST_URI'],'.')),strrpos($x,'/')+1)) ; ?> does not exist</p>

我只需要它能够提供所键入的URL,即使用户未提供扩展名也是如此。它可以与/page.php一起使用,但是如果用户键入/page,它将无法使用。

2 个答案:

答案 0 :(得分:1)

您可以使用.htaccess设置自定义错误页面

ErrorDocument 404 /404.php

然后在代码中,您可以引用$ _SERVER [“ REQUEST_URI”]以显示所请求的URL并告诉用户该URL不存在。

答案 1 :(得分:0)

您可以使用.htaccess设置自定义错误页面

ErrorDocument 404 /404.php

然后在代码中,您可以引用$ _SERVER [“ REQUEST_URI”]以显示请求的URL,并告诉用户仅此代码就不存在该URL:

<?php
$x=substr($x=substr($_SERVER['REQUEST_URI'],0,strrpos($_SERVER['REQUEST_URI'],'.')),strrpos($x,'/')+1);
if(!$x)
    $x=substr($_SERVER['REQUEST_URI'],strrpos($_SERVER['REQUEST_URI'],'/')+1);
?>
<p class="404">Sorry, <?php echo ucfirst($x) ?> does not exist.</p>