0

I have created a upload file form. It's working fine but i am not able to check whether files exists or not. if it does then it should be renamed automatically.

HTML CODE :-

<form id="upload_form" enctype="multipart/form-data" method="post">
    <input type="file" name="file1" id="file1"><br>
    <input type="button" value="Upload File" onclick="uploadFile()">
    <progress id="progressBar" value="0" max="100" style="width:300px;"></progress><br><br>
  Below is the direct link to file :-
  <h3 id="status"></h3>
  <p id="loaded_n_total"></p>
</form>

PHP CODE :-

<?php
    $fileName = $_FILES["file1"]["name"]; // The file name
    $fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
    $fileType = $_FILES["file1"]["type"]; // The type of file it is
    $fileSize = $_FILES["file1"]["size"]; // File size in bytes
    $fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
    if (!$fileTmpLoc) { // if file not chosen
        echo "ERROR: Please browse for a file before clicking the upload button.";
        exit();

    }

    if(move_uploaded_file($fileTmpLoc, "upload/$fileName")){
        echo "$fileName uploaded";
    } else {
        echo "move_uploaded_file function failed";
    }
?>
Ben
  • 8,894
  • 7
  • 44
  • 80
  • 1
    Have you tried something? There's plenty of ways to do this, show us what you've tried :) – Epodax Aug 11 '15 at 08:02
  • possible duplicate of [check if file exists in php](http://stackoverflow.com/questions/4253487/check-if-file-exists-in-php) –  Aug 11 '15 at 08:14

2 Answers2

0

check this one, I used file_exists() function

<?php

$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
    echo "ERROR: Please browse for a file before clicking the upload button.";
    exit();
}

$fileReadyForUpload = "upload/" . $fileName;
if (file_exists($fileReadyForUpload)) {
    $fileName = time() . "_" . $fileName;
} else {
    $fileName = $fileName;
}
if (move_uploaded_file($fileTmpLoc, "upload/$fileName")) {
    echo "$fileName uploaded";
} else {
    echo "move_uploaded_file function failed";
}
?>
Gayan
  • 2,845
  • 7
  • 33
  • 60
0

You have to check if the $_FILES["file1"] Variable is set.

For example:

$file = (isset($_FILES["file1"]) ? $_FILES["file1"] : 0);

if(!file) { die("ERROR: Please browse for a file before clicking the upload button."); }
DevTec
  • 307
  • 3
  • 14