Implement the Javascript escape of function code in PHP

  • 2020-03-31 21:00:35
  • OfStack

In this case, it is generally necessary to pre-encode the normal string into a format that the JavaScript unescape() function can interpret. In the case of PHP, the following functions can be used to achieve the same function as the JavaScript escape() function:
 
<?php 
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) { //Multibyte character
$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:
 
<?php 
//Include the escapeToHex() function definition yourself
$test = document.write(<a href="http://www.dirk.sh/assets/uploaded/thisistest.pdf">test</a>); 
echo <script Language="Javascript">eval_r(unescape(" . escapeToHex($test) . "))</script>; 
?> 

If you look at the source code of the page, you will see (because it is too long, it has been manually divided, the actual result should be a full line) :
 
<script Language="Javascript">eval_r(unescape("%64%6F%63%75%6D%65%6E%74%2E%77  
%72%69%74%65%28%27%3C%61%20%68%72%65%66%3D%22%68%74%74%70%3A%2F%2F%77%77%77  
%2E%64%69%72%6B%79%65%2E%6E%65%74%2F%75%70%6C%6F%61%64%65%64%2F%74%68%69%73  
%69%73%74%65%73%74%2E%70%64%66%22%3E%74%65%73%74%3C%2F%61%3E%27%29"))</script> 

And the page that is displayed in the browser is no different from normal HTML.
Note:
1. The second parameter ($encoding) of the escapeToHex() function indicates the encoding of the string you passed in. The default is utf-8.
2. Unescape () is opposed in the ECMAScript v3 specification, which suggests the use of a new alternative function decodeURIComponent(). However, after testing, I found that the decodeURIComponent() function had problems with multi-byte character (Chinese) processing, so I still used the unescape() function.
3. In principle, the above method is only to prevent the search crawler from obtaining the resource address that you think needs to be kept secret. Browsing the page in a javascript-enabled browser is exactly the same as seeing the rendering without such protection.

Related articles: