【问题标题】:How would you sanitize the URLs in this function?您将如何清理此函数中的 URL?
【发布时间】:2013-12-20 16:21:49
【问题描述】:

我是 PHP 新手,很难尝试清理此函数创建的输出。任何反馈将不胜感激。

函数如下:

function getTemplateBreadcrumbs($path, $title){

  $path = str_replace("/", "/", $path);

  $breadcrumbs = "<ul>\n";
  $breadcrumbs .= "  <li><a href=\"/\">Home</a></li>\n";

  $directories = explode("/", $path);
  $tempPath = "/";

  for($x=1; $x < count($directories)-2; $x++){
    if($directories[$x] != null){

      $tempPath .= $directories[$x] . "/";

      $linkText = getPageVariable("pageTitle", $_SERVER["DOCUMENT_ROOT"] . $tempPath . "index.php");
      if($linkText == null){
        $linkText = ucwords(str_replace("-", " ", $directories[$x]));
      }

      $breadcrumbs .= "  <li><a href=\"" . $tempPath . "\">$linkText</a></li>\n";
    }
  }

  $breadcrumbs .= "  <li>" . $title . "</li>\n";
  $breadcrumbs .= "</ul>\n";

  return $breadcrumbs;
}

【问题讨论】:

  • 消毒是为了什么?您必须对将要使用数据的环境进行清理。清理不是您可以像在食物上撒盐那样撒在数据上的东西。

标签: php url output sanitize


【解决方案1】:

filter_var()FILTER_SANITIZE_URL flag 一起使用。

$url = filter_var($tempPath , FILTER_SANITIZE_URL);

【讨论】:

  • 你得到了正确的链接,然后你的代码显示FILTER_VALIDATE_URL
  • @DigitalChris 哎呀。固定。
  • 非常感谢。 FILTER_SANITIZE_URL 解决了我遇到的问题。非常感谢!
【解决方案2】:

您可以使用echoprint_r()var_dump() 进行调试 我用:

echo htmlspecialchars(print_r($var));

如何使用的示例:

function getTemplateBreadcrumbs($path, $title){

  //rest of the code
  echo '<pre>';
  echo htmlspecialchars(print_r($breadcrumbs));
  echo '</pre>';
  return $breadcrumbs;
}

如果您想从代码的另一部分进行测试:

$teste = getTemplateBreadcrumbs('/home/index', 'Home Page');
echo '<pre>';
echo htmlspecialchars(print_r($teste));
echo '</pre>';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 2023-03-27
    • 1970-01-01
    • 2011-02-23
    • 2020-09-12
    • 1970-01-01
    相关资源
    最近更新 更多