测试字符串是否用PHP进行URL编码 [英] Test if string is URL encoded in PHP

查看:518
本文介绍了测试字符串是否用PHP进行URL编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试字符串是否经过URL编码?

How can I test if a string is URL encoded?

以下哪种方法更好?

  • 在字符串中搜索将要编码的字符,否则将不进行编码,或者
  • 使用我做的类似的东西

function is_urlEncoded($string){
 $test_string = $string;
 while(urldecode($test_string) != $test_string){
  $test_string = urldecode($test_string);
 }
 return (urlencode($test_string) == $string)?True:False; 
}

$t = "Hello World > how are you?";
if(is_urlEncoded($sreq)){
 print "Was Encoded.\n";
}else{
 print "Not Encoded.\n";
 print "Should be ".urlencode($sreq)."\n";
}

上面的代码有效,但在字符串经过双重编码的情况下无效,如以下示例所示:

The above code works, but not in instances where the string has been doubly encoded, as in these examples:

  • $t = "Hello%2BWorld%2B%253E%2Bhow%2Bare%2Byou%253F";
  • $t = "Hello+World%2B%253E%2Bhow%2Bare%2Byou%253F";
  • $t = "Hello%2BWorld%2B%253E%2Bhow%2Bare%2Byou%253F";
  • $t = "Hello+World%2B%253E%2Bhow%2Bare%2Byou%253F";

推荐答案

您将永远无法确定字符串是否经过URL编码,或者是否应该包含序列%2B.相反,它可能取决于字符串的来源,即它是手工制作的还是来自某些应用程序.

You'll never know for sure if a string is URL-encoded or if it was supposed to have the sequence %2B in it. Instead, it probably depends on where the string came from, i.e. if it was hand-crafted or from some application.

最好在字符串中搜索将要编码的字符,否则将不进行编码,如果存在则表示未编码.

Is it better to search the string for characters which would be encoded, which aren't, and if any exist then its not encoded.

我认为这是一种更好的方法,因为它将处理以编程方式完成的事情(假设应用程序不会留下未编码的字符).

I think this is a better approach, since it would take care of things that have been done programmatically (assuming the application would not have left a non-encoded character behind).

在这里会令人困惑的一件事...从技术上讲,如果%应该"被编码在最终值中,则它应该被编码,因为它是一个特殊字符.您可能必须结合使用多种方法来查找应编码的字符,并验证是否在没有找到字符串的情况下成功解码了该字符串.

One thing that will be confusing here... Technically, the % "should be" encoded if it will be present in the final value, since it is a special character. You might have to combine your approaches to look for should-be-encoded characters as well as validating that the string decodes successfully if none are found.

这篇关于测试字符串是否用PHP进行URL编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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