Advertisement
emmanuelbarrameda

Untitled

Nov 21st, 2024
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. <?php
  2. // db connection
  3. $host = 'localhost';
  4. $db = 'deanslister_db';
  5. $user = 'root';
  6. $pass = '';
  7.  
  8. $conn = new mysqli($host, $user, $pass, $db);
  9.  
  10. if ($conn->connect_error) {
  11. die("Database connection failed: " . $conn->connect_error);
  12. }
  13.  
  14. // to store uploaded files
  15. $uploadDir = 'uploads/';
  16. if (!is_dir($uploadDir)) {
  17. mkdir($uploadDir, 0777, true);
  18. }
  19.  
  20. // fields & db column mapping
  21. $fileFields = [
  22. 'COR' => 'cor_path',
  23. 'COG' => 'cog_path',
  24. 'FORM' => 'applicationform_path',
  25. 'QPA' => 'qpa_path',
  26. ];
  27.  
  28. // file size limit (5MB)
  29. $fileSizeLimit = 5 * 1024 * 1024;
  30.  
  31. $uploadedPaths = [];
  32.  
  33. try {
  34. foreach ($fileFields as $field => $column) {
  35. if (isset($_FILES[$field]) && $_FILES[$field]['error'] === UPLOAD_ERR_OK) {
  36. $fileTmpPath = $_FILES[$field]['tmp_name'];
  37. $fileName = $_FILES[$field]['name'];
  38. $fileSize = $_FILES[$field]['size'];
  39. $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
  40.  
  41. // check file size
  42. if ($fileSize > $fileSizeLimit) {
  43. throw new Exception("File size for $field exceeds the limit of 5MB.");
  44. }
  45.  
  46. // valid file types
  47. $allowedExtensions = ['jpg', 'jpeg', 'png', 'pdf', 'xlsx'];
  48. if (!in_array(strtolower($fileExt), $allowedExtensions)) {
  49. throw new Exception("Invalid file type for $field. Allowed types: " . implode(', ', $allowedExtensions));
  50. }
  51.  
  52. // generate unique file name
  53. $newFileName = $field . '_' . time() . '.' . $fileExt;
  54. $destPath = $uploadDir . $newFileName;
  55.  
  56. if (move_uploaded_file($fileTmpPath, $destPath)) {
  57. $uploadedPaths[$column] = $destPath;
  58. } else {
  59. throw new Exception("Error uploading $field.");
  60. }
  61. } else {
  62. throw new Exception("File $field is missing or failed to upload.");
  63. }
  64. }
  65.  
  66. // sql prepare & execute
  67. $stmt = $conn->prepare("
  68. INSERT INTO deanslister_tbl (cor_path, cog_path, applicationform_path, qpa_path)
  69. VALUES (?, ?, ?, ?)
  70. ");
  71. $stmt->bind_param(
  72. "ssss",
  73. $uploadedPaths['cor_path'],
  74. $uploadedPaths['cog_path'],
  75. $uploadedPaths['applicationform_path'],
  76. $uploadedPaths['qpa_path']
  77. );
  78.  
  79. if ($stmt->execute()) {
  80. echo "Files uploaded and saved successfully!";
  81. } else {
  82. throw new Exception("Database error: " . $stmt->error);
  83. }
  84.  
  85. $stmt->close();
  86. } catch (Exception $e) {
  87. echo "Error: " . $e->getMessage();
  88. }
  89.  
  90. $conn->close();
  91. ?>
  92.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement