PHP - Validation Of File Upload Field
I'm having some trouble validating a file upload. I have it set to display a message if the file upload name already exists, but it is also displaying the same message when the field is left blank. I tried adding in a message to display when the field was blank, but it always displays the previous message, plus the new message, and on top of that, the error message about the file field being blank displays even if the user has uploaded a file. can anyone help??
Code: [Select] <?php $firstname = ""; $lastname = ""; $address = ""; $city = ""; $state = ""; $zip = ""; $phone = ""; $position = ""; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>KulaE_WDP4451_U2IP</title> </head> <body> <form action="process_U2IP.php" method="post" enctype="multipart/form-data"> <h3>Please fill out the form below and upload your resume to apply for a position within our company:</h3> <table> <tr> <td><label for="firstname"><b>First Name*</b></label></td> <td><input name="firstname" type="text" size="20" id="firstname" value="<?php echo $lastname; ?>" /></td> </tr> <tr> <td><label for="lastname"><b>Last Name*</b></label></td> <td><input name="lastname" type="text" size="20" id="lastname" value="<?php echo $lastname; ?>" /></td> </tr> <tr> <td><label for="address"><b>Address*</b></label></td> <td><input name="address" type="text" size="20" id="address" value="<?php echo $address; ?>" /></td> </tr> <tr> <td><label for="city"><b>City*</b></label></td> <td><input name="city" type="text" size="20" id="city" value="<?php echo $city; ?>" /></td> </tr> <tr> <td><label for="state"><b>State*</b></label></td> <td><input name="state" type="text" size="20" id="state" value="<?php echo $state; ?>" /></td> </tr> <tr> <td><label for="zip"><b>Zip*</b></label></td> <td><input name="zip" type="text" size="20" id="zip" value="<?php echo $zip; ?>" /></td> </tr> <tr> <td><label for="phone"><b>Phone*</b></label></td> <td><input name="phone" type="text" size="20" id="phone" value="<?php echo $phone; ?>" /></td> </tr> <tr> <td><label for="position"><b>Position*</b></label></td> <td><input name="position" type="text" size="20" id="position" value="<?php echo $position; ?>" /></td> </tr> <tr> <td><b>Upload Resume*</b></td> <td><input type="file" name="file" id="file" /> </td> </tr> <tr> <td colspan="2"><p><i>Your information will not be sold or shared with others.</i></p></td> </tr> <tr> <td colspan="2"><p style="color: red;">* denotes required field</p></td> </tr> <tr> <td colspan="2" align="center"><input type="hidden" name="submitted" value="1" /> <input type="submit" value="Submit" /> <input type="reset" name="reset" value="Reset" /></td> </tr> </table> </form> </body> </html> Code: [Select] <?php if (@$_POST['submitted']){ $firstname = (@$_POST['firstname']); $lastname = (@$_POST['lastname']); $address = (@$_POST['address']); $city = (@$_POST['city']); $state = (@$_POST['state']); $zip = (@$_POST['zip']); $phone = (@$_POST['phone']); $position = (@$_POST['position']); $file = (@$_POST['file']); if (get_magic_quotes_gpc()){ $firstname = stripslashes($firstname); $lastname = stripslashes($lastname); $address = stripslashes($address); $city = stripslashes($city); $state = stripslashes($state); $zip = stripslashes($zip); $phone = stripslashes($phone); $position = stripslashes($position); } $error_msg=array(); if ($firstname==""){ $error_msg[]="Please enter your first name"; } if(!preg_match("/^\b[a-zA-Z]+\b$/", $firstname)){ $error_msg[]="First Name can only contain letters"; } if ($lastname==""){ $error_msg[]="Please enter your last name"; } if(!preg_match("/^\b[a-zA-Z]+\b$/", $lastname)){ $error_msg[]="Last Name can only contain letters"; } if ($address==""){ $error_msg[]="Please enter your address"; } if(!preg_match('/^[a-z0-9 ]*$/i', $address)){ $error_msg[]="Address can only contain numbers, letters and spaces"; } if ($city==""){ $error_msg[]="Please enter your city"; } if (!preg_match("/^\b[a-zA-Z]+\b$/", $city)){ $error_msg[]="City can only contain letters"; } if ($state==""){ $error_msg[]="Please enter your state"; } if (strlen($state)<>2){ $error_msg[]="State can only contain 2 letters; use state abbreviation"; } if (!preg_match("/^\b[a-zA-Z]+\b$/", $state)){ $error_msg[]="State can only contain letters"; } if ($zip==""){ $error_msg[]="Please enter your zip code"; } if (strlen($zip)<>5){ $error_msg[]="Zip code can only contain 5 digits"; } if(!is_numeric($zip)){ $error_msg[]="Zip code must contain only numbers"; } if ($phone==""){ $error_msg[]="Please enter your phone number"; } if (strlen($phone)<>10){ $error_msg[]="Phone number can only contain 10 digits"; } if(!is_numeric($phone)){ $error_msg[]="Phone number must contain only numbers"; } if ($position==""){ $error_msg[]="Please enter your desired position"; } if(!preg_match('/^[a-z0-9 ]*$/i', $position)){ $error_msg[]="Position can only contain numbers, letters and spaces"; } if (file_exists("upload/" . $_FILES["file"]["name"])) { $error_msg[]= $_FILES["file"]["name"] . " already exists"; } if ((($_FILES["file"]["type"] != "document/msword") || ($_FILES["file"]["type"] != "document/pdf")) && ($_FILES["file"]["size"] > 50000)) { $error_msg[]= "Uploaded file can only be in MSWord or PDF format and can only be under 50KB in size"; } } if ($error_msg){ $display_errors = "<h3>There were errors in your submission.</h3> <p>Please review the following errors, press the Back button on your browser, and make corrections before re-submitting.</p> <ul style=color:red>\n"; foreach ($error_msg as $err){ $display_errors .= "<li>".$err."</li>\n"; } $display_errors .= "</ul>\n"; } if (!$error_msg){ echo " <h3>Thank you for applying! Applicants we are interested in interviewing will be contacted within 48 hours.</h3> <p>You have submitted the following information:</p> <table> <tr> <td><b>First Name:</b></td> <td>$firstname</td> </tr> <tr> <td><b>Last Name:</b></td> <td>$lastname</td> </tr> <tr> <td><b>Address:</b></td> <td>$address</td> </tr> <tr> <td><b>City:</b></td> <td>$city</td> </tr> <tr> <td><b>State:</b></td> <td>$state</td> </tr> <tr> <td><b>Zip Code:</b></td> <td>$zip</td> </tr> <tr> <td><b>Phone Number:</b></td> <td>$phone</td> </tr> <tr> <td><b>Position Desired:</b></td> <td>$position</td> </tr>"; move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "<tr> <td><b>Uploaded File:</b></td> <td><a href=upload/" . $_FILES["file"]["name"] . ">" . $_FILES["file"]["name"] . "</a></td> </tr> </table>"; exit(); } echo $display_errors; ?> Similar TutorialsHi, This is the code I made to show the problem: $useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 ( .NET CLR 3.5.30729)"; $timeout = 10 ; $cookie = tempnam ("/tmp", "CURLCOOKIE"); $post = array('_method'=>"put", 'authenticity_token'=>' zcvcxfsdfvxcv', 'profile_image[a]'=>"@Girl-Next-Door-movie-f01.jpg" ); $ch = curl_init(); curl_setopt( $ch, CURLOPT_USERAGENT, $useragent); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($ch, CURLOPT_URL, "http://localhost/test.php"); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie ); curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true ); curl_setopt( $ch, CURLOPT_ENCODING, "" ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch, CURLOPT_AUTOREFERER, true ); curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); # required for https urls curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout ); curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout ); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); $html = curl_exec($ch); curl_close($ch); Now this link used above: http://localhost/test.php has this code: print_r($_POST); print_r($_FILES); It simply prints whats in post and files. So the above code displays this on screen: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image] => Array ( [name] => Array ( [a] => Girl-Next-Door-movie-f01.jpg ) [type] => Array ( [a] => image/jpeg ) [tmp_name] => Array ( [a] => /tmp/phppLJPQV ) [error] => Array ( [a] => 0 ) [size] => Array ( [a] => 55377 ) ) ) but we need to modify the code so that it should display this: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image[a]] => Array ( [name] => Girl-Next-Door-movie-f01.jpg [type] => image/jpeg [tmp_name] => /tmp/phppLJPQV [error] => 0 [size] => 55377 ) ) Meaning, it is taking this(profile_image[a]) as an array when we are defining $post because that's how curl recognizes that we want to upload only a file or an array of files on server by http post. So, basically the problem is the name of the input field that is defined as an array (profile_image[a]) on the web page that we are trying to mock. If this(profile_image[a]) was this (profile_image_a)(without []) on that webpage, then it would not have been a problem. So, if you understand, this is basically a syntax problem. I do not know how stop curl from reading 'profile_image[a]' as an array here 'profile_image[a]'=>"@Girl-Next-Door-movie-f01.jpg. I need curl to read 'profile_image[a]' as an string and not array. I have to use [], otherwise I will not be able to mock the webpage as the name will change. It will give error. I hope I explained the problem and also gave you a way to test if you have a solution. Again, if your code starts displaying this: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image[a]] => Array ( [name] => Girl-Next-Door-movie-f01.jpg [type] => image/jpeg [tmp_name] => /tmp/phppLJPQV [error] => 0 [size] => 55377 ) ) ,then we have a solution. Thanks for helping in advance. Regards, Manoj files that upload during insert/submit form was gone , only files upload during the update remain , is the way query for update multiple files is wrong ? $targetDir1= "folder/pda-semakan/ic/"; if(isset($_FILES['ic'])){ $fileName1 = $_FILES['ic']['name']; $targetFilePath1 = $targetDir1 . $fileName1; //$main_tmp2 = $_FILES['ic']['tmp_name']; $move2 =move_uploaded_file($_FILES["ic"]["tmp_name"], $targetFilePath1); } $targetDir2= "folder/pda-semakan/sijil_lahir/"; if(isset($_FILES['sijilkelahiran'])){ $fileName2 = $_FILES['sijilkelahiran']['name']; $targetFilePath2 = $targetDir2 . $fileName2; $move3 =move_uploaded_file($_FILES["sijilkelahiran"]["tmp_name"], $targetFilePath2); } $targetDir3= "folder/pda-semakan/sijil_spm/"; if(isset($_FILES['sijilspm'])){ $fileName3 = $_FILES['sijilspm']['name']; $targetFilePath3 = $targetDir3 . $fileName3; $move4 =move_uploaded_file($_FILES["sijilspm"]["tmp_name"], $targetFilePath3); } $query1=("UPDATE semakan_dokumen set student_id='$noMatrik', email= '$stdEmail', surat_tawaran='$fileName', ic='$fileName1',sijil_lahir='$fileName2',sijil_spm= '$fileName3' where email= '$stdEmail'");
Hi all, I've been struggling to develop a robust image upload validation script. I have an area on my site where users can upload a profile picture into a directory so, to keep it clean and safe here is what I want: 1) Script must work in IE and Firefox 2) Script must only allow image files to be uploaded 3) Images shouldn't be unreasonable in size say 4mb max. Currently i'm using this Code: [Select] if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 40000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { if (file_exists("profiles/images/$filegif")) { unlink("profiles/images/$filegif"); } if (file_exists("profiles/images/$filejpeg")) { unlink("profiles/images/$filejpeg"); } move_uploaded_file($_FILES["file"]["tmp_name"], "profiles/images/" .$name); } //.... send me email to let me view picture ....// } else { echo "Invalid file - Only Gif or Jpeg files may be uploaded."; ///... send me error message to let me know user having problems .../// } } Some users upload fine (is this browser compatability?), mostly I get alot or error messages though and have to upload manually. Thanks in advance! In this multi file upload form, choose three images, click submit and preview the images on the preview page. If the user wishes to delete or replace an image, click edit and the form will go back to the previous page. Select the replace radio button for example on one of the three images and select a new image from the file input prompt and click submit. The form will go to the preview page again to display the images. During this process the image names are being input into a table and the images are being moved to a directory. The table is `id` AUTO_INCREMENT, `image0` `image1` `image2` `status` So input name='image[image0]' can be directed to table `image0` and so on. The code for keep and delete work fine, but how do I replace an image? I have two foreach blocks. The first one deletes the image file from the directory and deletes the image name from the table, but the second foreach dose not move the new image file into the directory. Thanks. <input type='radio' name='image[image0]' value='keep' checked='checked'/> <input type='radio' name='image[image0]' value='delete' /> <input type='radio' name='image[image0]' value='replace' /> <input type="file" name="image[]" /> <input type='radio' name='image[image1]' value='keep' checked='checked'/> <input type='radio' name='image[image1]' value='delete' /> <input type='radio' name='image[image1]' value='replace' /> <input type="file" name="image[]" /> <input type='radio' name='image[image2]' value='keep' checked='checked'/> <input type='radio' name='image[image2]' value='delete' /> <input type='radio' name='image[image2]' value='replace' /> <input type="file" name="image[]" /> <?php if (isset($_POST['status'])) { $status = $_POST['status']; $confirm_code = $status; #--------------------------- replace -------------------------------------------- if (isset($_POST['submitted']) && ($image = $_POST['image'])) { foreach($image as $imageKey => $imageValue) { if ($imageValue == 'replace') { $query = "SELECT $imageKey FROM table WHERE status = '$status' "; if($result = $db->query( $query )){ $row = $result->fetch_array(); } unlink( UPLOAD_DIR.$row[0] ); $query = "UPDATE table SET $imageKey = '' WHERE status = '$status' "; } } foreach($image as $imageKey => $imageValue) { if ($imageValue == 'replace') { $filenm = $_FILES['image']['name']; $file = $_FILES['image']['tmp_name']; move_uploaded_file($file, UPLOAD_DIR . $filenm); $filename[] = $filenm; $query = "INSERT INTO table VALUES ('','$filename[0]','$filename[1]','$filename[2]','$confirm_code')"; } } } } ?> Hiya, Firstly, I'm a complete novice, apologies! But I have got my upload.php working which is nice. I will post the code below. However, I would now like to restrict the file size and file type to only word documents. I currently have a restriction of 200KB but it's not working - no idea why as I've looked at other similar codes and they look the same. Also, just to complicate things - can I stop files overwriting each other when uploaded? At the moment, if 2 people upload files with the same name one will overwrite the other. Is this too many questions in 1? Any help is very much appreciated! Code below: Code: [Select] <form enctype="multipart/form-data" action="careers.php" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form> <?php $target = "upload/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition if ($uploaded_size > 200) { echo "Your file is too large.<br>"; $ok=0; } //This is our limit file type condition if ($uploaded_type =="text/php") { echo "No PHP files<br>"; $ok=0; } //Here we check that $ok was not set to 0 by an error if ($ok==0) { Echo "Sorry your file was not uploaded"; } //If everything is ok we try to upload it else { if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "Your file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded."; } else { echo "Sorry, there was a problem uploading your file."; } } ?> Hi People, I have this problem, i have created an upload form which includes some text fields and also an image upload which then gets sent to a server. I haven't yet got any validation or sanitisation on there at the moment. Im abit new to PHP and can code beginners stuff really, could someone give us some help with this please! addproduct.php - This is my form Code: [Select] <table width="300" border="0" align="center" cellpadding="0" cellspacing="1"> <tr> <td><form enctype="multipart/form-data" name="form1" method="post" action="insert_add.php"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="200"><b>Model</b></td> <td width="10">:</td> <td width="400"><input name="model" type="text" id="model" size="28"></td> </tr> <tr> <td><b>Product</b></td> <td>:</td> <td><input name="product" type="text" id="product" size="28"></td> </tr> <tr> <td><b>Description</b></td> <td>:</td> <td><textarea rows="5" cols="21" type="text" name="description" id="description"></textarea></td> </tr> <tr> <td><b>Price</b></td> <td>:</td> <td><input name="price" type="text" id="price" size="28"></td> </tr> <tr> <td><b>Image:</b></td> <td>:</td> <td><input type="file" name="photo"></td> </tr> <tr> <tr> <td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td> </tr> </table> </form> </td> </tr> </table> insert_add.php - This is a page which uploads contents to server <?php $host=""; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name=""; // Table name // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); //This is the directory where images will be saved $target = "images/"; $target = $target . basename( $_FILES['photo']['name']); // Get values from form $model=$_POST['model']; $product=$_POST['product']; $description=$_POST['description']; $price=$_POST['price']; $pic=($_FILES['photo']['name']); // Insert data into mysql $sql="INSERT INTO $tbl_name(model, product, description, price, photo)VALUES('$model', '$product', '$description', '$price', '$pic')"; $result=mysql_query($sql); if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { //Tells you if its all ok echo "<center>The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory</center>"; } else { //Gives and error if its not echo "Sorry, there was a problem uploading your file."; } // close connection mysql_close(); ?> Any help with coding would be greatfully appreciated. Hello, all: been trying to convert this little single-file upload to multiple by naming each file form-field as "userfile[]" as it's supposed to automatically treat them as an array.. but no luck! Can you guide me as to what am I doing wrong?? appreciate the help! Code: [Select] <?php if (!isset($_REQUEST["seenform"])) { ?> <form enctype="multipart/form-data" action="#" method="post"> Upload file: <input name="userfile[]" type="file" id="userfile[]"> Upload file: <input name="userfile[]" type="file" id="userfile[]"> <input type="submit" value="Upload"> <input type="hidden" name="seenform"> </form> <?php } else { // upload begins $userfiles = array($_FILES['userfile']); foreach ($userfiles as $userfile) { // foreach begins $uploaded_dir = "uploads/"; $userfile = $_FILES['userfile']["name"]; $path = $uploaded_dir . $userfile; if (move_uploaded_file($_FILES['userfile']["tmp_name"], $path)) { print "$userfile file moved"; // do something with the file here } else { print "Move failed"; } } // foreach ends } // upload ends ?> <td><label for='images'> <b>File to upload:</b> </label></td> <td><input type='file' name = 'drama_image' '<?php echo $row['drama_image']; ?>'/></ </tr> <?php $target_path = "images/"; $target_path = $target_path . basename( $_FILES['images']['name']); if(move_uploaded_file($_FILES['images']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['images']['name']). " has been uploaded"; } else{ echo $row['drama_image']; } ?> ['drama_image'] is the name of the file I wanna echo it out in the box of file upload so when I save , the default picture will still be there instead of being overwritten as the box does not have any value in it. So, I'm learning how to upload pictures into a system from my awesome PHP book. I've looked and looked through the script but I can't figure out whats wrong with it. Goal: The script is meant to save a full version of the image in the images folder and a thumbnail in the thumbnail folder. Bug: The full image does not appear in any folder, and the thumbnail is created but its put in the images folder. I've checked the GD library, and everything is supported. image_effect.php <?php //change this path to match your images directory $dir ='C:/x/xampp/htdocs/images'; //change this path to match your fonts directory and the desired font putenv('GDFONTPATH=' . 'C:/Windows/Fonts'); $font = 'arial'; // make sure the requested image is valid if (isset($_GET['id']) && ctype_digit($_GET['id']) && file_exists($dir . '/' . $_GET['id'] . '.jpg')) { $image = imagecreatefromjpeg($dir . '/' . $_GET['id'] . '.jpg'); } else { die('invalid image specified'); } // apply the filter $effect = (isset($_GET['e'])) ? $_GET['e'] : -1; switch ($effect) { case IMG_FILTER_NEGATE: imagefilter($image, IMG_FILTER_NEGATE); break; case IMG_FILTER_GRAYSCALE: imagefilter($image, IMG_FILTER_GRAYSCALE); break; case IMG_FILTER_EMBOSS: imagefilter($image, IMG_FILTER_EMBOSS); break; case IMG_FILTER_GAUSSIAN_BLUR: imagefilter($image, IMG_FILTER_GAUSSIAN_BLUR); break; } // add the caption if requested if (isset($_GET['capt'])) { imagettftext($image, 12, 0, 20, 20, 0, $font, $_GET['capt']); } //add the logo watermark if requested if (isset($_GET['logo'])) { // determine x and y position to center watermark list($width, $height) = getimagesize($dir . '/' . $_GET['id'] . '.jpg'); list($wmk_width, $wmk_height) = getimagesize('images/logo.png'); $x = ($width - $wmk_width) / 2; $y = ($height - $wmk_height) / 2; $wmk = imagecreatefrompng('images/logo.png'); imagecopymerge($image, $wmk, $x, $y, 0, 0, $wmk_width, $wmk_height, 20); imagedestroy($wmk); } // show the image header('Content-Type: image/jpeg'); imagejpeg($image, '', 100); ?> check_image.php <?php include 'db.inc.php'; //connect to MySQL $db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die ('Unable to connect. Check your connection parameters.'); mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db)); //change this path to match your images directory $dir ='C:/x/xampp/htdocs/images'; //change this path to match your thumbnail directory $thumbdir = $dir . '/thumbs'; //change this path to match your fonts directory and the desired font putenv('GDFONTPATH=' . 'C:/Windows/Fonts'); $font = 'arial'; // handle the uploaded image if ($_POST['submit'] == 'Upload') { //make sure the uploaded file transfer was successful if ($_FILES['uploadfile']['error'] != UPLOAD_ERR_OK) { switch ($_FILES['uploadfile']['error']) { case UPLOAD_ERR_INI_SIZE: die('The uploaded file exceeds the upload_max_filesize directive ' . 'in php.ini.'); break; case UPLOAD_ERR_FORM_SIZE: die('The uploaded file exceeds the MAX_FILE_SIZE directive that ' . 'was specified in the HTML form.'); break; case UPLOAD_ERR_PARTIAL: die('The uploaded file was only partially uploaded.'); break; case UPLOAD_ERR_NO_FILE: die('No file was uploaded.'); break; case UPLOAD_ERR_NO_TMP_DIR: die('The server is missing a temporary folder.'); break; case UPLOAD_ERR_CANT_WRITE: die('The server failed to write the uploaded file to disk.'); break; case UPLOAD_ERR_EXTENSION: die('File upload stopped by extension.'); break; } } //get info about the image being uploaded $image_caption = $_POST['caption']; $image_username = $_POST['username']; $image_date = @date('Y-m-d'); list($width, $height, $type, $attr) = getimagesize($_FILES['uploadfile']['tmp_name']); // make sure the uploaded file is really a supported image $error = 'The file you uploaded was not a supported filetype.'; switch ($type) { case IMAGETYPE_GIF: $image = imagecreatefromgif($_FILES['uploadfile']['tmp_name']) or die($error); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($_FILES['uploadfile']['tmp_name']) or die($error); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($_FILES['uploadfile']['tmp_name']) or die($error); break; default: die($error); } //insert information into image table $query = 'INSERT INTO images (image_caption, image_username, image_date) VALUES ("' . $image_caption . '", "' . $image_username . '", "' . $image_date . '")'; $result = mysql_query($query, $db) or die (mysql_error($db)); //retrieve the image_id that MySQL generated automatically when we inserted //the new record $last_id = mysql_insert_id(); // save the image to its final destination $image_id = $last_id; imagejpeg($image, $dir . '/' . $image_id . '.jpg'); imagedestroy($image); } else { // retrieve image information $query = 'SELECT image_id, image_caption, image_username, image_date FROM images WHERE image_id = ' . $_POST['id']; $result = mysql_query($query, $db) or die (mysql_error($db)); extract(mysql_fetch_assoc($result)); list($width, $height, $type, $attr) = getimagesize($dir . '/' . $image_id . '.jpg'); } if ($_POST['submit'] == 'Save') { // make sure the requested image is valid if (isset($_POST['id']) && ctype_digit($_POST['id']) && file_exists($dir . '/' . $_POST['id'] . '.jpg')) { $image = imagecreatefromjpeg($dir . '/' . $_POST['id'] . '.jpg'); } else { die('invalid image specified'); } // apply the filter $effect = (isset($_POST['effect'])) ? $_POST['effect'] : -1; switch ($effect) { case IMG_FILTER_NEGATE: imagefilter($image, IMG_FILTER_NEGATE); break; case IMG_FILTER_GRAYSCALE: imagefilter($image, IMG_FILTER_GRAYSCALE); break; case IMG_FILTER_EMBOSS: imagefilter($image, IMG_FILTER_EMBOSS); break; case IMG_FILTER_GAUSSIAN_BLUR: imagefilter($image, IMG_FILTER_GAUSSIAN_BLUR); break; } // add the caption if requested if (isset($_POST['emb_caption'])) { imagettftext($image, 12, 0, 20, 20, 0, $font, $image_caption); } //add the logo watermark if requested if (isset($_POST['emb_logo'])) { // determine x and y position to center watermark list($wmk_width, $wmk_height) = getimagesize('images/logo.png'); $x = ($width - $wmk_width) / 2; $y = ($height - $wmk_height) / 2; $wmk = imagecreatefrompng('images/logo.png'); imagecopymerge($image, $wmk, $x, $y, 0, 0, $wmk_width, $wmk_height, 20); imagedestroy($wmk); } // save the image with the filter applied imagejpeg($image, $dir . '/' . $_POST['id'] . '.jpg', 100); //set the dimensions for the thumbnail $thumb_width = $width * 0.10; $thumb_height = $height * 0.10; //create the thumbnail $thumb = imagecreatetruecolor($thumb_width, $thumb_height); imagecopyresampled($thumb, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height); imagejpeg($thumb, $dir . '/' . $_POST['id'] . '.jpg', 100); imagedestroy($thumb); ?> <html> <head> <title>Here is your pic!</title> </head> <body> <h1>Your image has been saved!</h1> <img src="images/<?php echo $_POST['id']; ?>.jpg" /> </body> </html> <?php } else { ?> <html> <head> <title>Here is your pic!</title> </head> <body> <h1>So how does it feel to be famous?</h1> <p>Here is the picture you just uploaded to our servers:</p> <?php if ($_POST['submit'] == 'Upload') { $imagename = 'images/' . $image_id . '.jpg'; } else { $imagename = 'image_effect.php?id=' . $image_id . '&e=' . $_POST['effect']; if (isset($_POST['emb_caption'])) { $imagename .= '&capt=' . urlencode($image_caption); } if (isset($_POST['emb_logo'])) { $imagename .= '&logo=1'; } } ?> <img src="<?php echo $imagename; ?>" style="float:left;"> <table> <tr><td>Image Saved as: </td><td><?php echo $image_id . '.jpg'; ?></td></tr> <tr><td>Height: </td><td><?php echo $height; ?></td></tr> <tr><td>Width: </td><td><?php echo $width; ?></td></tr> <tr><td>Upload Date: </td><td><?php echo $image_date; ?></td></tr> </table> <p>You may apply special options to your image below. Note: saving an image with any of the options applied <em>cannot be undone</em>.</p> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <div> <input type="hidden" name="id" value="<?php echo $image_id;?>"/> Filter: <select name="effect"> <option value="-1">None</option> <?php echo '<option value="' . IMG_FILTER_GRAYSCALE . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GRAYSCALE) { echo ' selected="selected"'; } echo '>Black and White</option>'; echo '<option value="' . IMG_FILTER_GAUSSIAN_BLUR . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GAUSSIAN_BLUR) { echo ' selected="selected"'; } echo '>Blur</option>'; echo '<option value="' . IMG_FILTER_EMBOSS . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_EMBOSS) { echo ' selected="selected"'; } echo '>Emboss</option>'; echo '<option value="' . IMG_FILTER_NEGATE . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_NEGATE) { echo ' selected="selected"'; } echo '>Negative</option>'; ?> </select> <br/><br/> <?php echo '<input type="checkbox" name="emb_caption"'; if (isset($_POST['emb_caption'])) { echo ' checked="checked"'; } echo '>Embed caption in image?'; echo '<br/><br/><input type="checkbox" name="emb_logo"'; if (isset($_POST['emb_logo'])) { echo ' checked="checked"'; } echo '>Embed watermarked logo in image?'; ?> <br/><br/> <input type="submit" value="Preview" name="submit" /> <input type="submit" value="Save" name="submit" /> </div> </form> </body> </html> <?php } ?> Any help appreciated. I havent included the whole title as it wouldnt let me but I was wondering if someone could help me on this? I know this is possible as torrentflux caters for this but unsure of where to start. I dont want to allow file or directory uploads or creation in my /etc/php.ini file (this is turned off). Yet then torrentflux allows me to link a torrent from an external source (using legal downloads of course ) but then it uploads it on my server and creates folders on a per user basis. How is this possible can someone give me some pointers please? I look forward to any replies, Jeremy. Hello all! I want to use PHP to valididate html fields. I'm using a form in index.php and using process.php to process the data, here is my current base: <?php if (isset($_REQUEST['email'])) { $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $from = $_REQUEST['from'] ; $amount = $_REQUEST['amount'] ; $message = $_REQUEST['message'] ; $from = $from; $length = $amount; for ($p = 0; $p < $length; $p++) { mail("$email", "$subject", $message, "From:" . $from); } $headers = "From:" . $from; header('Location: success.php'); } ?> If I wanted to only allow a certain figure in the 'amount' field, would something like this work: <?php $options = array( 'options' => array( 'min_range' => 1, 'max_range' => 99, ) ); $options['options']['default'] = 1; if (($int_c = filter_var($int_c, FILTER_VALIDATE_INT, $options)) !== FALSE) { echo "That number entered is between 1-99."; } ?> However, I'm not sure how I'd apply it to process.php to stop the 'mail' from occurring if the quantity is not between 1-99. Also that above code doesn't echo' That number you have entered is not valid' Many thanks Hi, I have this form to create a new user: Code: [Select] <form action="<?php htmlentities($_SERVER['PHP_SELF']); ?>" method="post" enctype="multipart/form-data" name="form1" id="form1" on> <table width="850" border="0" align="center" cellpadding="8" cellspacing="0"> <tr> <td><table width="100%" border="0" cellspacing="0" cellpadding="10"> <tr> <td><table width="100%" border="0" cellspacing="0" cellpadding="6"> <tr> <td><span class="CP_blueTXT">Nombre de la persona autorizada</span></td> </tr> <tr> <td> <input name="usuario_nombre" type="text" class="CP_loginFormFields" id="usuario_nombre" size="32" /></td> </tr> </table></td> </tr> </table> <table width="100%" border="0" cellpadding="10" cellspacing="0"> <tr> <td><table width="100%" border="0" cellspacing="0" cellpadding="6"> <tr> <td><span class="CP_blueTXT">Nombre de usuario</span></td> </tr> <tr> <td> <input name="usuario" type="text" class="CP_loginFormFields" id="usuario" size="32" /> <span class="CP_SiNoText"><?php echo isset($errorMsg) ? $errorMsg : '';?></span></td> </tr> </table></td> </tr> </table> <table width="100%" border="0" cellspacing="0" cellpadding="10"> <tr> <td><table width="100%" border="0" cellspacing="0" cellpadding="6"> <tr> <td><span class="CP_blueTXT">Contraseña</span></td> </tr> <tr> <td> <input name="password" type="text" class="CP_loginFormFields" id="password" size="32" /></td> </tr> </table></td> </tr> </table> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td><table width="100%" border="0" cellspacing="0" cellpadding="6"> <tr> <td width="2%"> </td> <td width="98%"><input name="upload" type="submit" class="box" id="upload" value=" crear usuario" /></td> </tr> </table></td> </tr> </table></td> </tr> </table> </form> ...and I use this query to cretae a new user record: Code: [Select] $colname_checkdup_RS = "-1"; // this checks that if the user entered is already in database if (isset($_POST['usuario'])) { $colname_checkdup_RS = $_POST['usuario']; } mysql_select_db($database_MySQLconnect, $MySQLconnect); $query_checkdup_RS = sprintf("SELECT * FROM t_usuario WHERE usuario = %s", GetSQLValueString($colname_checkdup_RS, "text")); $checkdup_RS = mysql_query($query_checkdup_RS, $MySQLconnect) or die(mysql_error()); $row_checkdup_RS = mysql_fetch_assoc($checkdup_RS); $totalRows_checkdup_RS = mysql_num_rows($checkdup_RS); if($totalRows_checkdup_RS==1) { $errorMsg = "el usuario introducido ya existe en la base de datos"; // duplicate entry found message } else{ $query = "INSERT INTO eu45antinew.t_usuario (usuario_nombre,usuario,password) ". "VALUES ('$usuario_nombre','$usuario','$password')"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); //echo "<br>Files uploaded<br>"; header("Location: PC_users_display.php"); } } ?> The query includes a function to check if the value entered in "user" already exists. This works fine, but I want the field "user" to be an email address...so I would like to validate that field...how can I do that? Thanks I have a form that allows my client to update some products. Now the products are simple just basic info and 1 picture. I have set this up so they can edit the products and change the information, having done this many times in the past, but now hit a puzzling block that I am baffled. The client when editing is presented with the form with the information pulled from the database and the form fields loaded with that data ready to edit. The image can either be left alone or they can choose to upload a new image. They are shown the image they currently have stored in the database. The problem I have is EVEN if they decide not to upload an image and change other information, when the submit the form it must be sending a blank value for the image somewhere as it is updating the database and removing the image reference as if it has been removed. I have an if/else statement based on the form to perform 2 different queries for the update in mysql. Here is the code for the form update, as you can see the image should not update?? Please help?? if ($_SERVER['REQUEST_METHOD'] =='POST') { //This stops SQL Injection in POST vars foreach ($_POST as $key => $value) { $_POST[$key] = mysql_real_escape_string($value); } // **************************** THIS IS FOR NO NEW IMAGE ******************************** if ($_SERVER['REQUEST_METHOD'] =='POST' && empty($_FILES['product_image']['name'])) { # setup SQL statement for no new image $SQL = " UPDATE products SET product_title = '{$_POST['product_title']}', product_description = '{$_POST['product_description']}', standard_price = '{$_POST['standard_price']}', deluxe_price = '{$_POST['deluxe_price']}' WHERE product_id = '{$_REQUEST['product_id']}' "; } // **************************** THIS IS FOR A NEW IMAGE ******************************** else { // Check the image type is a jpeg or gif for the image. if (($_FILES['product_image']['type'] != "image/gif") && ($_FILES['product_image']['type'] != "image/jpeg") && ($_FILES['product_image']['type'] != "image/pjpeg")) { echo "<FONT FACE=\"Verdana\"><SPAN CLASS=\"content\">You have chosen not to upload a <b>Product Image</b>.<BR></SPAN>" ; } elseif ($_FILES['product_image']['size'] > 100000) { echo "<FONT FACE=\"Verdana\"><SPAN CLASS=\"content\">The file size is bigger than 300kb.<BR></SPAN>" ; } else { move_uploaded_file($_FILES['product_image']['tmp_name'], "/httpdocs/product_images/".$_FILES['product_image']['name']) ; echo "<FONT FACE=\"Verdana\"><SPAN CLASS=\"content\"><B>Your front image has successfully uploaded.</B><BR></SPAN>" ; } } # setup SQL statement for update $SQL = " UPDATE products SET product_title = '{$_POST['product_title']}', product_description = '{$_POST['product_description']}', standard_price = '{$_POST['standard_price']}', deluxe_price = '{$_POST['deluxe_price']}', product_image = '{$_FILES['product_image']['name']}' WHERE product_id = '{$_REQUEST['product_id']}' "; } #execute SQL statement $result = mysql_db_query( *****,"$SQL",$connection ); # check for error if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n"); } HI All, I have a form submission that uploads a photo as well as submitting other data. I would like to change the name of the photo to the id of the person record (created automatically on by the database) then a hyphen, then their first name and lastname. (i am flexible on this). This file name will also need to be submitted into the person record so the photo and the person can be linked. I am struggling with this one - but here is the code i have so far.
<?php include 'includes/dbconn.php'; $target_dir = "img/people/"; $target_file = $target_dir . basename($_FILES["personHeadshot"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); if ($_SERVER['REQUEST_METHOD']=='POST'){ $fn = $_POST['fname']; $ln = $_POST['lname']; $ad1 = $_POST['ad1']; $ad2 = $_POST['ad2']; $city = $_POST['city']; $post = $_POST['postcode']; $tel = $_POST['phone']; $email = $_POST['email']; $crole = $_POST['comRole']; $OFA = $_POST['OFA']; $playerType = $_POST['playerType']; $team = $_POST['primaryTeam']; $stmt = $conn->prepare(" INSERT IGNORE INTO person (fname, lname, committee_role_id, player_type_id, team_id, ad1, ad2, city, postcode, mobile, email, on_field_auth_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) "); $stmt -> bind_param(ssiiissssssi, $fn, $ln, $crole, $playerType, $team, $ad1, $ad2, $city, $post, $tel, $email, $OFA); $stmt -> execute(); // Check if image file is a actual image or fake image //photo upload $check = getimagesize($_FILES["personHeadshot"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } //photo upload header("location: ../admin-people-list.php"); } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["personHeadshot"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["personHeadshot"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["personHeadshot"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } }
Hello! I have this validation script that seems to work great until I add the size validation. I'm ready to pull my hair out! Can someone tell me what I'm doing wrong? Code: [Select] if (isset($_POST['Submit'])) { $user_id = $userdata[user_id]; $number_of_file_fields = 0; $number_of_uploaded_files = 0; $number_of_moved_files = 0; $uploaded_files = array(); $max_filesize = 5242880; // Maximum filesize in BYTES (currently 5MB). $upload_directory = dirname(__file__) . '/'.$user_id.'/'; //set upload directory if (!is_dir($upload_directory)) { mkdir($upload_directory, 0777, true); } for ($i = 0; $i < count($_FILES['images']['name']); $i++) { $number_of_file_fields++; if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not $number_of_uploaded_files++; if($_FILES['images']['size'] > $max_filesize){ echo "<b class='red'>Max file size is 5MB.</b><br/>"; $sz = true; } $ext = validate_extension($_FILES['images']['name'][$i]); if (($ext == true) && ($sz == true)){ $uploaded_files[] = $_FILES['images']['name'][$i]; if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . $_FILES['images']['name'][$i])) { $number_of_moved_files++; } }else { echo "<b class='red'>File extention error. Only .doc, .pdf, .jpg and .gif files are allowed. </b><br/>"; } } } if ($number_of_uploaded_files >= 1){ echo "Number of files submitted:<b class='red>".$number_of_uploaded_files."</b><br/>"; echo "Number of successfully uploaded files:<b class='red>".$number_of_moved_files."</b><br/><br/>"; echo "Uploaded File Name(s):<br/>" . implode('<br/>', $uploaded_files); } } As of now it results in every uploaded file returning the error "Max file size is 5MB." I have been toying around with form validation and have got to a sticking point in four areas that I am pretty sure are easier to do than I am finding! What I have so far works fine - once you start typing in a field, if it is invalid, then there is a message and some extra styling that is removed once it is valid. These are the functions for the four fields so far (there will be more, some required, some not). $('#username').on('keyup', function(){ var valid = /^[a-zA-Z0-9_-]{3,16}$/.test(this.value) && this.value.length; $('#regUsername .regAlert').html((valid?'':'Not Valid')); if(!valid){ $("#regUsername").addClass('bg-danger'); }else{ $("#regUsername").removeClass('bg-danger'); } }); $('#email').on('keyup', function(){ var valid = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/.test(this.value) && this.value.length; $('#regEmail .regAlert').html((valid?'':'Not Valid')); if(!valid){ $("#regEmail").addClass('bg-danger'); }else{ $("#regEmail").removeClass('bg-danger'); } }); $('#password').on('keyup', function(){ var valid = (/^(?=.*\d)(?=.*[a-zA-Z])[0-9a-zA-Z]{6,}$/).test(this.value) && this.value.length; $('#regPassword .regAlert').html((valid?'':'Not Valid')); if(!valid){ $("#regPassword").addClass('bg-danger'); }else{ $("#regPassword").removeClass('bg-danger'); } }); $('#password_confirm').on('keyup', function(){ var valid = (/^(?=.*\d)(?=.*[a-zA-Z])[0-9a-zA-Z]{6,}$/).test(this.value) && this.value.length; $('#regPassword2 .regAlert').html((valid?'':'Not Valid')); if(!valid){ $("#regPassword2").addClass('bg-danger'); }else{ $("#regPassword2").removeClass('bg-danger'); } }); What I am trying to do next is, if any of these fields are not valid, for the submit button to be disabled I can do by including if(!valid){ $('#registerSubmit').prop('disabled', true); }else{ $('#registerSubmit').prop('disabled', false); }in each function BUT if one is invalid, but the next is valid, then this overrides it and the button is clickable again. I have also tried setting a variable to true/false and the same happens. Plus, if all are valid, once the button is clicked, it needs to check for empty (required) fields and only submit if all fields have data. I am also guessing that they is a better way of writing this using a single keyup function and then placing each fields rules within that, but I have tried to wrap it all in a single function but got more in a mess. So, what I am looking for help with (bearing in mind there will be more fields, radio's, checkboxes and selects in the full form) is How can I streamline all of the functions into one to save on repeated code and to make it simple to add more fields in future How can I disable the submit button if ANY of the validations have failed How can I check for any empty required fields on submit button click and not process the form if any are found How can I check that #password and #password_confirm match on keyup from #password_confirm Thanks in advance for any advice Steve Having trouble figuring this out. 1) How can I check whether the user's input for a field is an integer with a value greater than 0? Was thinking of using regular expressions using 1-9 but then 10 might result in an error and that's not wanted. 2) For a field that's a drop-down, how can I have an error show if they choose the default option (value of "none") Thanks for the help. I am trying to validate username and password fields. I want to use preg match, but have little knowledge of this function. I want the password to only contain A-z 0-9 and with at least one letter and one number. Username needs to only include "A-z 0-9 _ -" no spaces in any of these. Here is what I have so far: $username= $_POST['username']; $password = $_POST['password']; $password2 = $_POST['password2']; if($password==$password2){ if( preg_match("[A-z0-9]", $password) || strlen($password)>6 // at least 7 chars || strlen($password)<26 // at most 20 chars ){$errors[] = 'Password must contain at least one number and letter plus be between 7-25 characters. May only contain alphanumeric characters, _ and .';} }else{$errors[] = 'Your Passwords did not Match';} if( preg_match("[A-z0-9_-]", $username) || strlen($username)>5 // at least 6 chars || strlen($username)<26 // at most 25 chars ){ $errors[] = 'Username must be 6-25 characters and contain only alphanumeric characters, _ and .'; } How do I Upload Multiple Files using a PHP form and script? 10 files at one time would be great. Ultimately I need a photo upload and management script. Here is my current single file upload form: <form action="upload.php" method="post" enctype="multipart/form-data"> <label for="file">Upload a Photo:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html> Here is the Php Script: <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 200000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]); echo "Stored in: " . "uploads/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?> |