0

I am trying to write a script where the system checks if the user has selected a file to upload before uploading anything. The issue I'm having is that even if I don't select a file, the system echoes that a file has been uploaded successfully. See code below:

<?php
include("dbconfig.php");

if(isset($_POST['btn-upload'])) {

    $loggedinuser = $_GET['bid'];   
    $file = $_FILES['file']['name'];
    $file_size = $_FILES['file']['size'];
    $file_type = $_FILES['file']['type'];

    $sql = mysqli_query($conn, "INSERT INTO upload (personalid, file, type, size) values ((select personalid from person where username='$loggedinuser'), '$file', '$file_type', '$file_size')") or die (mysqli_error($conn));

    if($sql){
        header("location:upload.php?msg0=Document upload successful.");     
    } elseif( !file_exists($_FILES['file']['name']) || !is_uploaded_file($_FILES['file']['name']) ) {
        header("location:upload.php?msg1=Document upload failed.");
    }
}
?>
<!-- need to comment -->

Updated Version - 16:34 (13/11/2015)

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include("dbconfig.php");
if(isset($_POST['btn-upload'])){

if (empty($_FILES['file']['name'])){

    echo 'error!';

} else {

$loggedinuser = $_GET['bid'];

$file = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$sql = mysqli_query($conn, "INSERT INTO upload (personalid, file, type, size) values ((select personalid from person where username='$loggedinuser'), '$file', '$file_type', '$file_size')") or die (mysqli_error($conn));

if($sql){
    header("location:upload.php?msg0=Document upload successful.");     
}
else {
    header("location:upload.php?msg1=Document upload failed.");
}
}
}


 ?>
<!-- need to commentt -->

I have done some research online and I've come across some discussions that mention you can us file_exists or is_uploaded_file - I'm not sure if I'm using them correctly. Please do let me know how I can check if a user has selected a file before uploading.

Thanks,

Sohail.

1 Answers1

0

Well at the moment your statement is based only if the button is pushed as POST request, which it always will be.

I am not 100% on this but I am prepared to try and answer this.

$loggedinuser = $_GET['bid'];
if (isset($_FILES['file']['name']) && !empty($_FILES['file']['name'])) {
    $file = $_FILES['file']['name'];
    $file_size = $_FILES['file']['size'];
    $file_type = $_FILES['file']['type'];
}

if (isset($file) && isset($file_size) && isset(file_type)) {    
  SQL stuff;
}

if(isset($sql) && $sql){
    header("location:upload.php?msg0=Document upload successful.");     
} else {
    header("location:upload.php?msg1=Document upload failed.");
}

On a side note, can you not just ensure the field is required in the HTML?