-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload_avatar.php
More file actions
51 lines (48 loc) · 2.17 KB
/
upload_avatar.php
File metadata and controls
51 lines (48 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
// Kết nối cơ sở dữ liệu
$link = @mysqli_connect("localhost", "root", "", "dating_app") or die("Không thể kết nối cơ sở dữ liệu");
// Kiểm tra nếu có file được upload
if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
$userID = 1; // ID người dùng (cần thay đổi theo logic của bạn)
$uploadDir = './uploads/avatars/'; // Thư mục lưu ảnh
if (!is_dir($uploadDir)) {
if (!mkdir($uploadDir, 0777, true)) {
// Nếu không thể tạo thư mục, xóa file tạm thời đã upload
if (isset($_FILES['avatar']['tmp_name']) && file_exists($_FILES['avatar']['tmp_name'])) {
unlink($_FILES['avatar']['tmp_name']); // Xóa file tạm thời
}
die("Failed to create upload directory and temporary file has been deleted.");
}
}
$fileName = basename($_FILES['avatar']['name']);
$fileTmpPath = $_FILES['avatar']['tmp_name'];
$fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
// Kiểm tra định dạng file
if (in_array($fileExtension, $allowedExtensions)) {
// Tạo tên file duy nhất
$newFileName = 'avatar_' . $userID . '_' . time() . '.' . $fileExtension;
$destination = $uploadDir . $newFileName;
// Di chuyển file vào thư mục đích
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
if (move_uploaded_file($fileTmpPath, $destination)) {
// Cập nhật đường dẫn ảnh vào cơ sở dữ liệu
$avatarPath = $destination;
$sql = "UPDATE userinformation SET Avt = '$avatarPath' WHERE ID = $userID";
if (mysqli_query($link, $sql)) {
echo "Avatar uploaded and updated successfully!";
} else {
echo "Failed to update avatar in database.";
}
} else {
echo "Failed to move uploaded file.";
}
} else {
echo "Invalid file type. Only JPG, JPEG, PNG, and GIF are allowed.";
}
} else {
echo "No file uploaded or an error occurred.";
}
?>