When the user uploads their first profile picture, there is no problem. But if they uploads a second or even third one, the pictures showed on their profiles do not change if the images have different extensions. Well, just change if:
So, I get three pictures on the folder (saved every time the user uploads a new profile picture): profile1.png, profile1.jpg, profile1.jpeg. And I want to show the latest uploaded picture for the user and, if possible, prevent the creation of so many (3) files with the same name but different extension.
When the user uploads a new picture with the same extension of the previous one, it overwrites it properly. But, if the extension is different, creates a new image in the folder and mostly won't show as the new picture.
I know I don't explain myself properly, sorry. :c
This is the code to show the avatar:
<?php
require 'includes/database.php';
$id = $_SESSION['userId'];
$sqlImg = "SELECT * FROM u_profiles WHERE user_id='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
if (mysqli_num_rows($resultImg) > 0) {
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
if ($rowImg['img_status'] == 0) {
$fileName = 'Uploads/profile'.$id.'*';
$fileInfo = glob($fileName);
$fileExt = explode('.', $fileInfo[0]);
$fileActualExt = $fileExt[1];
$avatar = '<img src="Uploads/profile'.$id.'.'.$fileActualExt.'?'.mt_rand().'">';
echo $avatar;
} else {
$default_avatar = '<img src="Uploads/profile-default.png">';
echo $default_avatar;
}
}
}
And this is the upload code:
<?php
require_once 'database.php';
session_start();
$id = $_SESSION['userId'];
if (isset($_POST['file-submit'])) {
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 1000000) {
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = '../Uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE u_profiles SET img_status=0 WHERE user_id='$id';";
$result = mysqli_query($conn, $sql);
header("Location: ../edit-profile.php?uploads=success");
} else {
header("Location: ../edit-profile.php?error=avatarsize");
}
} else {
echo "There was a problem uploading your file.";
}
} else {
echo "You cannot upload this type of file.";
}
} else {
header("Location: ../index.php");
exit();
}
I manage to solve it: I just had to replace:
$fileNameNew = "profile".$id.".".$fileActualExt;
For:
$fileNameNew = "profile".$id.".jpg";
So all the images will be converted to jpg!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.