Home > Net >  Allow user to upload/change profile image from a default image in php
Allow user to upload/change profile image from a default image in php

Time:05-21

So I want the users to be able to upload profile images in which they will be able to be seen when making posts/commenting or replying to other comments/posts. So far the user is able to upload an image in which the image gets stored in a uploads/ folder, but once I reload the profile page the image is not there anymore and it is not currently being saved to the user. I also think that the image is not saved nor connected to the specific user when uploading. Heres how the codes look:

profile.php

<?php
    require 'header.php';
    require 'upload.php';
    if(!isset($_SESSION["username"])){header("location: login.php");}
    

?>
<body>


<div >
  <button  onclick="openTab(event, 'User Profile')" id="default">User Profile</button>
  <button  onclick="openTab(event, 'Security')">Security & Privacy</button>
  <button  onclick="openTab(event, 'Tokyo')">Tokyo</button>
  <button  onclick="openTab(event, 'Tokyo')">Tokyo</button>
</div>

<div id="User Profile" >
<?php
    echo '<img src="'.$target_file.'">';
   if(isset ($_SESSION["username"])){
   echo "<h3 id='username'>" . $_SESSION["username"] . "</h3>";
   
        }
    ?>
      <?php
        if(isset ($_SESSION["role"])){
          echo "<h4>" . $_SESSION["role"] . "</h4>";
            }
            
           
          ?>
              <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" enctype="multipart/form-data">
              <input type="file" name="fileToUpload" id="fileToUpload">
              <button type="submit" name="submit" value="Upload Image">Upload Image</button>
              </form>

upload.php

<?php
require_once 'header.php';
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "File is not an image.";
    $uploadOk = 0;
  }
}

// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
  $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
  if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
  } else {
    echo "Sorry, there was an error uploading your file.";
  }
}

?>

As far as I've understood this, it would not be good to save the images to the database as it would make the website/database a lot slower. However, I would still need to reference the image somehow to the specific user I assume? I am quite new at this. This is how the table structures look in MYSQL:

CREATE TABLE IF NOT EXISTS `users` (
  `users_id` int(11) NOT NULL AUTO_INCREMENT,
  `users_username` tinytext
  `users_password` longtext
  `users_email` tinytext
  `create_datetime` datetime
  `users_role` tinytext
  `gender` tinytext
  PRIMARY KEY (`users_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

CREATE TABLE IF NOT EXISTS `profileimg` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `users_id` int(11) NOT NULL,
  `status` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;

Any tips on how I could improve this? Thank you guys!

CodePudding user response:

It is indeed not the most optimised to save the image directly into the database, but what you can do (which is what is generally done actually) is to save the path to the image into the database once it has been saved onto your server (that would come right inside the move_uploaded_file condition block in your code).

You just have to change a bit your tables to include a string that will be a path to the uploaded image, and then you will be able to load the image from the saved path anytime you want to display it.

CodePudding user response:

I don't know the answer but I think i can exploit this... Maybe I make a payload with extend type jpg -> upload to you website -> refresh page -> take control your website and hosting... Just joking... but upload image by user -> shouldn't be... Let's using avatar from Social Network is better!

  • Related