"OdenseTrack" is a school assignment/project from AspIT https://aspit.dfine.net/odensetrack
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

upload.class.php 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /*
  3. * Handles all uploads
  4. */
  5. class Upload {
  6. public function __construct() {
  7. }
  8. public static function generateRandomString($length = 5) {
  9. // Function to generate a random string of 5 chars.
  10. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // Chars to use
  11. $charactersLength = strlen($characters); // Check string length
  12. $randomString = ''; // An empty var to store our randomstring
  13. for ($i = 0; $i < $length; $i++) {
  14. // Here we loop until we filled our string with the wanted length.
  15. $randomString .= $characters[rand(0, $charactersLength - 1)];
  16. }
  17. return $randomString; // Returns our randomstring.
  18. }
  19. public static function handleUpload($file = false) {
  20. $cwd = getcwd(); // Our websites CWD (Current working dir)
  21. $filename = $file['name']; // Get filename
  22. $size = $file['size']; // Gets filesize
  23. $tempname = $file['tmp_name']; // Where did php upload our data to?
  24. $type = $file['type']; // Unused in current state.
  25. $ext = explode('.', $file['name']); // end() doesnt like us using explode directly.
  26. $extension = strtolower(end($ext)); // Get the extension of the file.
  27. $randomname = Upload::generateRandomString(); // We give our file a random name - It will be this.
  28. // If filename exists, we roll a new one.
  29. while (IS_FILE($cwd .'/'. Config::$file_path . $randomname . '.' . $extension)) {
  30. $randomname = Upload::generateRandomString();
  31. }
  32. // We got our unique filename, lets continue.
  33. $uploadPath = $cwd .'/'. Config::$file_path . $randomname . '.' . $extension;
  34. if (!in_array($extension, Config::$file_types)) {
  35. // Error! This file does not have an acceptable filetype
  36. return false; // Return false when upload fails.
  37. }
  38. if ($size > Config::$file_size) {
  39. // Filesize is configured in config, defined in bytes.
  40. return false; // Return false when upload fails.
  41. }
  42. if (empty($errors)) {
  43. // Do fileupload
  44. // move_uploaded_file is self-explanatory. We move the file into the correct path.
  45. $makeUpload = move_uploaded_file($tempname, $uploadPath);
  46. if (!$makeUpload) {
  47. return false; // Return false when upload fails.
  48. } else {
  49. // Add information to the database.
  50. Alter::insertImage($randomname . '.' . $extension, $type);
  51. // Return where the image was uploaded to.
  52. return Config::$sys_url.Config::$file_path.$randomname.'.'.$extension;
  53. }
  54. }
  55. }
  56. }