-4

我正在寻找一个 PHP 函数,它接受一个相对 URL 并返回是否是这个 URL。

<?PHP
function isCurrentPage($page)
{
    //Magic
}
?>

这将被传递值,例如"/", "/foo/bar", page.php, 甚至"foo/page.php?parameter=value"

我的第一次尝试涉及使用$page == $_SERVER["REQUEST_URI"],但那说"/foo/bar" != "/foo/bar/"。这不是什么大问题,但困难在于它说"/foo/bar" != "/foo/bar/index.php?parameter=value"。出于我的目的,我需要它说这些是等价的。

在给定的限制下,如何判断当前 URL 是否是传递给此函数的?我更喜欢一个简单、强大的解决方案,它可以保证在未来 5 年内有效,因为这是一个长期的、高使用率的项目。旧的、未弃用的函数和/或正则表达式更可取。

概括地说,该方法必须true在 url 上返回http://example.com/foo/bar

  • isCurrentPage("http://example.com/foo/bar")
  • isCurrentPage("http://example.com/foo/bar/")
  • isCurrentPage("http://example.com/foo/bar/index.php")
  • isCurrentPage("http://example.com/foo/bar/index.phps")
  • isCurrentPage("http://example.com/foo/bar/index.phtml")
  • isCurrentPage("/foo/bar")
  • isCurrentPage("/foo/bar/")
  • isCurrentPage("/foo/bar/index.php")
  • isCurrentPage("/foo/bar?parameter=value")
  • isCurrentPage("/foo/bar/?parameter=value")
  • isCurrentPage("/foo/bar/index.php?parameter=value")
  • isCurrentPage("/foo/bar/index.php#id")
  • isCurrentPage("#id")
  • isCurrentPage("index.php")
  • isCurrentPage("index.php?parameter=value")

等等。

4

2 回答 2

7

您也许可以使用该parse_url()功能来分解您的 URL 并删除所有不重要的数据,例如查询字符串。

这是一个简单的例子:

$url = 'http://yoursite.com/foo/bar?some=param';
$urlParts = parse_url($url);
// Array
// (
//     [scheme] => http
//     [host] => yoursite.com
//     [path] => /foo/bar
//     [query] => ?some=param
// )

您现在可以将$urlParts['path']与您的已知路径列表进行比较...

于 2013-04-29T14:34:00.593 回答
1

怎么样:

function isCurrentPage($page)
{
      //Magic
      $page = preg_replace('/https?:\/\/[a-zA-Z0-9_\.\-]+/', '', $page);

      $url = 'http';
      if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
          $url .= 's';
      }
      $url .= '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT']  . $page;
      $handle = curl_init($url);
      curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

      /* Get the HTML or whatever is linked in $url. */
      $response = curl_exec($handle);

      /* Check for 404 (file not found). */
      $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
      curl_close($handle);

      return $httpCode != 404;
}
于 2013-04-29T14:45:05.717 回答