0

问题:

优化 PHP 代码以在到达多个页面之一时打印代码。

PHP代码:

if (substr(strrchr($_SERVER['PHP_SELF'], '/'), 1) == "part-c.php" || substr(strrchr($_SERVER['PHP_SELF'], '/'), 1) == "part-g.php" || substr(strrchr($_SERVER['PHP_SELF'], '/'), 1) == "part-j.php" || substr(strrchr($_SERVER['PHP_SELF'], '/'), 1) == "part-n.php" || substr(strrchr($_SERVER['PHP_SELF'], '/'), 1) == "part-q.php")
{
    echo 'Hello';
}

建议:

我正在考虑将所有页面放在一个数组中并检查您所在的页面是否存在于该数组中是否是一个好主意。其他建议如何解决?

4

2 回答 2

2

是的,您是对的,您可以通过将所有页面放入数组并使用in_array检查来减少代码。

$checkString = substr(strrchr($_SERVER['PHP_SELF'], '/'), 1);
$pages = array("part-c.php","part-g.php","part-j.php","part-n.php","part-q.php");

if(in_array($checkString,$pages)){
   echo 'Hello';
}
于 2013-04-25T04:41:42.643 回答
0

You can also put your files in a txt file which is only read by the server setting it to CHMOD 0664, then list the files like so:

vPages.txt

part-c.php
part-g.php
part-j.php
part-n.php
part-q.php

and then run some code like Rikesh suggested:

$page = substr( strrchr( $_SERVER['PHP_SELF'], '/' ), 1 );
$vPages = file( './vPages.txt' );

if ( in_array( $page, $vPages ) ) {
    // Seems legit...

}

and you'll be able to easily edit a file to include more valid pages.

于 2013-04-25T05:22:39.927 回答