Php - file_get_contents - Uploading files with spaces in the file name does not work

I am trying to upload files using file_get_contents() . However, if the location of the file is http://www.example.com/some name.jpg , the function cannot load it.

But if the URL is listed as http://www.example.com/some%20name.jpg , the same one loads.

I tried rawurlencode() , but this hides all the characters in the url and the download ends again.

Can anyone suggest a solution for this?

+7
source share
6 answers

I think this will work for you:

 function file_url($url){ $parts = parse_url($url); $path_parts = array_map('rawurldecode', explode('/', $parts['path'])); return $parts['scheme'] . '://' . $parts['host'] . implode('/', array_map('rawurlencode', $path_parts)) ; } echo file_url("http://example.com/foo/bar bof/some file.jpg") . "\n"; echo file_url("http://example.com/foo/bar+bof/some+file.jpg") . "\n"; echo file_url("http://example.com/foo/bar%20bof/some%20file.jpg") . "\n"; 

Exit

 http://example.com/foo/bar%20bof/some%20file.jpg http://example.com/foo/bar%2Bbof/some%2Bfile.jpg http://example.com/foo/bar%20bof/some%20file.jpg 

Note:

I would use urldecode and urlencode for this, since the output would be identical for each url. rawurlencode save + , even if %20 is probably appropriate for any url you use.

+24
source

As you already found out, urlencode () should only be used on every part of the URL that needs escaping.

From the docs for urlencode (), just apply it to the image file name, which will give you a problem and leave the rest of the url. From your example, you can safely encode everything that follows the last "/"

+1
source

Here is maybe the best solution. If for any reason you are using a relative URL, for example:

//www.example.com/path

Prior to php 5.4.7, this would not create an array element [schema] that would reset the maček function. This method can be faster.

$url = '//www.example.com/path';

 preg_match('/(https?:\/\/|\/\/)([^\/]+)(.*)/ism', $url, $result); $url = $result[1].$result[2].urlencode(urldecode($result[3])); 
0
source

Assuming that only the file name has the problem, this is the best approach. only urlencode in the last section i.e. file name.

 private function update_url($url) { $parts = explode('/', $url); $new_file = urlencode(end($parts)); $parts[key($parts)] = $new_file; return implode("/", $parts); } 
0
source

I pull my hair out with this stuff.

This works great if I have a normal name, for example http://webdesign-flash.ro/ht/rap/start/content/mp3/0 1.mp3, but if the file has spaces or some non-standard characters, such as && * (no longer working, I get okb size on disk.

I do not understand why this does not work, I tried to encode decoding, but it did not work.

What am I missing?

0
source

This should work

 $file = 'some file name'; urlencode($file); file_get_contents($file); 
-one
source

All Articles