PDA

View Full Version : Resolved How do you restrict file uploads???



Dirt_Diver
02-18-2009, 06:03 AM
when the user is submitting the form I only want them to upload files with a certain extension, how do I do that?

Also, when uploading a file and a picture how do I get php to take the names of the file and add it to the database?

Nile
02-19-2009, 01:42 AM
Here's a whole upload script:


<?php
$types = array("image/jpeg","text/html","text/js","text/css");
if(isset($_POST['submit'])){
$error = true;
foreach($types as $type){
if($_FILES['uploadedfile']['type'] == $type){
$error = false;
}
}
if(!$error){
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
} else if($_FILES['uploadedfile']['name'] != ""){
echo "Looks like you have a ".$_FILES["uploadedfile"]["type"]." type! You can't!";
} else {
echo "No file";
}
}
?>
<div id="uploader"></div>
<form enctype="multipart/form-data" onsubmit="upload(); return false;" method="post" name="uploader">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" name="submit" />
</form>


(not highlighted)

A little help from http://www.tizag.com/phpT/fileupload.php

Explain the database part please. :p

Dirt_Diver
02-20-2009, 01:29 AM
I already have a whole page of code that includes alot more than just one fox box.

Can you add some code to this?




<?php
//connects to the database
include("db")

//define a maxim size for the uploaded images
define ("MAX_SIZE","204800");
// define the width and height for the thumbnail
// note that these dimensions are considered the maximum dimension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","720");
define ("HEIGHT","720");

// create the thumbnail image
// resize image
function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);

if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);

//gets the dimmensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);

$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;
if($ratio1>$ratio2) {
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}
else {
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}

// we create a new image with the new dimensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

// resize the big image to the new created one
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

// output the created image to the file. Now we will have the thumbnail into the file named by $filename
if(!strcmp("png",$ext))
imagepng($dst_img,$filename);
else
imagejpeg($dst_img,$filename);

//destroys source and destination images.
imagedestroy($dst_img);
imagedestroy($src_img);
}

// This function reads the extension of the file.
// It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

// This variable is used as a flag. The value is initialized with 0 (meaning no error found)
//and it will be changed to 1 if an error occurs. If the error occurs the file will not be uploaded.
$errors=0;
// checks if the form has been submitted
if(isset($_POST['Submit']))
{
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
// if it is not empty
if ($image)
{
// get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);

// get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
// if it is not a known extension, we will suppose it is an error, print an error message
//and will not upload the file, otherwise we continue
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo '<font color="#F0B80F"><b>Please make sure that the image extension is .jpg, .jpeg, .png or .gif. No other extenstions are allowed. </b></font>';
$errors=1;
}
else
{
// get the size of the image in bytes
// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server
$size=getimagesize($_FILES['image']['tmp_name']);
$sizekb=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($sizekb > MAX_SIZE*1)
{
echo '<font color="#F0B80F"><b>Your image size is too large, please resize your image.</b></font>';
$errors=1;
}

//we will give an unique name, for example the time in unix time format
$image_name = $filename;
//the new name will be containing the full path where will be stored (images folder)
$newname="../../images/ps_actions/temp/".$image_name;
$copied = copy($_FILES['image']['tmp_name'], $newname);
//we verify if the image has been uploaded, and print error instead
if (!$copied)
{
echo '<font color="#F0B80F"><b>Your image upload was unsuccessful!</b></font>';
$errors=1;
}
else
{
// the new thumbnail image will be placed in images/thumbs/ folder
$thumb_name='../../images/ps_actions/temp/th_'.$image_name;
// call the function that will create the thumbnail. The function will get as parameters
//the image name, the thumbnail name and the width and height desired for the thumbnail
$thumb=make_thumb($newname,$thumb_name,160,120);
}} }}

ini_set ('display_errors', 1);
error_reporting (E_ALL & ~E_NOTICE);

//If no errors registred, print the success message and show the thumbnail image created
if(isset($_POST['Submit']) && !$errors)
{
//This makes sure they did not leave any fields blank
if (!$_POST['uploader_name']) {
die('<font color="#F0B80F"><b>We need your name so we know who uploaded the action.</b></font>');
}
if (!$_POST['uploader_email']) {
die('<font color="#F0B80F"><b>I think you forgot to add your email address. Please go back and try again.</b></font>');
}
if (!$_POST['action_desc']) {
die('<font color="#F0B80F"><b>It looks like you forgot to tell us about your action.</b></font>');
}


//Makes sure the email address is valid
if (!preg_match("/.*@.*..*/", $_POST['uploader_email']) ||
preg_match("/(<|>)/", $_POST['uploader_email'])) {
die('<font color="#F0B80F"><b>The e-mail address you entered is invalid.</b></font>');
}

//grabs the file and uploads it to ../../downloads/photoshop/temp_actions/
if (move_uploaded_file ($_FILES['action_id']['tmp_name'], "../../downloads/photoshop/temp_actions/{$_FILES['action_id']['name']}")){
print '<p> Thank you for your contribution to this site.';

} else {
print '<p><font color="#F0B80F">Your action could not be uploaded because: <b>';

//print a message based upon the eror
switch ($_FILES['action_id']['error']){
case 1:
print 'The file you are trying to upload exceeds the allowed maximium file size allowed. Please contact an administrator for help.';
break;
case 2:
print 'The file you are trying to upload exceeds the allowed maximium file size allowed. Please contact an administrator for help.';
break;
case 3:
print 'Your action was partically uploaded, however please go back and try to upload the entire file again. <br> Sorry for the inconvience.';
break;
case 4:
print 'The file is missing or is corrupt. Please try another file.';
break;
}
print '</b>.</font></p>';
}

echo "</p> You should see your action on the site within 24 hours.<br><br>";
echo '<a href="'.$newname.'"rel="lightbox" title="<center><strong>Your Image</strong></center>"> <img src="'.$thumb_name.'"></a>';
//mail('email', 'New Uploaded Feature Image', 'a user has uploaded an image to be reviewed for a featured image. ');




// Connects to the Database

// Adding the info into the database
$uploader_name = mysql_real_escape_string(htmlentities($_POST['uploader_name']));
$uploader_email = mysql_real_escape_string(htmlentities($_POST['uploader_email']));
$action_name = mysql_real_escape_string(htmlentities($_POST['action_id']));
$action_desc = mysql_real_escape_string(htmlentities($_POST['action_desc']));
$image_name = mysql_real_escape_string(htmlentities($_POST['image']));
$ip = mysql_real_escape_string(htmlentities($_SERVER['REMOTE_ADDR']));


$insert = "INSERT INTO psactions (uploader_name, uploader_email, action_name, action_desc, image_name, ip)
VALUES ('$uploader_name', '$uploader_email', '$action_name', '$action_desc', '$image_name', '$ip')";
mysql_query($insert) or die(mysql_error());

?>



<?php
}
else {
?>

<!-- next comes the form, you must set the enctype to "multipart/form-data" and use an input type "file" -->

<form name="newad" method="post" enctype="multipart/form-data" action="" onSubmit="submitonce(this);document.getElementById('rules').style.display='none';">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="50%"><p><strong>What is your name? </strong><br>
<span class="small_text">(This is the name that will be displayed
on the actions download page.)</span><br>
<input name="uploader_name" type="text" id="uploader_name">
</p>
<p>&nbsp;</p></td>
</tr>
<tr>
<td><p><strong>What is your email address?</strong><br>
<input name="uploader_email" type="text" id="uploader_email">
</p>
<p>&nbsp; </p></td>
</tr>
<tr>
<td><p><strong>Can you explain what your action does? </strong><br>
<span class="small_text">(Briefly tell me what your action does
so others can understand it.)</span><br>
<textarea name="action_desc" cols="43" rows="5" id="action_desc"></textarea>
</p>
<p>&nbsp; </p></td>
</tr>
<tr>
<td><p><strong>Upload your Action here.</strong><br>
<input type="hidden" name="MAX_FILE_SIZE" value="52428800">
<input name="action_id" type="file" id="action_id" size="45">
</p>
<p>&nbsp; </p></td>
</tr>
<tr>
<td><p><strong>Can you upload a sample image of your action? </strong><br>
<span class="small_text">(no bigger than 640px by 640px)</span><br>
<input name="image" type="file" size="45" >
</p>
<p>&nbsp; </p></td>
</tr>
</table>
<br>

<input name="Submit" type="submit" value="Upload Action">
</form>
<?php
}
?>

Dirt_Diver
02-20-2009, 01:36 AM
I need to add another file extension validator to allow ONLY .atn files to be uploaded from the action_id text field.

Right now only jpg, png and gif files can be uploaded from the image field but I need to add another one for the action _id field.

Can anyone help?

Dirt_Diver
02-20-2009, 05:10 AM
nevermind I got it