I made a PHP upload file script. Now, I don’t want people uploading files that are huge and I don’t want them to upload PHP files either. Here’s my current PHP script:
<?php
// Where the file is going to be placed
$target_path = "files/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$length = 10;
$characters = '123456789abcdefghijklmnopqrstuvwxyz';
$string="";
for($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
$pos = strrpos(basename( $_FILES['uploadedfile']['name']), ".");
$ext = str_split(basename( $_FILES['uploadedfile']['name']), $pos);
$target_path = $target_path.$string.$ext[1];
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "<h2>Your file has been uploaded!</h2><br /><p>Your file has been uploaded successfully. <a href='".$target_path."'>Click here</a> to see the file you uploaded.
<br /><br /><br />
<h2>A link to your file</h2><br />The full link to your file is:
<br /><br />
<code>http://www.americaspoeticsoul.com/extras/upload/".$target_path."</code></p>";
} else{
echo "<span class='error'>There was an error uploading the file, please try again.</span>";
}
?>
How would I set a max file upload size and allow only certain file types such as only JPEGs, GIFs, PNGs, and HTML files?
Thanks in advance,
Nathan
You can check the file size using
$_FILES['uploadedfile']["size"]. The client-supplied file type is available in...["type"].But for your code you will want to probe the
$extvariable against a whitelist (just looking for extensions to forbid might not be a good idea):At this point it might be advisable to consider a readymade helper class/script for all the upload checking. Your code is quite unreadable already.