PHP代码不读取URL

时间:2014-07-03 22:28:06

标签: php

我有一个简单的while循环,用于使用PHP生成动态菜单。

虚拟代码示例工作正常:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>linkpuller.php</title>
</head>
<body>
    <?php
        $allMenus = array("alpha", "bravo", "charlie", "delta", "echo", "foxtrot");
        $i = 0;
        while ((strpos(basename($_SERVER['REQUEST_URI']), $allMenus[$i]) == false) ) {
            $i++;
        }
        $pathResult = $allMenus[$i];
    ?>

    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Asperiores deserunt cum blanditiis saepe, pariatur aliquam maiores eos obcaecati ratione sit provident quisquam, ipsa autem tempore quod animi, cupiditate numquam minus.</p>

    <?php
        echo "<h1>$pathResult $i</h1>";
    ?>
</body>
</html>

我通过调用linkpuller.php?v=fooalphabar来测试它并且它工作正常但是如果我将文件命名为alpha.php它会运行30秒并超时。我假设这是因为PHP处理的路径与参数不同,但有没有办法让它工作? &#34;回声&#34;显示它确实拉动了#alpha; alpha&#34;来自while循环。我还尝试了其他内容,例如$_SERVER["PHP_SELF"]$_SERVER["SCRIPT_NAME"]或将变量设置为$_SERVER['REQUEST_URI'],但没有骰子。

2 个答案:

答案 0 :(得分:0)

还提供更好的选择:

尝试:

,而不是让自己容易出现这种无限循环
$pathResult = null;
foreach($allMenus as $item) {
    if( strpos(basename($_SERVER['REQUEST_URI']), $item) !== false) {
        $pathResult = $item;
        break;
    }
}

答案 1 :(得分:0)

目前还不清楚代码的目标是什么,但下面的代码非常相似,并使用foreach代替while循环。如果当前页面与$allMenus中的内容匹配,则菜单名称将存储在$current中。

最后几行用于测试。

$allMenus = array("alpha", "bravo", "charlie", "delta", "echo", "foxtrot");
$current = false;

foreach($allMenus as $menu_name) {
  // Check if the $menu_name appears at the beginning of the REQUEST_URI.
  if ( strpos(basename($_SERVER['REQUEST_URI']), $menu_name) === 0 ) {
    $current = $menu_name;
    break; // Stop running the loop, we're done
  }
}

if ( $current ) echo  'The current page is: ' . $menu_name;
else echo 'No menu page was found';

// Test results:
// http://example.org/alpha.php      -- The current page is: alpha
// http://example.org/not-alpha.php  -- No menu page was found