Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP urlencode - encode only the filename and dont touch the slashes

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

The problem is that urlencode will also encode the slashes which makes the URL unusable. How can i encode just the last filename ?

like image 310
Winston Smith Avatar asked Jun 18 '13 22:06

Winston Smith


2 Answers

Try this:

$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're looking for the last occurrence of the slash sign. The part before it is ok so just copy that. And urlencode the rest.

like image 75
ducin Avatar answered Sep 19 '22 16:09

ducin


First of all, here's why you should be using rawurlencode instead of urlencode.

To answer your question, instead of searching for a needle in a haystack and risking not encoding other possible special characters in your URL, just encode the whole thing and then fix the slashes (and 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

like image 33
Jeff Puckett Avatar answered Sep 19 '22 16:09

Jeff Puckett