PHP urlencode - encode only the filename and dont touch the slashes
Asked Answered
M

4

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 ?

Modern answered 18/6, 2013 at 22:9 Comment(0)
F
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.

Falito answered 18/6, 2013 at 22:18 Comment(3)
Working perfectly with the missing ")" at the end :)Modern
I would also use rawurlencode instead of urlencode for filenamesBevy
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. "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?Algophobia
I
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

Inhalation answered 16/6, 2016 at 19:54 Comment(0)
P
0

Pull the filename off and escape it.

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

$newFileName = urlencode($filename);

$myNewUrl = implode('/', array_push($newFileName));
Puke answered 18/6, 2013 at 22:19 Comment(1)
this is a slow solution. No need to dump the string into an array.Falito
F
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));
}
Fourdimensional answered 29/4, 2021 at 20:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.