2

I am developing a site where users submit links and they specify an image from that link to be used as a thumbnail. The image will be saved from the webpage, not uploaded by the user.

It seems like I have two options to do this and they are file_get_contents and cURL

file_get_contents example:

$url = 'http://example.com/file_name.jpg';
$img = '/path/file_name.jpg';
file_put_contents($image, file_get_contents($url));

cURL example:

$ch = curl_init('http://example.com/file_name.jpg');
$fp = fopen('/path/file_name.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

In terms of reliability and security, which is preferred? What security concerns does fetching a remote file using the methods present and how can I protect against them?

I am using Codeigniter if there are any classes or functions that would help with this.

Motive
  • 3,071
  • 9
  • 40
  • 63

1 Answers1

2

In terms of reliability and security, which is preferred? What security concerns does fetching a remote file using the methods present and how can I protect against them?

Well, for starters, this isn't any safer than allowing people to upload if that's the point. If you aren't very careful, jimmyB can upload malicious.js to his server and either of your methods will then be serving up his file on your site.

I'd recommend considering CI's File Upload class rather than trying to use these methods. End result either way is you end up with a file on your server; with CI's file upload, at least there are some built-in checks for filetype etc. You can also utilize CI's XSS filtering and stuff.

http://ellislab.com/codeigniter/user_guide/libraries/file_uploading.html

Kumar V
  • 8,810
  • 9
  • 39
  • 58
stormdrain
  • 7,915
  • 4
  • 37
  • 76
  • I'm avoiding the file upload because it's not something the user should be doing. I don't want them to save an image and upload. – Motive Nov 09 '12 at 19:56
  • As for security, my concern is more about ensuring that the file is just an image and doesn't contain anything malicious. – Motive Nov 09 '12 at 19:58
  • Take a look at codeigniters core/libraries/Upload.php file (specifically the MIME type check). You can't rely on the file extension (e.g. jpg/png) to determine the actual type of the file. As far as content is concerned, not much you can do about that short of scanning it with A/V software. See http://stackoverflow.com/a/8638112/183254 – stormdrain Nov 09 '12 at 20:26
  • 1
    For images you can use `exif_imagetype` or `getimagesize` to verify the file is in fact an image. More info: http://stackoverflow.com/a/2006664/398242 – Wesley Murch Nov 09 '12 at 21:18