php中的Doc和PDF文件限制

问题描述:

I am trying to restrict jpg files being uploaded but it is not working. This is my code for uploading.

<?php
include "admin/includes/connect.php";


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

 $file = rand(1000,100000)."-".$_FILES['file']['name'];
    $file_loc = $_FILES['file']['tmp_name'];
 $file_size = $_FILES['file']['size'];
 $file_type = $_FILES['file']['type'];
  $name = $_POST['name'];

     $email = $_POST['email'];

     $allowedExts = array("pdf", "doc");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if (($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/doc")
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }}




 $folder="uploads/"; 

 move_uploaded_file($file_loc,$folder.$file);

 $sql="INSERT INTO upload(name,email,file,type,size) VALUES('$name','$email','$file','$file_type','$file_size')";
  mysqli_query($conn, $sql);

}
?>

in local(php.ini)
Change this

file_uploads = On

Then HTML Form should be like this

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select files to upload:
    <input type="file" name="UploadFile" id="UploadFile">
    <input type="submit" value="Upload File" name="submit">
</form>

Then in upload.php

<?php
    $path_to_move = "../uploads/pdf";//give your folder name
    $file = $path_to_move . basename($_FILES["UploadFile"]["name"]);
    $status = 1;
    $FileType = pathinfo($file,PATHINFO_EXTENSION);

    // Check the uploaded file size
    if ($_FILES["UploadFile"]["size"] > 500000)//500000 = 500kb
    {
        echo "File is too large.";//error message
        $status = 0;//Change this to
    }

    // Validate file Format
    if($FileType != "pdf" && $FileType != "doc" && $FileType != "docx")
    {
        echo "Only PDF, doc or docx file Formats are allowed.";//error message
        $status = 0;//Change this to
    }    

    // Uploading file
        if ($status == 0)
        {
            echo "Upload Failed";        
        } 
        else
        {
            if (move_uploaded_file($_FILES["UploadFile"]["tmp_name"], $path_to_move)) 
            {
                echo "File  uploaded";
            } else 
            {
                echo "Error in uploading your file. Try Again";
            }
        }
?>

Get the Idea from reading W3schools Site