开发者

Save uploaded image with unique name, create thumbnail and write db only if all goes well

I'm coding a php script to get an uploaded picture, move it in a folder (let's say "/img") renaming it with a unique name, create a thumbnail with the same name in a subfolder ("/img/small"), and insert a record for the picture in my database where the picture's name is the primary key.

Basically I'm obtaining the unique name from the database itself, after an INSERT INTO, with mysql_insert_id. This means that I'm moving the picture and creating the thumbnails after the database insertion, so if something goes wrong (e.g.: invalid image format, not enough space, etc.) I should perform a "DELETE" from the database, pseudocode:

perform "INSERT INTO ..."

name = inserted_id

if (!move_file(temp, "/img/" + name)) perform "DELETE WHERE id = name"

if (!create_thumbnail(temp, "/img/small" + name)) perform "DELETE WHERE id = name"

I'd like to know if some of you faced the same problem and came out with a more开发者_Python百科 rational and elegant solution.


Use transactions instead. The basic procedure would be:

  1. start a transaction
  2. insert a skeleton image record into the db. Enough to create a record, but not enough that it would show the image as available to the rest of your system
  3. retrieve the ID of the new record
  4. do the image processing (resizing, renaming, moving, etc...)
  5. Update the database record with anything else you need to store (file sizes, resolution, availability, etc...)
  6. if everything went ok, commit the transaction, otherwise roll back.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜