Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <html>
- <body>
- <form action="index.php" method="post" enctype="multipart/form-data">
- Select image to upload:
- <input type="file" name="upload" id="upload">
- <input type="submit" value="Upload Image" name="submit">
- </form>
- </body>
- </html>
- <?php
- try {
- //Settings
- $target_dir = "uploads/";
- $mimes = array("jpg", "png", "jpeg", "gif");
- //Generated variables
- $file = $_FILES["upload"];
- $file_name = basename($file["name"]);
- $target_file = $target_dir . $file_name;
- if(isset($_POST["submit"])) {
- $check = getimagesize($file["tmp_name"]);
- $extension = pathinfo($target_file, PATHINFO_EXTENSION);
- if($check === false)
- throw new Exception('FILE_NOT_IMAGE');
- // Check if file already exists
- if(file_exists($target_file))
- throw new Exception('FILE_EXIST');
- // Check file size
- if($file["size"] > 5 * 1024 * 1024)
- throw new Exception('FILE_LARGE');
- // Allow certain file formats
- if(!in_array($extension, $mimes))
- throw new Exception('FILE_EXTENSION_NOT_ALLOWED');
- // Check if $uploadOk is set to 0 by an error
- if (move_uploaded_file($file["tmp_name"], $target_file))
- echo "The file ". $file_name . " has been uploaded.";
- else
- throw new Exception('FILE_ERROR');
- }
- } catch (Exception $e) {
- if($e->getMessage() == 'FILE_NOT_IMAGE')
- echo "Error: File is not a image.";
- else if($e->getMessage() == 'FILE_EXIST')
- echo "Error: File already exist.";
- else if($e->getMessage() == 'FILE_EXTENSION_NOT_ALLOWED')
- echo "Error: File extension not allowed.";
- else
- echo "Epic Fail!";
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment