Daniel Daniel - 1 year ago 69
MySQL Question

Upload files using PHP and MySQL

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

its > 10MB it won't execute the
but it will execute the query to the database and it will
an entry with the file name (so i will have records to in-existing files). I think this happens because the
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)');
$successMSG = "new record succesfully inserted ...";
$errMSG = "error while inserting....";

Answer Source

The 3rd parameter for in_array() is for strict comparison (including the variable type), it is not related in any way to file sizes or limits.

So instead of this:

if (in_array($fileExt, $valid_extensions,$fileSize <= 10000000) ){

You probably want something like this:

if (in_array($fileExt, $valid_extensions) && $fileSize <= 10000000) {

Edit: Based on the comments below the question, your upload has failed: [error] => 2. That should be 0 / UPLOAD_ERR_OK for a successful upload.

Instead of checking for a non-empty name, you should check for a successful upload instead:

if ($_FILES['cv']['error'] !== UPLOAD_ERR_OK) {
    // the upload has failed
} else {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download