1

When a user uploads a photo, it checks to see if they already have one; and if they do I want it to delete the old one (which could have any extension) and then put the new one. Is there a way to do that without getting the old extension from the database? Code at the moment:

        $del = $members->prepare("insert into profiles(userid, path, width, height, type, rtu, ext) values(?, ?, ?, ?, ?, ?, ?) 
                                    ON DUPLICATE KEY UPDATE path = ?, width = ?, height = ?, type = ?, rtu = ?, ext = ?, time = NOW()");
        $del->bind_param('sssssssssssss', $_SESSION['token'], $title, $file_info[0], $file_info[1], $file_info[2], $rh, $extension, 
        $title, $file_info[0], $file_info[1], $file_info[2], $rh, $extension);

        $del->execute();

        $new_file_name = "bb-x".$_SESSION['token'].".".$extension;

        if ($del->affected_rows > 0) {

            unlink('profiles/bb-x62'<any extension>);
        }

        $move_file = move_uploaded_file($file['tmp_name'], $upload_image_to_folder.$new_file_name);
Andy Lobel
  • 3,356
  • 9
  • 31
  • 40

2 Answers2

13

Instead of unlink('profiles/bb-x62'<any extension>);

Use these two lines:

$file_pattern = "profiles/bb-x62.*" // Assuming your files are named like profiles/bb-x62.foo, profiles/bb-x62.bar, etc.
array_map( "unlink", glob( $file_pattern ) );

That should do the trick.

Camden S.
  • 2,185
  • 1
  • 22
  • 27
  • 2
    You want to be VERY careful about deleting files based on user input, that's an attack just waiting to happen. Far safer to just look the file up in the database. – John Carter Apr 13 '12 at 22:46
  • 1
    wheres the user input in that answer oO – Andy Lobel Apr 13 '12 at 22:48
  • should i be using transactions with this sort of thing as well, like at the end of the move file (if it works like that idk) – Andy Lobel Apr 13 '12 at 22:50
1

You could get a list of files from the server in the affected directory and search it for an entry with the same filename right up to the dot and extension. Take the full filename from the server data and delete that file. There's some risk of deleting a very similar filename, but you could build in checks to determine the filename is the same except for the extension.

Sounds like getting the full filename from the database might be less trouble and load on the server...

Surreal Dreams
  • 26,055
  • 3
  • 46
  • 61
  • +1 It's not what the question asked for exactly but this definitely seems like a more sensible approach. – John Carter Apr 13 '12 at 22:44
  • PHP's built-in glob() function does something similar (http://php.net/glob) thus the recommendation in my answer. – Camden S. Apr 13 '12 at 22:46