Home > front end >  Uploaded File Type Verification
Uploaded File Type Verification

Time:04-12

function uploadFile() {
  var file = _("file1").files[0];
  //alert(file.name " | " file.size " | " file.type);
  var formdata = new FormData();
  formdata.append("file1", file);
  var ajax = new XMLHttpRequest();
  ajax.upload.addEventListener("progress", progressHandler, false);
  ajax.addEventListener("load", completeHandler, false);
  ajax.addEventListener("error", errorHandler, false);
  ajax.addEventListener("abort", abortHandler, false);
  ajax.open("POST", "upload_file_for_booking.php");
  ajax.send(formdata);
  
}

function progressHandler(event) {
  _("loaded_n_total").innerHTML = " Yüklendi "   event.loaded   " bytes'tan "   event.total;
  var percent = (event.loaded / event.total) * 100;
  _("progressBar").value = Math.round(percent);
  _("status").innerHTML = Math.round(percent)   "% Yüklendi ... Lütfen Bekleyin";
}

function completeHandler(event) {
  _("status").innerHTML = event.target.responseText;
  _("progressBar").value = 0;
  $("#rez-but").removeAttr("style")
}

function errorHandler(event) {
  _("status").innerHTML = "Yükleme Başarısız";
}

function abortHandler(event) {
  _("status").innerHTML = "Yükleme Durduruldu";
}

<?php 
$localhost = "localhost"; #localhost
$dbusername = "mydb"; #username of phpmyadmin
$dbpassword = "mydbpass";  #password of phpmyadmin
$dbname = "mydbname";  #database name

$conn = mysqli_connect($localhost,$dbusername,$dbpassword,$dbname);

$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 "Hata : Lütfen bir dosya seçiniz";
    exit();
}

if(move_uploaded_file($fileTmpLoc, "upload/$fileName")){
    $sql = "INSERT INTO `uploads` (`id`,`file_name`,`upload_time`) VALUES (NULL,'$fileName',NOW())";
    mysqli_query($conn,$sql) ;
    echo "$fileName Yükleme Tamamlandı.";
    $class = 'show';
} else {
    echo "Hata Oluştu";
    $class = 'hidden';
}
?>

I am trying to make only pdf files uploadable in the code block that I have forwarded above, but I have not succeeded. Is there anyone who can help?

I am using ajax button for upload.

What should I do so that only pdf files are uploadable?

Should I solve this on the ajax side or the php side?

CodePudding user response:

Add a mime-type check via mime_content_type function:

// ....
if (!$fileTmpLoc) { // if file not chosen
    echo "Hata : Lütfen bir dosya seçiniz";
    exit();
}
elseif( mime_content_type( $fileTmpLoc ) != 'application/pdf' ){
    // non-pdf file error message here
}
// ...
  • Related