Skip to content

Instantly share code, notes, and snippets.

@petk
Last active February 26, 2018 20:28
Show Gist options
  • Save petk/ed6e41c68840bd11848c57b3dbc2077b to your computer and use it in GitHub Desktop.
Save petk/ed6e41c68840bd11848c57b3dbc2077b to your computer and use it in GitHub Desktop.
Uploading a file with PHP https://php.earth/docs/security/uploading
<form method="post" enctype="multipart/form-data" action="upload.php">
File: <input type="file" name="file">
<input type="submit">
</form>
<?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