11
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 ?

zero8
  • 1,997
  • 3
  • 15
  • 25
Winston Smith
  • 691
  • 2
  • 7
  • 11

4 Answers4

11

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.

B00MER
  • 5,471
  • 1
  • 24
  • 41
ducin
  • 25,621
  • 41
  • 157
  • 256
  • 1
    Working perfectly with the missing ")" at the end :) – Winston Smith Jun 19 '13 at 00:18
  • 1
    I would also use rawurlencode instead of urlencode for filenames – Emilio Bool Mar 31 '16 at 09:43
  • Are we positive that a forward slash could not exist in a URL somewhere after a ?, even if it shouldn't be there? Technically it should be escaped, but what if it's not. ie. "https://example.com/thing?redirect=www.example.com/other-thing". Maybe it doesn't matter because the URL is not valid, but would there be a solution to properly encode this entire string? – Joel M Dec 30 '20 at 22:06
7

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

Community
  • 1
  • 1
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
0

Pull the filename off and escape it.

$temp = explode('/', $myurl);
$filename = array_pop($temp);

$newFileName = urlencode($filename);

$myNewUrl = implode('/', array_push($newFileName));
Schleis
  • 41,516
  • 7
  • 68
  • 87
0

Similar to @Jeff Puckett's answer but as a function with arrays as replacements:

function urlencode_url($url) {
    return str_replace(['%3A','%2F'], [':', '/'], rawurlencode($url));
}