1

I am trying to upload .pdf file using form and while checking whether the file exists or not, the result is always true even if the directory doesn't have any file.

HTML Form:

<form id="contactForm" method="post" autocomplete="off" enctype="multipart/form-data">
          <input autocomplete="false" name="hidden" type="text" style="display:none;">
          <div class="row">
            <div class="col-md-12 form-group">
              <label for="name">Name</label>
              <input type="text" name="name" class="form-control form-control-lg" id="name" required autocomplete="off">
            </div>
          </div>
          <div class="row">
            <div class="col-md-12 form-group">
              <label for="email">Email</label>
              <input type="email" name="email" id="email" class="form-control form-control-lg" autocomplete="off">
            </div>
          </div>
          <div class="row">
            <div class="col-md-12 form-group">
              <label for="email">Phone</label>
              <input type="number" name="phone" id="phone" class="form-control form-control-lg" required autocomplete="off">
            </div>
          </div>
          <div class="row">
            <div class="col-md-12 form-group">
              <label for="address">Address</label>
              <textarea name="address" id="address" class="form-control form-control-lg" cols="30" rows="8" autocomplete="off"></textarea>
            </div>
          </div>
          <div class="row">
            <div class="col-md-12 form-group">
              <label for="department">Department</label>
              <select class="form-control form-control-lg" name="department" required autocomplete="off">
                <option value="so">Select Department</option>
                <option value="Accounts">Accounts</option>
                <option value="Machine Handling">Machine Handling</option>
                <option value="Marketing">Marketing</option>
                <option value="Sales Development">Sales Development</option>
                <option value="Floor Manager">Floor Manager</option>
                <option value="After Sales Service Manager">After Sales Service Manager</option>
              </select>
            </div>
          </div>
          <div class="row">
            <div class="col-md-12 form-group">
              <label for="file">Upload Your Resume (.pdf only!)</label>
              <input type="file" name="fileToUpload" required autocomplete="off" class="form-control" accept="application/pdf">
            </div>
          </div>
          <div class="row">
            <div class="col-md-6 form-group">
              <input type="submit" name="submit" value="Send Message" class="btn btn-primary btn-lg btn-block">
            </div>
          </div>
        </form>

FORM SUBMISSION SCRIPT:

<script>
$("#contactForm").submit(function(e){
  e.preventDefault();
  var form_data = $(this).serialize();
  $('input[type="submit"]').val("Sending Message...");
  $.ajax({
    type: "POST",
    url: "backend/career.php",
    dataType: "json",
    data: form_data
  }).done(function (data){
    console.log(data);
    $('input[type="submit"]').removeClass('btn-primary');
    $('input[type="submit"]').addClass('btn-success');
    $('input[type="submit"]').val("Message Sent...");
    $("#contactForm").closest('form').find("input[type='text'],input[type='number'],input[type='email'],input[type='file'], textarea, select").val("");
  }).fail(function(data){
    console.log(data);
    $('input[type="submit"]').removeClass('btn-primary');
    $('input[type="submit"]').addClass('btn-danger');
    $('input[type="submit"]').val("Sending Failed...");
    $("#contactForm").closest('form').find("input[type='text'],input[type='number'],input[type='email'],input[type='file'], textarea, select").val("");
  });
});
  </script>

PHP Code:

$target_dir = "../pdf/";
$target_file = $target_dir.basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$pdfFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}
if ($_FILES["fileToUpload"]["name"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}
if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}

The output:

Sorry, file already exists.Sorry, your file was not uploaded.

This is the output even if the there doesn't exist any file in that directory.

How to solve this?

Avinash Goen
  • 49
  • 1
  • 11
  • `$_FILES["fileToUpload"]["name"]` is a simple name, I suppose `basename` is useless here. – u_mulder May 30 '18 at 12:01
  • A side note: you _don't_ want to store the uploaded file under the name specified by the client side. That is a security issue. you use a generated name for the physical file and only store the specified name in a database, if you need it later. – arkascha May 30 '18 at 12:02
  • try:- `$target_file = $target_dir.$_FILES["fileToUpload"]["name"];` – Alive to die - Anant May 30 '18 at 12:02
  • Not working. Still showing the same error @AlivetoDie – Avinash Goen May 30 '18 at 12:10
  • @arkascha, I am uploading the file onto my server directory. I don't want to save it to my database. – Avinash Goen May 30 '18 at 12:12
  • What happens if you `var_dump(basename($_FILES["fileToUpload"]["name"]));`? Could it be that that's empty or invalid? – OK sure May 30 '18 at 12:13
  • Have you done the test multiple times with the same file? results can be put in a cache as stated in the docs [here](http://php.net/manual/en/function.file-exists.php#refsect1-function.file-exists-notes) and more detailled [here](http://php.net/manual/en/function.clearstatcache.php). Just an idea.. – Kaddath May 30 '18 at 12:16
  • @Kaddath I am working on Incognito window and there's no chance of cache being stored – Avinash Goen May 30 '18 at 12:27
  • @OKsure The output is: string(0) – Avinash Goen May 30 '18 at 12:33
  • @AvinashGoen and `var_dump($target_file);` is `/pdf/0`? – OK sure May 30 '18 at 12:35
  • @OKsure The output is string(30) "/home/aadhunik/public_html/pdf – Avinash Goen May 30 '18 at 12:39
  • Error_log says Undefined Index fileToUpload How should i solve this problem? – Avinash Goen May 30 '18 at 12:43
  • Your $_FILES var is empty so it would be. Can you include your form code - specifically the upload/file input. – OK sure May 30 '18 at 13:10
  • I said nothing against storing the file in the file system. I said you should not _name it_ as specified by the client because that is a security issue. You store the name in the database, not the file. – arkascha May 30 '18 at 14:26

3 Answers3

0

Try this instead, use an absolute path with file_exists

$target_dir = realpath('../pdf');
Hugo
  • 9
  • 4
0

If var_dump($target_file); is returning /home/aadhunik/public_html/pdf, file_exists is checking if that /pdf/ directory exists, which it does.

The problem seems to be that $_FILES["fileToUpload"]["name"] is not set.

I would start debugging by inspecting $_FILES using var_dump($_FILES); - find out where that filename actually is.

There could be many reasons for this - but it's not a problem with file_exists

If $_FILES is empty, check that the form has enctype="multipart/form-data" and that file uploads are permitted on the server (in php.ini, you should have file_uploads=1. If it's not empty, adjust your code to use the correct data, e.g. $_FILES['some_file']['name']

Update:

You can't upload files with ajax in this way. Use the new HTML5 FormData object instead of JQuery serialization. See this link for more info: How can I upload files asynchronously?

Bear in mind that this is only supported on newer browsers. Some suggest using iFrames or one of the many libraries available for this. jQuery Ajax File Upload

Something like this:

<script>
  $("#contactForm").submit(function(e){
    e.preventDefault();
    $('input[type="submit"]').val("Sending Message...");
    $.ajax({
      type: "POST",
      url: "backend/career.php",
      data: new FormData($(this)[0]),
      cache: false,
      contentType: false,
      processData: false
    }).done(function (data){
      console.log(data);
      $('input[type="submit"]').removeClass('btn-primary');
      $('input[type="submit"]').addClass('btn-success');
      $('input[type="submit"]').val("Message Sent...");
      $("#contactForm").closest('form').find("input[type='text'],input[type='number'],input[type='email'],input[type='file'], textarea, select").val("");
    }).fail(function(data){
      console.log(data);
      $('input[type="submit"]').removeClass('btn-primary');
      $('input[type="submit"]').addClass('btn-danger');
      $('input[type="submit"]').val("Sending Failed...");
      $("#contactForm").closest('form').find("input[type='text'],input[type='number'],input[type='email'],input[type='file'], textarea, select").val("");
    });
  });
</script>
OK sure
  • 2,617
  • 16
  • 29
0
data: new FormData($(this).get(0))

This is the editing which I had to do on ajax code to upload the file.

if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_dir.$target_file)) {

This is the change I had to make in PHP Code

Avinash Goen
  • 49
  • 1
  • 11