Implement Javascript's escape() function code in PHP_PHP tutorial

WBOY
Release: 2016-07-21 15:34:53
Original
965 people have browsed it

Here, it is generally necessary to pre-encode the normal string into a format that can be interpreted by the JavaScript unescape() function. Taking PHP as an example, you can use the following function to achieve the same function as the escape() function in Javascript:

Copy code The code is as follows:

function escapeToHex($string, $encoding = UTF-8) {
$return = ;
for ($x = 0; $x < mb_strlen($string, $encoding); $x ++) {
$str = mb_substr($string, $x, 1, $ encoding);
if (strlen($str) > 1) { // Multi-byte characters
$return .= %u . strtoupper(bin2hex(mb_convert_encoding($str, UCS-2, $encoding) ));
} else {
$return .= % . strtoupper(bin2hex($str));
}
}
return $return;
}
? >

Suppose we want to hide the following address: http://www.dirk.sh/assets/uploaded/thisistest.pdf
We can use the following script to achieve this:
Copy the code The code is as follows:

// Please include the escapeToHex() function definition yourself
$test = document.write(test);
echo

The page displayed in the browser is no different from ordinary html.
Note:
1. The second parameter ($encoding) of the escapeToHex() function indicates the encoding of the string you pass in. The default is UTF-8. If you use other encodings, you should call the function Explicitly specified;
2. The use of unescape() is deprecated in the ECMAScript v3 specification. The specification recommends using the new alternative function decodeURIComponent(), but I found through testing that the decodeURIComponent() function does not support multi-byte characters (Chinese). ) processing problem, so the unescape() function is still used.
3. In principle, the above method is only to prevent search crawlers from obtaining the resource addresses that you think need to be kept confidential. When browsing the page in a browser that supports Javascript, the rendering seen without this protection mechanism is completely different. Same.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322351.htmlTechArticleHere, it is generally necessary to pre-encode the normal string into a format that can be interpreted by the JavaScript unescape() function. Taking PHP as an example, you can use the following function to implement escap in Javascript...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template