过滤输入URL的最佳方法是什么? [英] What is the best way to filter URLs for input?

查看:147
本文介绍了过滤输入URL的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单接受来自PHP用户的URL。



我应该允许或禁止使用哪些字符?目前我使用

$ input = preg_replace(/ [^ a-zA-Z0-9-\?:#。()\,/ \& amp ; \\\\] /,,$ string);

$ input = substr($ input,0,255);



所以,它被修剪为255个字符,只能包括字母,数字和? - _:#(),&'/



任何我应该剥离的东西我没有,或者我剥离的东西可能需要在一个有效的URL吗?

解决方案

RFC 1738 定义了URL规范,规定只有字符

  abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 + .- 

可以在URL方案中使用,只有字符

  abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 $ -_。+! *'(); /?:@ =&安培; 

可以在URL的特定于方案的部分内使用未编码。 (; /?:@ =& ),如果使用unncoded,必须用于保留目的,但是如果你只是检查无效字符,不需要担心)。所以,如果你想完全一般性,我会检查这个正则表达式的URL:

 /([a-zA-Z + .-] +:\ / \ /)(![A-ZA-Z0-9\ $ \-_\.\ + \ * \(\),\\ \\ \\ \\ \\ \\ \\?\:\ @ \ = \&] +)/

(可能有些转义是没有必要的)。如果你只是在寻找HTTP URL,其他的答案应该没问题。

I have a form that is accepting URLs from users in PHP.

What characters should I allow or disallow? Currently I use

$input= preg_replace("/[^a-zA-Z0-9-\?:#.()\,/\&\'\\"]/", "", $string);

$input=substr($input,0,255);

So, it's trimmed to 255 chars and only can include letters, numbers, and ? - _ : # ( ) , & ' " /

Anything I should be stripping that I'm not, or anything I'm stripping that might need to be in a valid URL?

解决方案

RFC 1738 which defines the URL specification states that only the characters

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+.-

may be used within a URL scheme, and only the characters

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$-_.+!*'(),;/?:@=&

may be used unencoded within the scheme-specific part of a URL. (;/?:@=&, if used unencoded, must be used for their "reserved purposes", but if you're just checking for invalid characters you don't need to worry about that). So if you want full generality, I'd check the URL against this regex:

"/([a-zA-Z+.-]+:\/\/)?([a-zA-Z0-9\$\-_\.\+\!\*'\(\),\;\/\?\:\@\=\&]+)/"

(probably some of that escaping is not necessary). If you're only looking for HTTP URLs, (some of) the other answers should be fine.

这篇关于过滤输入URL的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆