Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_get_contents false when url have spaces (encode everything not working)

So, the problem is in this line

$imageString = file_get_contents($image_url);

with urls that have space character it doesn't work. But if I make

$imageString = file_get_contents(urlencode($image_url));

Nothing works.I keep receiving false in the variable.

the ulr is of the kind:

https://s3-eu-central-1.amazonaws.com/images/12/Screenshot from 2016-04-28 18 15:54:20.png
like image 755
Matheus Oliveira Avatar asked Jul 28 '16 14:07

Matheus Oliveira


1 Answers

use this function

function escapefile_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 escapefile_url("http://example.com/foo/bar bof/some file.jpg") . "\n";
echo escapefile_url("http://example.com/foo/bar+bof/some+file.jpg") . "\n";
echo escapefile_url("http://example.com/foo/bar%20bof/some%20file.jpg") . "\n";
like image 136
Akram Wahid Avatar answered Sep 28 '22 08:09

Akram Wahid