Jump to content

PHP5 file upload file types


baxt01

Recommended Posts

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
?> 

I have been working through the w3school tutorial on file upload but the codes are set to only use image file how do I change the file type that can be uploaded?

 

above is the section of code were the file is checked and uploaded:

 

I think its line 8 that controls the file type but I also think I am guessing

Edited by baxt01
Link to comment
Share on other sites

/* index.php */
<html>
<head>
<title>Puddins's Page</title>
<link rel="stylesheet" type="text/css" href="style.css"> 
</head>
<body background ="/puddin/files/BG_image.jpg">


<?PHP

// open this directory 
$myDirectory = opendir("./files");

// get each entry
while($entryName = readdir($myDirectory)) {
	$dirArray[] = $entryName;
}

// close directory
closedir($myDirectory);

//	count elements in array
$indexCount	= count($dirArray);
Print ("$indexCount files<br>\n");

// sort 'em
sort($dirArray);

// print 'em
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
print("<TR><TH>Filename</TH></TR>\n");
// loop through the array of files and print them all
for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
		print("<TR><TD><a href=\"/puddin/files/$dirArray[$index]\" >$dirArray[$index]</a></td>");
		
		print("</TR>\n");
	}
}
print("</TABLE>\n");

?>


<!DOCTYPE html>
<html>
<body>

<form action="./upload.php" method="post" enctype="multipart/form-data">
   <p>
      <label for="file">Select a file:</label> <input type="file" name="userfile" id="file"> <br />
      <button>Upload File</button>
   <p>
</form>

</body>
</html> 
/* upload.php file */
<?php
   // Configuration - Your Options
      $allowed_filetypes = array('.jpg','.gif','.bmp','.png','.zip'); // These will be the types of file that will pass the validation.
      $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
      $upload_path = './files/'; // The place the files will be uploaded to (currently a 'files' directory).
 
   $filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
   $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
 
   // Check if the filetype is allowed, if not DIE and inform the user.
   if(!in_array($ext,$allowed_filetypes))
      die('The file you attempted to upload is not allowed.');
 
   // Now check the filesize, if it is too large then DIE and inform the user.
   if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
      die('The file you attempted to upload is too large.');
 
   // Check if we can upload to the specified path, if not DIE and inform the user.
   if(!is_writable($upload_path))
      die('You cannot upload to the specified directory, please CHMOD it to 777.');
 
   // Upload the file to your specified path.
   if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
         echo 'Your file upload was successful, Go Back to last page to see files <a href="/puddin/index.php" title="Back To Your Files">here</a>'; // It worked.

      else
         echo 'There was an error during the file upload.  Please try again.'; // It failed .

 
?>

thanks for that I managed to get that code fixed by simply re writing the whole thing in a different style

here is what I did next:

however this new code has given me an issue I never would have seen coming

once I setup my index.html page to work with the upload.php file from above

my file counter seems to inherit 2 files from no where,

in short even when my ./files directory is empty it is showing 2 files in the count there for it always shows 2 more files than are there anyone got any clues

 

ok this text area works in an odd way at the very top is my index.php file followed by my upload.php

Link to comment
Share on other sites

It's counting the entries for "." and "..", which will always be returned in a list of files or directories. You can filter those out when you loop through the entries. This may be helpful also:

 

http://php.net/manual/en/class.directoryiterator.php

http://php.net/manual/en/directoryiterator.construct.php

Link to comment
Share on other sites

Using extension array filter will fix that

        $allowed_filetypes = array('jpg', ' jpe', 'jpeg', 'gif', 'bmp', 'png', 'zip');

//open this directory
        $myDirectory = opendir("../images/emvivacesupplemental2012/gallery/");

        $dirArray = [];

// get each entry
        while ($entryName = readdir($myDirectory)) {

            $imageFileType = strtolower(pathinfo($entryName, PATHINFO_EXTENSION));  //retrieve extension only
            if (in_array($imageFileType, $allowed_filetypes)) {
                $dirArray[] = $entryName;
            }
        }
// close directory
        closedir($myDirectory);

        // count elements in array
        $indexCount = count($dirArray);
        echo ($indexCount . " files<br>\n");

Its not practical to use

$filename = $_FILES['userfile']['name'];

on its own (1), because older versions IE include fullpath, and (2) also someone can use this to access/identify folders and files, that is why basename() is used as it always strips it down to file including extension only.

 

jpeg files include jpe, jpeg, also extensions could be uppercase and will fail validation when checked against extension values within array, check code at top code to see how it is changed to lowercase before comparing to array values.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...