PHP urlencode - encodes only the file name and does not apply to slashes

http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip urlencode($myurl); 

The problem is that urlencode also encodes slashes that make the URL unusable. How can I encode only the last file name?

+6
source share
3 answers

Try the following:

 $str = 'http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip'; $pos = strrpos($str, '/') + 1; $result = substr($str, 0, $pos) . urlencode(substr($str, $pos)); 

You are looking for the last slash occurrence. The part before this is OK, so just copy this. And urlencode rest.

+4
source

Pull out the file name and exit it.

 $temp = explode('/', $myurl); $filename = array_pop($temp); $newFileName = urlencode($filename); $myNewUrl = implode('/', array_push($newFileName)); 
0
source

First of all, this is why you should use rawurlencode instead of urlencode .

To answer your question, instead of looking for a needle in a haystack and risking not encoding other possible special characters in your URL, just encode it all and then correct the slashes (and the colon).

 <?php $myurl = 'http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip'; $myurl = rawurlencode($myurl); $myurl = str_replace('%3A',':',str_replace('%2F','/',$myurl)); 

Results in this:

http://www.example.com/some_folder/some%20file%20%5Bthat%5D%20needs%20%22to%22%20be%20%28encoded%29.zip

0
source

Source: https://habr.com/ru/post/947597/


All Articles