PageRenderTime 267ms CodeModel.GetById 164ms RepoModel.GetById 2ms app.codeStats 0ms

/samples/samples/php/upload.php

https://github.com/bschwartz/swfupload
PHP | 178 lines | 86 code | 22 blank | 70 comment | 30 complexity | 52ab302d77d41db3359ef4d6efb2abfb MD5 | raw file
  1. <?php
  2. /*
  3. This is an upload script for SWFUpload that attempts to properly handle uploaded files
  4. in a secure way.
  5. Notes:
  6. SWFUpload doesn't send a MIME-TYPE. In my opinion this is ok since MIME-TYPE is no better than
  7. file extension and is probably worse because it can vary from OS to OS and browser to browser (for the same file).
  8. The best thing to do is content sniff the file but this can be resource intensive, is difficult, and can still be fooled or inaccurate.
  9. Accepting uploads can never be 100% secure.
  10. You can't guarantee that SWFUpload is really the source of the upload. A malicious user
  11. will probably be uploading from a tool that sends invalid or false metadata about the file.
  12. The script should properly handle this.
  13. The script should not over-write existing files.
  14. The script should strip away invalid characters from the file name or reject the file.
  15. The script should not allow files to be saved that could then be executed on the webserver (such as .php files).
  16. To keep things simple we will use an extension whitelist for allowed file extensions. Which files should be allowed
  17. depends on your server configuration. The extension white-list is _not_ tied your SWFUpload file_types setting
  18. For better security uploaded files should be stored outside the webserver's document root. Downloaded files
  19. should be accessed via a download script that proxies from the file system to the webserver. This prevents
  20. users from executing malicious uploaded files. It also gives the developer control over the outgoing mime-type,
  21. access restrictions, etc. This, however, is outside the scope of this script.
  22. SWFUpload sends each file as a separate POST rather than several files in a single post. This is a better
  23. method in my opinions since it better handles file size limits, e.g., if post_max_size is 100 MB and I post two 60 MB files then
  24. the post would fail (2x60MB = 120MB). In SWFupload each 60 MB is posted as separate post and we stay within the limits. This
  25. also simplifies the upload script since we only have to handle a single file.
  26. The script should properly handle situations where the post was too large or the posted file is larger than
  27. our defined max. These values are not tied to your SWFUpload file_size_limit setting.
  28. */
  29. // Code for Session Cookie workaround
  30. if (isset($_POST["PHPSESSID"])) {
  31. session_id($_POST["PHPSESSID"]);
  32. } else if (isset($_GET["PHPSESSID"])) {
  33. session_id($_GET["PHPSESSID"]);
  34. }
  35. session_start();
  36. // Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
  37. $POST_MAX_SIZE = ini_get('post_max_size');
  38. $unit = strtoupper(substr($POST_MAX_SIZE, -1));
  39. $multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
  40. if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
  41. header("HTTP/1.1 500 Internal Server Error");
  42. echo "POST exceeded maximum allowed size.";
  43. exit(0);
  44. }
  45. // Settings
  46. $save_path = getcwd() . "/uploads/"; // The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
  47. $upload_name = "Filedata";
  48. $max_file_size_in_bytes = 2147483647; // 2GB in bytes
  49. $extension_whitelist = array("jpg", "gif", "png"); // Allowed file extensions
  50. $valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-'; // Characters allowed in the file name (in a Regular Expression format)
  51. // Other variables
  52. $MAX_FILENAME_LENGTH = 260;
  53. $file_name = "";
  54. $file_extension = "";
  55. $uploadErrors = array(
  56. 0=>"There is no error, the file uploaded with success",
  57. 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
  58. 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
  59. 3=>"The uploaded file was only partially uploaded",
  60. 4=>"No file was uploaded",
  61. 6=>"Missing a temporary folder"
  62. );
  63. // Validate the upload
  64. if (!isset($_FILES[$upload_name])) {
  65. HandleError("No upload found in \$_FILES for " . $upload_name);
  66. exit(0);
  67. } else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
  68. HandleError($uploadErrors[$_FILES[$upload_name]["error"]]);
  69. exit(0);
  70. } else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
  71. HandleError("Upload failed is_uploaded_file test.");
  72. exit(0);
  73. } else if (!isset($_FILES[$upload_name]['name'])) {
  74. HandleError("File has no name.");
  75. exit(0);
  76. }
  77. // Validate the file size (Warning: the largest files supported by this code is 2GB)
  78. $file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
  79. if (!$file_size || $file_size > $max_file_size_in_bytes) {
  80. HandleError("File exceeds the maximum allowed size");
  81. exit(0);
  82. }
  83. if ($file_size <= 0) {
  84. HandleError("File size outside allowed lower bound");
  85. exit(0);
  86. }
  87. // Validate file name (for our purposes we'll just remove invalid characters)
  88. $file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", basename($_FILES[$upload_name]['name']));
  89. if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH) {
  90. HandleError("Invalid file name");
  91. exit(0);
  92. }
  93. // Validate that we won't over-write an existing file
  94. if (file_exists($save_path . $file_name)) {
  95. HandleError("File with this name already exists");
  96. exit(0);
  97. }
  98. // Validate file extension
  99. $path_info = pathinfo($_FILES[$upload_name]['name']);
  100. $file_extension = $path_info["extension"];
  101. $is_valid_extension = false;
  102. foreach ($extension_whitelist as $extension) {
  103. if (strcasecmp($file_extension, $extension) == 0) {
  104. $is_valid_extension = true;
  105. break;
  106. }
  107. }
  108. if (!$is_valid_extension) {
  109. HandleError("Invalid file extension");
  110. exit(0);
  111. }
  112. // Validate file contents (extension and mime-type can't be trusted)
  113. /*
  114. Validating the file contents is OS and web server configuration dependant. Also, it may not be reliable.
  115. See the comments on this page: http://us2.php.net/fileinfo
  116. Also see http://72.14.253.104/search?q=cache:3YGZfcnKDrYJ:www.scanit.be/uploads/php-file-upload.pdf+php+file+command&hl=en&ct=clnk&cd=8&gl=us&client=firefox-a
  117. which describes how a PHP script can be embedded within a GIF image file.
  118. Therefore, no sample code will be provided here. Research the issue, decide how much security is
  119. needed, and implement a solution that meets the needs.
  120. */
  121. // Process the file
  122. /*
  123. At this point we are ready to process the valid file. This sample code shows how to save the file. Other tasks
  124. could be done such as creating an entry in a database or generating a thumbnail.
  125. Depending on your server OS and needs you may need to set the Security Permissions on the file after it has
  126. been saved.
  127. */
  128. if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
  129. HandleError("File could not be saved.");
  130. exit(0);
  131. }
  132. // Return output to the browser (only supported by SWFUpload for Flash Player 9)
  133. echo "File Received";
  134. exit(0);
  135. /* Handles the error output. This function was written for SWFUpload for Flash Player 8 which
  136. cannot return data to the server, so it just returns a 500 error. For Flash Player 9 you will
  137. want to change this to return the server data you want to indicate an error and then use SWFUpload's
  138. uploadSuccess to check the server_data for your error indicator. */
  139. function HandleError($message) {
  140. header("HTTP/1.1 500 Internal Server Error");
  141. echo $message;
  142. }
  143. ?>