Hello Everyone! welcome back to the new tutorial of Tutoid “PHP File Upload”. Today I will show you how to upload files to the server using PHP. It is very simple and I hope you will like it. In this file uploads, first the file chosen goes to ‘tmp’ directory of web server and using command “move_uploaded_file()” we move the file to our desired location.

So first lets start with index.php. here is my style CSS.

<style>
* {font-family: Consolas;}
form {
width: 300px;
padding: 20px;
background: white;
margin: 200px auto;
border-radius:10px;
color: #727272;
}
form input {
width: 100%;
padding:5px;
font-size:20px;
margin-bottom: 10px;
}
form input[type=&quot;submit&quot;] {
color: white;
background: #ff4081;
border:0;
border-radius: 10px;

}
body {
background: #303f9f;

}
</style>

now here is the html form to upload files.

<body>
<form method="POST" enctype="multipart/form-data">
<h1>Upload File</h1>
<input type="file" name="file" required>
<input type="submit" value="Upload!">
</form>
</body>

Enctype attribute is important here. As The enctype attribute specifies how the form-data should be encoded when submitting it to the server. Here multipart/form-data refers “No characters are encoded. This value is required when you are using forms that have a file upload control”. For More Info Visit this website.

The php script is here. Here using if/elseif/else I have checked the file type and extension. I have not allowed php and exe files, you can set more according to your needs.

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$filename = uniquid(rand()).$_FILES['file']['name'];
$folder = 'uploads/';
$path = $folder.$filename;
if(strpos($filename,'.php') == true){
echo "Stop Right there :3";
}
elseif(strpos($filename,'.exe')){
echo "Stop Right there :3";
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'],$path)){
echo "File Uploaded Successfully! :)";
}else {
echo 'File Upload Failed :/';
};
};
};
?>

Well this was for all today….seems simple right? eh.

So if you have any suggestions/complaints just leave in the comments. Do visit my YouTube channel and subscribe too.

Download a Sample Project.

Watch a video tutorial here.

 

Advertisements