Page 1 of 1

unlink causes prior file_exists to fail

Posted: Wed Aug 22, 2007 3:18 am
by gr8dane
After uploading an image, I have the following code:

Code: Select all

if (file_exists($imgPath))
{
  $imgSize = getImageSize($imgPath);
  $imgWidth = $imgSize[0];
  $imgHeight = $imgSize[1];

  if (($imgWidth != 150) || ($imgHeight != 150))
  {
    $errorMsg[] = "Wrong size";
  }
}
else
{
  $errorMsg[] = "File does not exist";
}

if (!empty($errorMsg))
{
  foreach ($errorMsg as $error) print("<p>$error</p>");

  if ($action == "update")
  {
    $sql = "delete from...";
    $result = mysql_query($sql, $conn) or die(mysql_error());
  }

  if (file_exists($imgPath))
  {
    unlink($imgPath);
  }
}
else
{
  if ($action == "add")
  {
    $sql = "insert into...";
  }
  elseif ($action == "update")
  {
    $sql = "update...";
  }
  $result = mysql_query($sql, $conn) or die(mysql_error());

  print("<p><img src='$imgPath' /></p>\n");
}
It seems pretty straightforward to me, but I'm having two separate problems:

1) If the image size is wrong, the database is updated and image deleted, but $errorMsg contains "File does not exist" instead of "Wrong size". If I remove the unlink($imgPath) portion, everything works fine (except, of course, the unlink doesn't happen), so I can only assume that unlink() is somehow affecting the initial file_exists(). Is it possible for one function to be affected by a function later in the code? How can I both get the correct error message and delete the image?

2) If $action="add" and $errorMsg is empty, I get a "duplicate entry" error. Everything works fine when $action="update". It seems like the db insert is being attempted twice, but why would that happen?

I've been tearing my hair out for the last two days, so any help would be greatly appreciated!!

Posted: Thu Aug 23, 2007 12:52 am
by Benjamin
1: The image might be uploaded, and the database updated, but is the file_exists() function checking the correct path?

2: When you run the insert query, your trying to insert a record with a field containing a value that already exists in the primary key field of the table.

Posted: Fri Aug 24, 2007 10:36 pm
by gr8dane
It turns out that the file was executing twice, for some reason. I'm sure it had something to do with a callback from an image editing site. I've finally solved this problem by splitting the file into three separate files: one for the upload form; one for the callback and move_uploaded_file(); and one for the size-checking, db update, etc. The second file may still be executing twice - and I still don't know why - but it's not affecting anything anymore, so... who cares?!