Allow the users to upload profile images in PHP

Issue

I already have a proper image upload system. It uploads & stores the image in the folder /uploads/, now I need to keep track of who uploads the profile image, and I want to display that image on my user profile page.

This is my upload.php:

<?php
include('db.php');

// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
  $_SESSION['message'] = "You must log in before viewing your profile page!";
  header("location: error.php");    
}

if (isset($_POST['submit'])) {
    $file = $_FILES['file'];

    $fileName = $file['name'];
    $fileTmpName = $file['tmp_name'];
    $fileSize = $file['size'];
    $fileError = $file['error'];
    $fileType = $file['type'];

    $fileExt = explode('.', $fileName);
    $fileActualExt = strtolower(end($fileExt));

    $allowed = array('jpg', 'jpeg', 'png', 'pdf');

    if (in_array($fileActualExt, $allowed)) {
        if ($fileError === 0) {
            if ($fileSize < 1000000) {
                $fileNameNew = uniqid('', true).".".$fileActualExt;
                $fileDestination = 'uploads/'.$fileNameNew;
                move_uploaded_file($fileTmpName, $fileDestination);
                header("Location: user.php");
            } else {
                echo "Your file is too big!";
            }
        } else {
            echo "There was an error uploading your file!";
        }
    } else {
        echo "You cannot upload files of this type!";
    }
}

and this is the HTML:

<form action="upload.php" method="POST" enctype="multipart/form-data" >
<div class="specialcontainer">
    <input type="file" name="file" id="file" class="inputfile">
</div>
  <div class="inner"></div>
    <button type="submit" name="submit" class="uploadbuttonstyle">Upload</button>
</form>
</div>

I have 2 tables for this purpose, one handles the username, fname, lname, email, password, user description etc. And I want the second one to display the status of their profile image i.e if they have uploaded an image, status will be 1, if they haven’t then status will be 0. And if status is 0, image from the directory /uploads/profiledefault.jpg will be displayed which is the default profile image for the new users. I’m still a beginner when it comes to PHP. Was hoping someone can show me the way here.

Solution

You don’t need to use another table for this. Just add one more column “profile_image” in your first table and save image in that table

 if (move_uploaded_file($fileTmpName, $fileDestination)) {
 // save/update "profile_image" field here.
}

and when you want to show profile image just check where profile_image column is blank or not. If it is then show default image “/uploads/profiledefault.jpg” else show profile image from the “profile_image” column.

Answered By – Sehdev

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published