If you allow you users to upload files to your web server you will probably want to create some restrictions. You can block uploads based off of file size, extension, or if a filename already exists.
Prerequisites:
- Basic LAMP, or Web Server Administration
- Verify folder has WRITE permission for OTHER
- Basic PHP
- Basic HTML
in_array()
- https://www.php.net/manual/en/function.in-array.php
- https://www.w3schools.com/php/func_array_in_array.asp
file_exists()
- https://www.php.net/manual/en/function.file-exists.php
- https://www.w3schools.com/pHP/func_filesystem_file_exists.asp
pathinfo()
- https://www.php.net/manual/en/function.pathinfo.php
- https://www.w3schools.com/php/func_filesystem_pathinfo.asp
basename()
- https://www.php.net/manual/en/function.basename.php
- https://www.w3schools.com/php/func_filesystem_basename.asp
move_file_upload()
- https://www.php.net/manual/en/function.move-uploaded-file.php
- https://www.w3schools.com/php/func_filesystem_move_uploaded_file.asp
$_FILE
- https://www.php.net/manual/en/reserved.variables.files.php
- https://www.w3schools.com/php/php_file_upload.asp
LAMP Server
- Create a “pics” directory in the Public Web Directory (/var/www/html)
- Verify folder has at least a w– permission.
PHP.ini
- Location on demo system: /etc/php/7.2/apache2/php.ini
- Set File Uploads to: file_uploads = On
- Modify Max File size if needed: upload_max_filesize =2M
fileUpload.php
<?php
$dir = "./folder/";
$filename = $dir.basename($_FILES['Upload']['name']);
$filenameArray = pathinfo($filename);
$ext = array("jpeg","jpg","gif");
$isGood = 0;
if (file_exists($filename)) {
echo "The file already exists<br>";
$isGood = 1;
}
if ($_FILES['Upload']['size'] > 50000) {
echo "File is over 50kB in size<br>";
$isGood = 1;
}
if (!in_array($filenameArray['extension'],$ext)) {
echo "File Type is not Allowed (Upload jpeg, jpg,gif)<br>";
$isGood = 1;
}
if ($isGood != 1) {
if (move_uploaded_file($_FILES['Upload']['tmp_name'], $filename)){
echo "<p>File was uploaded --> ".$_FILES['Upload']['name'];
} else {
echo "Upload failed".$_FILES['Upload']['name'];
}
}
?>
<br>
<a href="./fileUpload.html">Back</a>
fileUpload.html
<html>
<head></head>
<body>
<h1>File Upload Form</h1>
<form action="fileUpload.php" method="post" enctype="multipart/form-data">
<input type="file" name="Upload">
<input type="submit">
</form>
</body>
</html>
Be the first to comment