如何在PHP中保存文件并根据可能的故障将文件特征保存到数据库

I am saving a file to a server and I'm saving the filename, user id of the individual who uploaded the file, and various other information about the file to a PostgreSQL database. I ideally want to structure this in a way that is similar to a database transaction. That is, one of the following should occur:

  1. Save file
  2. If successful, save information to database
  3. If saving information to database fails, delete file

OR

  1. Save information to database
  2. If successful, save file
  3. If saving file fails, delete information from database

The only problem with this methodology is step 3 may fail--that is, you may be left with a file saved without corresponding information in the database or you may have database information without a corresponding file saved.

What I want to know is if there is a way that you can use either of the two methods above while ensuring step 3 always occurs or occurs with sufficient reliability that I effectively do not have to worry about failure.

Note that I am using a PostgreSQL database and saving an image file using the imagegif, imagejpeg, and imagepng functions from the GD library.

EDIT

In response to Jack's solid comments below, I forgot to mention that I am interacting with the DB through an API server, so instead of directly interacting with the DB, I am sending REST requests to the API which in turn interacting with the DB. What this effectively means is that I can't just put both database interactions into one transaction.

I decided to choose a sub-optimal but still workable route of running a periodic check that searches for database entries for every filename and if a database entry cannot be found, then the file is deleted. (If anyone is actually interested in the code details, I will gladly provide it in an edit.)

I'm not sure about what you want, but maybe like this:

if(move_uploaded_file(...)){
  if(!mysql_query(...)){
    unlink(...);
  }
}

Forgive me, If I couldn't understand or I've been easy going on your question.