File upload along with data and apply proper validation in PHP
File : <form method="post" action="save-file.php" enctype="multipart/form-data">
<input name="file" type="file" />
<input name="submit" type="submit" />
</form>
save-file.php
if(isset($_POST['submit'])){
if((isset($_FILES['file']['name'])){
$errors = array();
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_type = $_FILES['file']['type'];
$ext = explode('.', $file_name);
$file_ext = end($ext);
$extensions = array('pptx', 'PPTX','pdf', 'PDF', 'ppt', 'PPT', 'docx', 'DOCX');
if(in_array($file_ext, $extensions) === FALSE){
$errors[] = "This extension file is not allowed, Please choose a .pptx or .pdf file";
}
if($file_size > 1024000){
$errors[] = "File size must be less than 1 MB";
}
$new_name = time().'--'.basename($file_name);
$name_current = "upload/".$new_name;
$target = $name_current;
if(empty($errors) == TRUE){
$sql = "INSERT INTO files (file) VALUES (?,)";
$result = $conn->prepare($sql);
if($result->execute(array($new_name))){
move_uploaded_file($file_tmp, $target);
echo 'File uploaded successfully';
}else{
$msg = 'Due to some technical issue, file cannot be upload. Contact developer';
}
}
}else{
$msg = '';
foreach($errors as $error_msg){
$msg .= ''.$error_msg.'';
}
}
}else{
$msg = 'Fill All Fields';
}
}
Comments
Post a Comment