Skip to content

Instantly share code, notes, and snippets.

@oleteacher
Created January 28, 2018 22:36
Show Gist options
  • Save oleteacher/09685fb5c1047e8c477bcef1b72ca4ab to your computer and use it in GitHub Desktop.
Save oleteacher/09685fb5c1047e8c477bcef1b72ca4ab to your computer and use it in GitHub Desktop.
Upload and Rename File Simple Version
<form action="" enctype="multipart/form-data" method="post">
<input id="file" name="file" type="file" />
<input id="Submit" name="submit" type="submit" value="Submit" />
</form>
<?php
// Upload and Rename File
if (isset($_POST['submit']))
{
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // This returns file name
$file_ext = substr($filename, strripos($filename, '.')); // This returns file extension
$filesize = $_FILES["file"]["size"];
$allowed_file_types = array('.doc','.docx','.rtf','.pdf');
if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000))
{
// Rename file
$newfilename = md5($file_basename) . $file_ext;
if (file_exists("upload/" . $newfilename))
{
// file already exists error
echo "You have already uploaded this file.";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $newfilename);
echo "File uploaded successfully.";
}
}
elseif (empty($file_basename))
{
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 200000)
{
// file size error
echo "The file you are trying to upload is too large.";
}
else
{
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment