Uploading profile image using php and mysql

Uploading profile image using php and mysql
0

#1

Hi, my self Sushanth, i have problem uploading the image to the designated folder. Here is the code. The error says undefined file in upload.php on line 9.
here is the code for upload.php,

<?php
session_start();
include_once 'dbh.php';
$id = $_SESSION['id'];

if(isset($_POST['upload_submit'])){
    $file= $_FILES['file'];
    $fileName = $_FILES['file']['name'];
    $fileTmp = $_FILES['file']['tmp_name'];
    $fileSize = $_FILES['file']['size'];
    $filesError = $_FILES['file']['error'];
    $fileType = $_FILES['file']['type'];
    
    $fileExt = explode('.',$_FILES['file']['name']);
    $fileActualExt = strtolower(end($fileExt));
    $allowed = array('jpg','jpeg','png','pdf');
    if(in_array($fileActualExt,$allowed)){
        if($_FILES['file']['error'] ===  0){
            if($_FILES['file']['size'] < 1000000){            
                $fileNameNew = "profile".$id.".".$fileActualExt;
                $fileDestination = 'uploads/'.$fileNameNew;
                move_uploaded_file($_FILES['file']['tmp_name'],$fileDestination);
                $sql = "UPDATE profileimg SET status = 0 WHERE userid ='$id';";
                $result = mysqli_query($conn, $sql);
                header("Location: index.php?uploadsucess");
            }else{
                echo "Your file is too big!";
            }
        }else{
            echo "You have an error uploading your file!";
        }
    }else{
        echo "You cannot upload files of this type!";
    }

}

here is the code for index.php,
<?php
    session_start();
    include_once 'dbh.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .container{
            margin:20px;
            padding:10px;
            background:#ccc;
           
        }
        .container img{
            width:50px;
            height:50px
        }
        .container p{
            font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
            font-size:20px;
            position:inherit;
            float:right;
            
        }
    </style>
</head>
<body>
    <?php
        $sql = "SELECT * from user";
        $result = mysqli_query($conn, $sql);
        if(mysqli_num_rows($result)> 0){
            while ($row = mysqli_fetch_assoc($result)){
                $id= $row['id'];
                $sqlimg = "SELECT * FROM profileimg WHERE userid='$id'";
                $resultimg=mysqli_query($conn,$sqlimg);
                while($rowimg = mysqli_fetch_assoc($resultimg)){
                    echo "<div class=container>";
                        if($rowimg['status'] == 0){
                            echo "<img src= 'uploads/profile".$id.".jpg'>";
                        }else{

                            echo "<img src='uploads/pd.jpg'>";
                        }
                        echo "<p>".$row['username']."</p>";
                    echo "</div>";
                }
            }
        }else{
            echo "There are no users yet!";
        }

        if(isset($_SESSION['id'])){
            if ($_SESSION['id'] == 1){
                echo "You are logged in as user #1";
            }
            echo "<form action='upload.php' method='POST'enctype='mutlipart/form-data'>
            <input type='file' name='file'>
            <button type='submit' name='upload_submit'>Upload</button></form>";
        }else {
            echo "You are not logged in!";
        }
    ?>
    <p>Login as user!</p>
    <form action="login.php" method="POST">
      <button type="submit" name="submitlogin">Login</button>
    </form>
    <p>Logout as user!</p>
    <form action="logout.php" method="POST">
      <button type="submit" name="submitlogout">Logout</button>
    </form>
</body>
</html>

My database name is login.
Help me to resolve this problem.


#2

Firstly, welcome to the forums.

Secondly, I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

While we are primarily here to help people with their Free Code Camp progress, we are open to people on other paths, too. Some of what you are asking is pretty trivial in the Free Code Camp context, so you might find that if you’re not getting the instruction and material you need in your current studies, the FCC curriculum will really help you get started. At a modest guess I’d say investing a 4-5 hours working through the curriculum here will really pay off. You can find the curriculum at https://freecodecamp.org.

We do not focus on PHP here as we focus on JavaScript for front-end and back-end.

With your current questions, we don’t have enough context to know what you already know or don’t know, so it is impossible to guide you without just telling you the answer (which we won’t do).

Happy coding :slight_smile:


#3

Hello @sushanth

I can see the error is that you are not checking the image file uploading errors.

Before the $file = $_FILES['file']; line, you can add the following.

if (empty($_FILES['file']) {
   exit('Empty File');
}

In any type of uploading, you should do some more validations, such as

  1. Checking the image upload
  2. Checking for upload time errors
  3. Checking whether the uploaded file exists in the server
  4. Validating the file size
  5. Validating the Mime Type

Also, you should use prepared statements when using user inputs for queries. So, mind changing your code to MYSQLI prepared statements

See this complete beginner’s guide to learn more on image uploading with PHP and MYSQL.