Click here to Skip to main content
15,889,315 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a php script that uploads a file to the server. Currently only jpg images are allowed. How can I allow more file types to be uploaded such as mp3's, WAV, and GIF?

Code Below:


PHP
<?php
//Сheck that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
  //Check if the file is JPEG image and it's size is less than 350Kb
  $filename = basename($_FILES['uploaded_file']['name']);
  $ext = substr($filename, strrpos($filename, '.') + 1);
  if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") &&
    ($_FILES["uploaded_file"]["size"] < 35000000)) {
    //Determine the path to which we want to save this file
      $newname = dirname(__FILE__).'/files/'.$filename;
      //Check if the file with the same name is already exists on the server
      if (!file_exists($newname)) {
        //Attempt to move the uploaded file to it's new place
        if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) {
           echo "It's done! The file has been saved as: ".$newname;



Any help is greatly appreciated.. Thanks in advance.
Posted

1 solution

I would create a new function to check the type:
function check_file_type($ext, $mime)
{
  $allowed_types = array(
    'jpg' => 'image/jpeg',
    // add other types here
  );
  $ext = strtolower($ext);
  return (array_key_exists($ext, $allowed_types) && $allowed_types[$ext] == $mime);
}


then replace the line:
if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") &&


with
if (check_file_type($ext, $_FILES["uploaded_file"]["type"]) &&
 
Share this answer
 
Comments
MicahC 30-Jun-10 23:24pm    
This is fantastic.. Works like a charm, I had looked into making an array, but just was not sure on how to implement it! Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900