Last active
February 26, 2018 20:28
-
-
Save petk/ed6e41c68840bd11848c57b3dbc2077b to your computer and use it in GitHub Desktop.
Uploading a file with PHP https://php.earth/docs/security/uploading
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form method="post" enctype="multipart/form-data" action="upload.php"> | |
File: <input type="file" name="file"> | |
<input type="submit"> | |
</form> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Adjust where you want to upload a file. Best is to use non public location: | |
$uploadDir = __DIR__.'../uploads'; | |
// Be sure the upload directory is writable | |
if (!is_writable($uploadDir)) { | |
throw new \Exception('Error: The upload directory is not writable'); | |
} | |
// Check if we've uploaded a file | |
if (!empty($_FILES['file']) && $_FILES['file']['error'] == UPLOAD_ERR_OK) { | |
// Be sure we're dealing with an upload | |
if (is_uploaded_file($_FILES['file']['tmp_name']) === false) { | |
throw new \Exception('Error on upload: Invalid file definition'); | |
} | |
// Rename the uploaded file | |
$uploadName = $_FILES['file']['name']; | |
$ext = strtolower(substr($uploadName, strripos($uploadName, '.')+1)); | |
$filename = round(microtime(true)).mt_rand().'.'.$ext; | |
move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir.'/'.$filename); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment