Search code examples
phpdelete-fileunlink

Unlink jpeg file when the url path is provided by a value of the mysql database


I'm trying to delete a jpg. The path to that image is stored in the database under the field name PandFoto3. After that I empty the field in the database. So far I have the following code:

    if(isset($_POST['F3Verwijderen']))
    try 
    {               
        
        //delete the file
        $sql = "SELECT PandFoto3 FROM tblpand WHERE `PK_Pand` = '".$pandid."'";
        
        $con = mysql_connect('immocorbati.be.mysql', 'immocorbati_be', 'zx4ge6ty');
        if (!$con) {
        die('Could not connect: ' . mysql_error());
        }
        mysql_select_db("immocorbati_be");
        $result = mysql_query($sql, $con);
        while ($row = mysql_fetch_array($result)) {
            if(file_exists($row['PandFoto3'])){
                unlink($row['PandFoto3']);
            } else {
                echo $row['PandFoto3'];
            }
        }
        //delete the value from the field PandFoto3
        mysql_query("UPDATE tblpand SET PandFoto3 = NULL WHERE `PK_Pand` = '".$pandid."'");
        mysql_close($con);          

    
        header('Location: ../admin/pand-aanpassen.php?id='.$pandid);
    }
    
    catch (Exception $e) 
    {
        $feedback = $e->getMessage();
    }

The url path is deleted from the database so that works. The file isn't deleted however. The code does reach the "while ($row = mysql_fetch_array($result))", but it fires the echo from the else case.

This echo in this case is: uploadImages/picname.jpg which is the correct path to the picture. However, the if is not fired and thus the picture is not deleted.

ps: I realized that I didn't use mysqli_connect, I'll edit this asap


Solution

  • use absolute path, e.g. /var/www/uploadImages or D:/www/uploadImages: In this case, your directory "uploadImages" exists in same document root as your php script.

    <?php
        if(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3'])) {
                    unlink($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3']);
                } else {
                    echo $row['PandFoto3'];
                }