简体   繁体   English

PHP使用preg_match检测URL中的标签

[英]PHP detecting tags in url with preg_match

I am trying to add a layer of security on top of my prepared statements by adding: 我正在尝试通过添加以下内容在准备好的语句之上添加一层安全性:

if (preg_match('#[@*,!$\'\-;:~`^|\(\\)\\{\\}\\[\\]]#i', $_SERVER['REQUEST_URI']) || strpos($_SERVER['REQUEST_URI'],'script')) { 
    echo 'Cannot do that';
}

I tried adding ([\\<])([^\\>]{1,})*([\\>]) into there but it didn't work. 我尝试将([\\<])([^\\>]{1,})*([\\>])到那里,但是没有用。 I also tried adding a condition if strcmp($_SERVER['REQUEST_URI'], strip_tags($_SERVER['REQUEST_URI'])) != 0 我还尝试添加条件,如果strcmp($_SERVER['REQUEST_URI'], strip_tags($_SERVER['REQUEST_URI'])) != 0

and when i added into the url, it didn't do anything 当我添加到URL时,它什么也没做

any help is appreciated! 任何帮助表示赞赏!

You don't need to validate the URL. 您不需要验证URL。 It seems that you are trying to prevent XSS - for this you should make sure you are escaping the output, not to validate the URL. 似乎您正在尝试防止XSS-为此,您应确保转义输出,而不是验证URL。 If you really want to block requests with html in the url, than you can look at some ready to use solutions such as mod_security 如果您真的想用url中的html阻止请求,则可以查看一些可以立即使用的解决方案,例如mod_security

The first is the tag you'd like to match, and the second is the variable containing the XML or HTML. 第一个是您要匹配的标签,第二个是包含XML或HTML的变量。 Once again, this can be very powerful used along with cURL. 再一次,它可以和cURL一起非常强大地使用。

function get_tag( $tag, $xml ) {
  $tag = preg_quote($tag);
  preg_match_all('{<'.$tag.'[^>]*>(.*?)</'.$tag.'>.'}',
                   $xml,
                   $matches,
                   PREG_PATTERN_ORDER);

  return $matches[1];
}

Matching an XHTML/XML tag with a certain attribute value 匹配具有特定属性值的XHTML / XML标签

This function is very similar to the previous one, but it allow you to match a tag having a specific attribute. 此功能与上一个功能非常相似,但是它允许您匹配具有特定属性的标签。 For example, you could easily match . 例如,您可以轻松匹配。

function get_tag( $attr, $value, $xml, $tag=null ) {
  if( is_null($tag) )
    $tag = '\w+';
  else
    $tag = preg_quote($tag);

  $attr = preg_quote($attr);
  $value = preg_quote($value);

  $tag_regex = "/<(".$tag.")[^>]*$attr\s*=\s*".
                "(['\"])$value\\2[^>]*>(.*?)<\/\\1>/"

  preg_match_all($tag_regex,
                 $xml,
                 $matches,
                 PREG_PATTERN_ORDER);

  return $matches[3];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM