What are best practices for uploading files using PHP to ensure that a database is also updated?
Current approach
1) Form validation confirms all fields are of valid types, lengths and clean of xss attacks.
2) File uploaded to server with user submitted filename
3) Database updated with user submitted details including filename
Is that a safe way? Would it be better to update the database first, then query the database for the filename and then upload the file using the database-retrieved filename?
Not looking for code necessarily but rather the philosophy. Thanks!
I would use this order:
First method: operation order dependent
- Form validation
- Check if file was uploaded (don't move it from temp, yet)
- Generate new filename based on your free choice
- Insert data about the file to database using newly generated filename
- Only then, if there's not exception thrown, move the file from temp using filename above. Otherwise, file will be deleted automatically on request end
- If file moving failed for some reason you should remove record from database.
I strongly suggest using some PDO
-like library to "talk" to database as these throw exceptions, instead of raising errors (like mysql_**
function). That way you will know for sure if your query succeeded without constantly checking result of database functions...
Second method: Transactions
- Form validation
- Check if file was uploaded (don't move it from temp, yet)
- Generate new filename based on your free choice
- Start transaction
- "Insert" data about the file to database using newly generated filename.
- Move the file from temp using filename above. If for some reason file move fails, throw an execption.
- Commit transaction
- At this point you're sure that both file is moved and data persisted properly.