-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathupload_profile_image.php
More file actions
55 lines (45 loc) · 1.6 KB
/
upload_profile_image.php
File metadata and controls
55 lines (45 loc) · 1.6 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
52
53
54
55
<?php
header('Content-Type: application/json');
session_start();
if (!isset($_SESSION['teacher_id'])) {
echo json_encode(['success' => false, 'error' => 'Not authenticated']);
exit;
}
if (!isset($_FILES['profileImage'])) {
echo json_encode(['success' => false, 'error' => 'No image uploaded']);
exit;
}
// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "frontend&backend";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die(json_encode(['success' => false, 'error' => "Database connection failed"]));
}
// Upload directory
$uploadDir = 'profile_images/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
// Generate unique filename
$extension = pathinfo($_FILES['profileImage']['name'], PATHINFO_EXTENSION);
$filename = 'teacher_' . $_SESSION['teacher_id'] . '_' . time() . '.' . $extension;
$targetPath = $uploadDir . $filename;
// Move uploaded file
if (move_uploaded_file($_FILES['profileImage']['tmp_name'], $targetPath)) {
// Update database with image path
$stmt = $conn->prepare("UPDATE teachers SET profile_image = ? WHERE id = ?");
$stmt->bind_param("si", $targetPath, $_SESSION['teacher_id']);
if ($stmt->execute()) {
echo json_encode(['success' => true, 'imagePath' => $targetPath]);
} else {
unlink($targetPath); // Delete the uploaded file if DB update fails
echo json_encode(['success' => false, 'error' => $conn->error]);
}
} else {
echo json_encode(['success' => false, 'error' => 'Failed to upload image']);
}
$conn->close();
?>