Skip to content
Advertisement

Image getting deleted from a file path

I have a dashboard where users can login and upload a profile picture of themselves which saves to their profile. This moves the image to the correct folder and also correctly inserts it into the db.

This has been working fine up until recently when I noticed the image disappeared. Within the inspect console I noticed I was getting a 404 not found error on the image, so I checked inside the file path and the image was no longer in there (hence the 404). There is no script at all for the user to delete an image, only to upload.

profile.php:

<p><b>Profile Picture: </b>
<?php 
    $picture = $row['imagePath'];
    if (empty($picture)){
        echo "<img src='profiles/no-image.png' width='100' height='100' >";
    } else {
        echo "<img src='profiles/".$row['imagePath']."' width='100' height='100' >";    
    };
?>
<form action="scripts/edit-picture.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="image"/>
    <input type="submit" name="edit-picture" value="Upload"/>
</p>
</form>

script for edit-image.php

<?php
    require 'db.php';
    session_start();
    $uploadDir = '../profiles/';

    // if edit-picture has been clicked on, run this if statement
    if (isset($_POST['edit-picture'])) {


        $studentID = $_SESSION['studentID'];

        // Creating 4 different variables using the $_FILES global variable to get data about the image that
        // you can view data about a file by doing: print_r($image);         
        $fileName = $_FILES['image']['name'];
        $tmpName = $_FILES['image']['tmp_name'];
        $fileSize = $_FILES['image']['size'];
        $fileType = $_FILES['image']['type'];

        $filePath = $uploadDir.$fileName;
        // The below doesn't work as it assigns different value to folder and in db for image name
        // $filePath = md5($file_name . microtime()) . substr($fileName , -5, 5);

        $result = move_uploaded_file($tmpName, $filePath);
        if (!$result) {
            header("Location: ../profile.php?img=errorFileRelocate");
            exit;
        }
        // Checking file size - working
        else if ($_FILES["image"]["size"] > 5000000) {
            header("Location: ../profile.php?img=errorFileSizeError");
            exit();
        }
        // Check if file name already exists in db - not working
        else if (file_exists($result)) {
            header("Location: ../profile.php?img=errorFileNameExists");
            exit();
        }
        // Allow certain file formats - not working
        else if($result != "jpg" && $result != "png" && $result != "jpeg") {
            header("Location: ../profile.php?img=errorFileTypeError");
            exit();
        }

        // This is to show any errors that may occur if the connection fails, this helps with error checking.
        else if(mysqli_connect_errno()){
              printf("Connect failed: %sn", mysqli_connect_error());
            exit();
        }

        else {
            $stmt = $conn->prepare ("INSERT INTO `profileImage` (`imagePath`, `studentID`) 
            VALUES ( ?, ?) ON DUPLICATE KEY UPDATE `imagePath` = VALUES (`imagePath`) ");
            $stmt->bind_param("si", $fileName, $studentID); 
            $stmt->execute() or die("Failed to insert image into the database");

            header("Location: ../profile.php?img=successImageUploaded");
            exit();
        }
    }     
?>

My folder structure:

profiles
    image1.jpg
    image2.jpg
profile.php
scripts
    edit-image.php

Has anyone ever come across an image actually disappearing from a folder after it being moved in there via move_uploaded_file as ANY help or guidance would be much appreciated.

Advertisement

Answer

Solve conditions for image upload and don’t overwrite existing image files:

<?php
require 'db.php';
session_start();
$uploadDir = '../profiles/';

// if edit-picture has been clicked on, run this if statement
if (isset($_POST[ 'edit-picture' ])) {


    $studentID = $_SESSION[ 'studentID' ];

    // Creating 4 different variables using the $_FILES global variable to get data about the image that
    // you can view data about a file by doing: print_r($image);
    $fileName = $_FILES[ 'image' ][ 'name' ];
    $tmpName = $_FILES[ 'image' ][ 'tmp_name' ];
    $fileSize = $_FILES[ 'image' ][ 'size' ];
    $fileType = $_FILES[ 'image' ][ 'type' ];

    $filePath = $uploadDir . $fileName;
    // The below doesn't work as it assigns different value to folder and in db for image name
    // $filePath = md5($file_name . microtime()) . substr($fileName , -5, 5);

    if (file_exists($filePath)) {
        header("Location: ../profile.php?img=errorFileNameExists");
        exit();

    } // Checking file size - working
    else if ($_FILES[ "image" ][ "size" ] > 5000000) {
        header("Location: ../profile.php?img=errorFileSizeError");
        exit();
    }
    $info = getimagesize($tmpName);
    // empty $info - not known image
    if (empty($info)) {
        header("Location: ../profile.php?img=errorFileTypeError");
        exit();
    } // This is to show any errors that may occur if the connection fails, this helps with error checking.

    $result = move_uploaded_file($tmpName, $filePath);

    if (!$result) {
        header("Location: ../profile.php?img=errorFileRelocate");
        exit;
    }
    else if (mysqli_connect_errno()) {
        printf("Connect failed: %sn", mysqli_connect_error());
        exit();
    } else {
        $stmt = $conn->prepare("INSERT INTO `profileImage` (`imagePath`, `studentID`)
            VALUES ( ?, ?) ON DUPLICATE KEY UPDATE `imagePath` = VALUES (`imagePath`) ");
        $stmt->bind_param("si", $fileName, $studentID);
        $stmt->execute() or die("Failed to insert image into the database");

        header("Location: ../profile.php?img=successImageUploaded");
        exit();
    }
}
?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement