Skip to content

Instantly share code, notes, and snippets.

@dmgig
Created April 3, 2016 19:36
Show Gist options
  • Save dmgig/0d803525e50a7d85e8deb6cda967fefe to your computer and use it in GitHub Desktop.
Save dmgig/0d803525e50a7d85e8deb6cda967fefe to your computer and use it in GitHub Desktop.
Obscenely Simple PHP File Upload
<?php
define("UPLOAD_DIR", "./");
ini_set("upload_max_filesize", "200M");
ini_set("post_max_size", "200M");
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file. ".$_FILES['myFile']['error']."</p>";
exit;
}else{
echo "Upload Successful! ".$name;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
?>
<form action="/simple-upload/index.php" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<br>
<input id="submit" type="submit" value="Upload">
<div id="loading" style="display:none">
Uploading!!! Please wait.
</div>
</form>
<script>
document.getElementById("submit").onclick = function(){
document.getElementById("loading").style.display = "block";
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment