0

PHP の警告に少し問題があります。

私は基本的に、次のようにリンクをクリックしてページのコンテンツを変更したいと考えています。

<?php $page = ((!empty($_GET['page'])) ? $_GET['page'] : 'home'); ?>
<h1>Pages:</h1>
<ul>
    <li><a href="index.php?page=news">News</a></li>
    <li><a href="index.php?page=faq">F.A.Q.</a></li>
    <li><a href="index.php?page=contact">Contact</a></li>
</ul>
<?php include("$page.html");?>

これは非常にうまく機能しますが、存在しないページを使用すると、たとえば localhost/dir/index.php?page=notapage次のエラーが発生します。

Warning: include(notapage.html): failed to open stream: No such file or directory in
C:\xampp\htdocs\dir\index.php on line 8

Warning: include(): Failed opening 'notapage.html' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\dir\index.php on line 8

この警告をカスタム メッセージに置き換えることはできますか? (「404が見つかりません」のように)

前もって感謝し、幸せなイースターを!

4

5 に答える 5

3

file_exists()を使用できますが、このアプローチはあまり安全ではないことに注意してください。より安全な方法は、許可されたページを持つ配列を使用することです。このようにして、ユーザー入力をより適切に制御できます。このようなもの:

$pages = array(
    'news' => 'News',
    'faq' => 'F.A.Q.',
    'contact' => 'Contact'
);

if (!empty($pages[$_GET['page']])) {
    include($_GET['page'].'html');
} else {
    include('error404.html');
}

その配列を使用してメニューを生成することもできます。

于 2013-03-29T18:02:46.117 に答える
1

できるよ

if (file_exists($page.html)) {
include("$page.html");
}
else
{
echo "404 Message";
}

出典: PHP マニュアル

于 2013-03-29T17:56:24.660 に答える
0

ファイルが存在するかどうかを確認し() 、カスタム 404 テンプレートを含めることができます。

<?php 
if (file_exists($page + '.html')) { 
    include ($page + '.html') 
} else { 
    include ('404.html'); 
}
?>
于 2013-03-29T17:55:53.740 に答える
0

include() を試みる前に、ファイルが存在するかどうかを確認するという考え方です。

if(!file_exists("$page.html"))
{
    display_error404();
    exit;
}

include("$page.html");
于 2013-03-29T17:57:37.343 に答える
0

はい、可能ですが、ページ パラメータを記述して裏で index.php にリダイレクトするクリーンな URL (/news、/faq、/contact など) も使用しない限り、404 を送信することをお勧めします。これは、index.php が実際に存在するためです。パラメータが間違っているだけです。したがって、404 は適切ではありません。これは言うまでもありませんが、既に出力をブラウザーに送信しているため、この場所に 404 ヘッダーを実際に設定することはできません。

あなたの場合、file_exists が存在し、次のように読み取り可能かどうかについて条件を設定するだけです。

$include_file = $page . '.html';
if (file_exists($include_file) && is_readable($include_file)) {
   include($include_file);
} else {
   // show error message
}
于 2013-03-29T17:59:07.020 に答える