Sarah
Sarah

Reputation: 459

Uploaded an image using `file_put_contents` with 0 bytes (empty)?

I've downloaded an image using file_get_contents from URL then uploaded it to my website using file_put_contents, the image appears in the specified directory, however it has the size of zero. I've changed the permissions to 777 in this directory and the parent directories, but nothing happened.

I already tried the same code in the localhost, and it worked perfectly.

By the way, I'm using a joomla website and a component called RSform Pro, it is used for creating forms and gives an area where you can edit the POST data before saving it in the database. Here's the code.

$content = file_get_contents($_POST['image_url']);

$date = date ('d-m-Y_h-m-i');   $random = rand(0,1000);
$name = 'mysite_'.$date.$random.'.png';

$filename = '/home/mysite/images/'.$name;

file_put_contents($filename, $content);

Upvotes: 0

Views: 6306

Answers (1)

Cristian Rodriguez
Cristian Rodriguez

Reputation: 629

Where I start, there is so much wrong this code...

  1. You have to check the return value of file_get_contents and ensure your host allows retriving remote data (allow_url_fopen set to On in php.ini)
  2. After that, everything else is awfully wrong and punches a security hole in your application.The result you store in the $content variable must be written to an unique temporary file, whose only correct way of generation is using the tempnam() function.
  3. After issing file_put_contents to the filename generated by tempnam() and checking return values of the operation, you have to verify if the file is really a png image using php's fileinfo functions.
  4. If the previous step succeeds then use rename() to move the file to permanent storage, using a name that is very unlikely to be repeated ever. for that use $filename = hash('sha256', openssl_random_pseudo_bytes(16)) . 'png'. then store the resulting filename so it can be used to construct the links your application will show to users.

Upvotes: 2

Related Questions