user3293611
user3293611

Reputation: 11

Restricting uploads to PDFs and MS Word files

I'm making a file uploader using PHP and want to restrict it to PDFs and Microsoft Word files. However, it's currently allowing uploads from all file types to the database. How can I restrict it to only allowing PDFs and Microsoft Word files?

Here is my code:

<?php

# Check if a file has been uploaded
if (isset($_FILES['uploaded_file']))

# Make sure the file was sent without errors
    if ($_FILES['uploaded_file']['error'] == 0) {
        # Connect to the database
        $dbLink = mysql_connect("localhost", "root") or die(mysql_error());
        mysql_select_db("webproject", $dbLink) or die(mysql_error());

        /* if(mysql_connect()) {
          die("MySQL connection failed: ". mysql_error());
          } */

        # Gather all required data
        $filename = mysql_real_escape_string($_FILES['uploaded_file']['name']);
        $filemime = mysql_real_escape_string($_FILES['uploaded_file']['type'] == "application/pdf" || $_FILES["uploaded_file"]["type"] == "application/msword");
        $size = $_FILES['uploaded_file']['size'];
        $data = mysql_real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
        $subjects = $_POST['subjects'];
        $name = $_POST['name'];
        $phone = $_POST['phone'];
        $email = $_POST['email'];

        # Create the SQL query
        $query = "
                INSERT INTO file(
                    Filename, Filemime, Filesize, Filedata, subjects, name, email, phone, Created
                )
                VALUES (
                    '{$filename}', '{$filemime}', {$size}, '{$data}', '{$subjects}','{$name}','{$email}','{$phone}', NOW()
                )";

        # Execute the query
        $result = mysql_query($query, $dbLink);

        # Check if it was successfull
        if ($result) {
            echo "Success! Your file was successfully added!";
        } else {
            echo "Error! Failed to insert the file";
            echo "<pre>" . mysql_error($dbLink) . "</pre>";
        }
    } else {
        echo "Error!
                    An error accured while the file was being uploaded.
                    Error code: " . $_FILES['uploaded_file']['error'];
    }

# Close the mysql connection
mysql_close($dbLink);


# Echo a link back to the mail page

echo "<p><a href='index.html'>Click here to go back home page!.</a></p>";
?>

Upvotes: 0

Views: 1375

Answers (2)

andrew
andrew

Reputation: 9583

Here is a extract from a function I sometimes use:

 function CheckFile ($file){

      $mimeTypes = array(
                    "application/pdf",
                    "application/msword",
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                    "application/excel",
                    "application/vnd.ms-excel",
                    "application/x-excel",
                    "application/x-msexcel",
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                $fileExtensions = array("pdf", "doc", "docx", "xls", "xlsx");
                if (in_array($file['type'], $mimeTypes) &&
                        in_array(end(explode(".", $file["name"])), $fileExtensions)) {
                    return true;
                }

 }

Call it with CheckFile($_FILES['uploaded_file']) It will return true if the doc is a pdf word or excel file

Edit:

One way to use it would be like so:

 if (!CheckFile($_FILES['uploaded_file'])){
     ?>
            <p>Sorry, your file was not of the correct type</p>
      <?php
     exit();
 }

Upvotes: 1

CodeBird
CodeBird

Reputation: 3858

I am not sure how your code actually works, but if you replace your second if at the top by this, the program will run only if the type is pdf or word, other files will cause this error: "Error! An error accured while the file was being uploaded. Error code: ". $_FILES['uploaded_file']['error'];" to occur

 if($_FILES['uploaded_file']['error'] == 0 && ($_FILES['uploaded_file']['type']=='application/pdf' || $_FILES['uploaded_file']['type']=='application/msword' || $_FILES["uploaded_file"]["type"] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'))

Your first if: if (isset($_FILES['uploaded_file'])) has no braces... that's not a very good practice.

Upvotes: 3

Related Questions