简体   繁体   中英

Upload image and thumbnail via PHP

So I need a very simple script to resize an image and upload the thumbnail in PHP. Please don't recommend a library because I'd rather be able to edit and learn from it with ease.

I had written a small PHP script on my own to upload an image and name it after its ID in the database and intended to make the thumb as simple as adding "thumb" to the end of the name (such as 123thumb.jpg), but I sort of ruined it trying to work in thumbnails.

Here's what it somewhat looked like:

mysql_query('
    INSERT INTO art (
        artist,
        title,
        extension)
    VALUES (
        1,
        "Penguins",
        "'.end(explode('.',$_FILES['art']['name'])).'")') ;
move_uploaded_file($_FILES['art']['tmp_name'],'images/'.mysql_insert_id()..end(explode('.',$_FILES['art']['name']))

Bad bad design. 1. No error checking on the query and using raw user-provided data in the query, leading to a gaping sql injection vulnerability. 2. Using raw user-provided filenames to store the files in, even if it does have a database ID prepended. 3. Blindly assuming the insert query worked, such that msyql_insert_id might not return anything. 3. blindly assuming the move command works.

A better/safer methodology is:

if ($_FILES['art']['error'] !== UPLOAD_ERR_OK) {
   die("Upload failed with error code " . $_FILES['art']['error']);
}

$filename = mysql_real_escape_string(basename($_FILES['art']['name']));
mysql_query("INSERT .... VALUES (1, 'Penguins', '$filename', ...)") or die(mysql_error());

move_uploaded_files(...) or die("Failed to move file");

There's more/better validation/error handling that can be done, but this is the skeleton of something far safer/more reliable than your version.

Besides all of the potential exploits of your script (see other answer) this page might be very helpful for teaching you how to resize the image to get a thumbnail. You will have to use a library like GD (built in to PHP) to resize the image.

http://salman-w.blogspot.com/2008/10/resize-images-using-phpgd-library.html

(Found it in another SO question.)

EDIT: And, of course, don't forget the PHP manual. http://php.net/manual/en/book.image.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM