I wrote this code to be able to upload a file that its <=10 MB in a folder on my server and also send its name to the database so that later I'll be able to generate the link to access that file.
My problem is that if the $fileSize its > 10MB it won't execute the move_uploaded_file but it will execute the query to the database and it will INSERT an entry with the file name (so i will have records to in-existing files). I think this happens because the $errMSG comes empty for that condition.
Can you have a look? Thank You!
require_once ('db.php');
if (array_key_exists('check_submit', $_POST)) {
$userFile = $_FILES['cv']['name'];
$tmp_dir = $_FILES['cv']['tmp_name'];
$fileSize = $_FILES['cv']['size'];
if (empty($userFile)) {
echo $errMSG = "Please Select File.";
} else {
$upload_dir = './files/'; // upload directory
$fileExt = strtolower(pathinfo($userFile, PATHINFO_EXTENSION)); // get file extension
// valid image extensions
$valid_extensions = array('doc', 'docx', 'pdf', 'ppt','pptx','txt','jpeg','jpg','png'); // valid extensions
// rename uploading image
$userFileName = rand(1000, 1000000) . "." . $fileExt;
// allow valid image file formats
if (in_array($fileExt, $valid_extensions,$fileSize <= 10000000) ){
// Check file size '10MB
move_uploaded_file($tmp_dir, $upload_dir . $userFileName);
} else {
echo $errMSG = "Sorry, your file is too large or its not JPG JPEG PNG PDF DOC DOX TXT.";
}
}
}
if(!isset($errMSG)) {
$stmt = $DB_con->prepare('INSERT INTO files (filename) VALUES(:filename)');
$stmt->bindParam(':filename',$userFileName);
if($stmt->execute())
{
$successMSG = "new record succesfully inserted ...";
header("refresh:5;index.php");
}
else
{
$errMSG = "error while inserting....";
}
}
in_array()is for strict comparison (including the variable type), it is not related in any way to file sizes or limits.