PHP - Upload Validation
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! Similar TutorialsHi 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. 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; ?> I have code written for image uploading, but it doesn't allow multiple images on a single upload, and doesn't re-size. Anyone willing to share a good upload script that will do the following?: -Allow multiple image uploads (10+ per submission), -Re-size images on upload, and -Rename images. Thanks Brett Hi everyone, I have a page that i use to upload images to my website, i got a bit fed up of uploading one at a time so i decided to add multiple file fields to the form to upload multiple images at the same time. Im having a few problems, iv read up he http://www.php.net/manual/en/features.file-upload.multiple.php and it seems all i have to do is add [] to the form names to turn them into arrays. However when i come to upload the images, i keep getting the "$error[] = "Incorrect format!...." error from the code below. I cant seem to figure out what the problem is. Could anybody please point me in the right direction? <?php session_start(); $id = $_SESSION['id']; $connect = mysql_connect("localhost","leemp5_admin","p7031521"); mysql_select_db("leemp5_database"); $query = mysql_query("SELECT * FROM users WHERE id='$id'"); $row = mysql_fetch_assoc($query); $username = $row['username']; $submit = $_POST['submit']; $type = $_FILES['image']['type']; $size = $_FILES['image']['size']; $max_size = "1000"; $width = "100"; $height = "100"; $error = array(); function make_thumb($image_name,$filename,$new_width,$new_height) { $ext=getExtension($image_name); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $source_image=imagecreatefromjpeg($image_name); if(!strcmp("png",$ext)) $source_image=imagecreatefrompng($image_name); if(!strcmp("gif",$ext)) $source_image=imagecreatefromgif($image_name); $old_x=imageSX($source_image); $old_y=imageSY($source_image); $ratio1=$old_x/$new_width; $ratio2=$old_y/$new_height; if($ratio1>$ratio2) { $thumb_width=$new_width; $thumb_height=$old_y/$ratio1; } else { $thumb_height=$new_height; $thumb_width=$old_x/$ratio2; } $destination_image=ImageCreateTrueColor($thumb_width,$thumb_height); imagecopyresampled($destination_image,$source_image,0,0,0,0,$thumb_width,$thumb_height,$old_x,$old_y); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) { imagejpeg($destination_image,$filename); } if(!strcmp("png",$ext)) { imagepng($destination_image,$filename); } if(!strcmp("gif",$ext)) { imagegif($destination_image,$filename); } imagedestroy($destination_image); imagedestroy($source_image); } function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } if($submit) { $image=$_FILES['image']['name']; if ($image) { $filename = stripslashes($_FILES['image']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $error[] = "Incorrect format! Please make sure your image is a .jpg, .jpeg, .png or .gif file."; } else { $size=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); if ($sizekb > $max_size*1024) { $error[] = "Your image is too big! The maximum upload size is 1MB."; } else { $image_name=time().'.'.$extension; $newname="uploads/" . $username . "/images/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { $error[] = "There was an error uploading your image. Please try again!"; } else { $thumb_name='uploads/' . $username . '/images/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,$width,$height); } } } } else { $error[] = "Please select an image to upload!"; } if(empty($error)) { echo "Upload Successfully!<br />"; echo '<img src="'.$thumb_name.'">'; mysql_query("INSERT INTO images VALUES ('','$username','$image_name','','','','','uploads/$username/images/$image_name','uploads/$username/images/thumbs/thumb_$image_name','$type','$size')"); } else { echo implode($error); } } ?> <form method="post" enctype="multipart/form-data" action="upload_images.php"> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="submit" name="submit" value="Upload"> </form> Thanks 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 there We are hosting a web server that requires large files (100MB+) to be uploaded to it. We are using PHP upload scripts, and it is working, but we are getting complaints that the uploads are unreliable (some files fail to upload, with no error messages). I have been reading on various forums that FTP should rather be used for larger files, rather than HTTP. But from what I can see, there are some limitations, and I was wondering if there are any ways around these: - Using cURL would mean that the files would first be uploaded to a temp folder on the web server via HTTP, and then only sent via FTP. This defeats the purpose, because if it is already on the Web Server (which is hosted locally), then I might just as well move the file. - Using the built in FTP functionality of PHP, it appears that ones needs to know the full path of the source file. The users who are uploading files are accessing the Web server via a form in a browser, which will not give the PHP script the full path of the file to be uploaded. All we want is to have a reliable means for an end-user to access a site with a browser, fill in a form, choose a file to upload, and submit it. Additional functionality, like a progress bar, the ability to select multiple files and a resume option for failed uploads, would all be very nice. But the main concern is that the transfers be more reliable. Thanks for any advice. Mills I have made this script to upload to an ftp server. How do I get the script to try to restart the upload if it fails? (if if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) returns false) Code: [Select] <?php $file = 'file.wmv'; $remote_file = 'file.wmv'; // set up basic connection $conn_id = ftp_connect('ftp.eu.filesonic.com'); $ftp_user_name='username'; $ftp_user_pass='password'; // login with username and password $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); // upload a file if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) { echo "successfully uploaded $file\n"; } else { echo "There was a problem while uploading $file\n"; } // close the connection ftp_close($conn_id); ?> Can someone Help me I made a code for uploading files to database.. but how can i retrieve it? Is it possible to open the pdf file in browser? Im using XAMPP MySql.. SOMEONE HELP ME PLS. Hey Im trying to upload a pdf file into a blob in a database. This script worked to insert images and I made a few minor changes so that it could do the same for pdf files. Only when i run the script in a browser it says error unknown file format. I dont understand this because I do list pdf as a valid file format. The txt and the doc possible file uploads are just there to take up spots where jpeg and gif were in the picture script i have no intention of actually uploading those. The file i tested was yes a pdf so that cant be the issue. Heres the script. Code: [Select] <?php $db_host = 'localhost'; // don't forget to change $db_user = 'root'; $db_pwd = 'dbpassword'; $database = 'mydbname'; $table = 'lit_gallery'; // use the same name as SQL table $password = '123'; // simple upload restriction, // to disallow uploading to everyone if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($database)) die("Can't select database"); // This function makes usage of // $_GET, $_POST, etc... variables // completly safe in SQL queries function sql_safe($s){ if (get_magic_quotes_gpc()) $s = stripslashes($s); return mysql_real_escape_string($s);} // If user pressed submit in one of the forms if ($_SERVER['REQUEST_METHOD'] == 'POST'){ // cleaning title field $title = trim(sql_safe($_POST['title'])); if ($title == '') // if title is not set $title = '(empty title)'; // use (empty title) string if ($_POST['password'] != $password)// cheking passwors $msg = 'Error: wrong upload password'; else { if (isset($_FILES['book'])) { @list(, , $ftype, ) = getimagesize($_FILES['book']['tmp_name']); // Get file type. // We use @ to omit errors if ($ftype == 3) // cheking image type $ext="pdf"; // to use it later in HTTP header elseif ($ftype == 2) $ext="txt"; elseif ($imtype == 1) $ext="doc"; else $msg = 'Error: unknown file format'; if (!isset($msg)) // If there was no error { $data = file_get_contents($_FILES['book']['tmp_name']); $data = mysql_real_escape_string($data); // Preparing data to be used in MySQL query mysql_query("INSERT INTO {$table} SET ext='$ext', title='$title', data='$data'"); $msg = 'Success: pdf uploaded'; } } elseif (isset($_GET['title'])) // isset(..title) needed $msg = 'Error: file not loaded'; // to make sure we've using // upload form, not form // for deletion if (isset($_POST['del'])) // If used selected some photo to delete { // in 'uploaded images form' $id = intval($_POST['del']); mysql_query("DELETE FROM {$table} WHERE id=$id"); $msg = 'Book deleted'; } } } elseif (isset($_GET['show'])){ $id = intval($_GET['show']); $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(book_time), data FROM {$table} WHERE id=$id LIMIT 1"); if (mysql_num_rows($result) == 0) die('no image'); list($ext, $book_time, $data) = mysql_fetch_row($result); $send_304 = false; if (php_sapi_name() == 'apache') { // if our web server is apache // we get check HTTP // If-Modified-Since header // and do not send image // if there is a cached version $ar = apache_request_headers(); if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists ($ar['If-Modified-Since'] != '') && // not empty (strtotime($ar['If-Modified-Since']) >= $book_time)) // and grater than $send_304 = true; // image_time } if ($send_304) { // Sending 304 response to browser // "Browser, your cached version of image is OK // we're not sending anything new to you" header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304); exit(); // bye-bye } // outputing Last-Modified header header('Last-Modified: '.gmdate('D, d M Y H:i:s', $book_time).' GMT', true, 200); // Set expiration time +1 year // We do not have any photo re-uploading // so, browser may cache this photo for quite a long time header('Expires: '.gmdate('D, d M Y H:i:s', $book_time + 86400*365).' GMT', true, 200); // outputing HTTP headers header('Content-Length: '.strlen($data)); header("Content-type: application/{$ext}"); // outputing book echo $data; exit(); } ?> <head> <title>MySQL Blob Image Gallery Example</title> <link rel="stylesheet" type="text/css" href="test.css"/> </head> <html> <body> <?php if (isset($msg)) // this is special section for // outputing message { ?> <p style="font-weight: bold;"><?=$msg?><br><a href="<?=$PHP_SELF?>">reload page</a><!-- I've added reloading link, because refreshing POST queries is not good idea --></p> <?php } ?> <h1>Blob image gallery</h1> <h2>Uploaded images:</h2> <form action="<?=$PHP_SELF?>" method="post"> <!-- This form is used for image deletion --> <?php $result = mysql_query("SELECT id, book_time, title FROM {$table} ORDER BY id DESC"); if (mysql_num_rows($result) == 0) // table is empty echo '<ul><li>No images loaded</li></ul>'; else{ echo '<ul>'; while(list($id, $book_time, $title) = mysql_fetch_row($result)) { // outputing list echo "<li><input type='radio' name='del' value='{$id}'>"; echo "<a href='{$PHP_SELF}?show={$id}'>{$title}</a> – "; echo "<small>{$book_time}</small></li>"; } echo '</ul>'; echo '<label for="password">Password:</label><br>'; echo '<input type="password" name="password" id="password"><br><br>'; echo '<input type="submit" value="Delete selected">'; } ?> <html> <body> </form><h2>Upload new image:</h2><form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data"> <label for="title">Title:</label><br><input type="text" name="title" id="title" size="64"><br> <br> <label for="book">Book:</label><br><input type="file" name="book" id="book"><br> <br> <label for="password">Password:</label><br><input type="password" name="password" id="password"><br> <br><input type="submit" value="upload"></form> </body> </html> I am looking to upload an image or pdf file to my server an with this upload script below. It works well and uploads the images and the pdf file but for some reason i can open the image and view it but not the pdf file can someone please let me know why this is happening and show me what changes i need to make to get the script to work as i'm very new to PHP . thanks Quote Code: [Select] <?php $target = "images/"; $target = $target . basename( $_FILES['image']['name']); $company=$_POST['company']; $image=($_FILES['image']['name']); mysql_connect("localhost", "username", "password") or die(mysql_error()) ; mysql_select_db("testupload") or die(mysql_error()) ; mysql_query("INSERT INTO `table` (company, image) VALUES ('$company', '$image')") ; if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { echo "Sorry, there was a problem uploading your file."; } ?> I have absolutely no idea how to allow users to upload their own avatars and then have the file save as their user ID (uID), and if the uID already exists, then have it overwrite it. Hi all, i am new here, but i have a working upload php working inside a flash file..... It working perfectly fine with uploading file onto my website. But i would like to add some code in it. Example: if you upload a file through it, i would like it to say " Your file have successfully uploaded" but i want to add the code, if you upload the same image.extension and same size, it would like it to say "Error - File exist!" <?php session_start(); $Directory = "image/"; $DAT = "file/"; $datei=$_GET['datei']; $txt1=$_GET['txt1']; $ok="0"; if ($_SESSION['ko']=="1") { session_unset(); echo "&message=File ".$_SESSION['tempdatei']." u. Information Process!&"; }else{ session_unset(); echo "&message=Server Error or Error File exists!&"; } if ($_FILES['Filedata']) { if (preg_match("/^.*?\.(pdf|wav|mp3|mov|wmv|mpeg|exe|avi|mpg|rar|zip|flv|xls|ppt|doc|mdb|txt|jpg|gif|png|swf|jpeg)$/si",$_FILES['Filedata']['name'])) { if($_FILES['Filedata']['size'] > 0 && $_FILES['Filedata']['size'] < 10485760) { $uploadfile = $Directory.basename($_FILES['Filedata']['name']); if (!file_exists($uploadfile)) { move_uploaded_file($_FILES['Filedata']['tmp_name'], $uploadfile); $_SESSION['ko']=$ok; $_SESSION['tempdatei']=$datei; }else{ echo "&message=check me out!&"; } chmod( $Directory. basename( $_FILES['Filedata']['name']),0644); if (!chmod( $Directory. basename( $_FILES['Filedata']['name']),0644)) { fail("The permissions failed to set to 0644."); } $tx=$DAT.$datei.".txt"; $fp= fopen($tx,'w+'); fwrite($fp,$txt1); fclose($fp); $ok="1"; }}} ?> Hello... I have some simple code but no ideas for upload another image?? PHP stores image name in database but there is no second picture uploaded in the images/ folder. Pls help. Thanks if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 2000000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "<strong>Slika:</strong> " . $_FILES["file"]["name"] . "<br />"; echo "<strong>Format slike:</strong> " . $_FILES["file"]["type"] . "<br />"; echo "<strong>Velicina:</strong> " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "<strong>Temp file:</strong> " . $_FILES["file"]["tmp_name"] . "<br />"; // here is mistake??? move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . $_FILES["file"]["name"]); // $sql="INSERT INTO test (name, something, slika, slika2) VALUES ('".$_POST['name']."', '".$_POST['something']."', '".$_FILES['file']['name']."', '".$_FILES['slika1']['name']."')"; if (mysql_query($sql)) { echo "Sucess"; } else { echo "Error" . mysql_error(); } } } else { echo "Invalid file"; } ?> What i have here is a code for uploading files to specified folder. I have a problem which i cant found in code. All uploaded files get a new name with many numbers. I dont want this because i cant collect files for gallery because filenames are different as uploaded ones. Example: I have a file biggreen.gif on my computer. I upload it trough this form, and when i check that file in folder i uploaded to, the name is 1299616037_biggreen.gif. Help me please. Code: [Select] <?php //Load the settings require_once("settings.php"); $message = ""; //Has the user uploaded something? if(isset($_FILES['file'])) { $target_path = Settings::$uploadFolder; $target_path = $target_path . time() . '_' . basename( $_FILES['file']['name']); //Check the password to verify legal upload if($_POST['password'] != Settings::$password) { $message = "Invalid Password!"; } else { //Try to move the uploaded file into the designated folder if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) { $message = "The file ". basename( $_FILES['file']['name']). " has been uploaded"; } else{ $message = "There was an error uploading the file, please try again!"; } } //Clear the array unset($_FILES['file']); } if(strlen($message) > 0) { $message = '<p class="error">' . $message . '</p>'; } /** LIST UPLOADED FILES **/ $uploaded_files = ""; //Open directory for reading $dh = opendir(Settings::$uploadFolder); //LOOP through the files while (($file = readdir($dh)) !== false) { if($file != '.' && $file != '..') { $filename = Settings::$uploadFolder . $file; $parts = explode("_", $file); $size = formatBytes(filesize($filename)); $added = date("m/d/Y", $parts[0]); $origName = $parts[1]; $filetype = getFileType(substr($file, strlen($file) - 3)); $uploaded_files .= "<ul class=\"list\"><li class=\"$filetype\"><a href=\"$filename\">$origName</a> $size - $added</li></ul>\n"; } } closedir($dh); if(strlen($uploaded_files) == 0) { $uploaded_files = "<ul class=\"list\"><li><em>No files found</em></li></ul>"; } function getFileType($extension) { $images = array('jpg', 'gif', 'png', 'bmp'); $docs = array('txt', 'rtf', 'doc'); $apps = array('zip', 'rar', 'exe'); if(in_array($extension, $images)) return "Images"; if(in_array($extension, $docs)) return "Documents"; if(in_array($extension, $apps)) return "Applications"; return ""; } function formatBytes($bytes, $precision = 2) { $units = array('B', 'KB', 'MB', 'GB', 'TB'); $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = min($pow, count($units) - 1); $bytes /= pow(1024, $pow); return round($bytes, $precision) . ' ' . $units[$pow]; } ?> I need help modifying this so that the picture that I upload will be submitted to the database and be uploaded. I have been trying to make it work for over an hour now. please help if you can. thanks. Code: [Select] <?php if($_post['submit']){ include_once "connect_to_mysql_1.php"; $name=$_POST['name']; $uploaddir = '/images/'; $picture = '$name.jpg'; $target_path = "/images/"; $file = $uploaddir . basename($_FILES['product1']['name']); move_uploaded_file($_FILES["product1"]["tmp_name"], "images/" . $_FILES["product1"]["name"]); echo "Stored in: " . "images/" . $_FILES["product1"]["name"]; if (move_uploaded_file($_FILES['product1']['tmp_name'], $file)) { echo "success"; $sql = "INSERT INTO products(link, name) VALUES('$file', '$name')"; $rs = mysql_query($sql) or die ("Problem with the query: $sql<br>" . mysql_error()); echo mysql_error(); } else { echo "error ".$_FILES['product1']['error']." --- ".$_FILES['product1']['tmp_name']." %%% ".$file."($size)"; $picture_name = pathinfo($picture, PATHINFO_FILENAME); }} ?> <!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" /> <meta name="description" content="Thank you for your interest in Old Mil-custom Woodworking. We have hired Aaron's Web Design to build a brand new website for us! Thank you for your patience!"> <meta name="keywords" content="Web, Design, web design, old, mil, oldmil, old mil, wood, woodwork, work, working, woodworking, woodworker, woodworkers, custom"> <title>Our Products-Old Mil</title> <style type="text/css"> <!-- body { font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif; background: #42413C; margin: 0; padding: 0; color: #000; background-image: url(../images/background.png); } /* ~~ Element/tag selectors ~~ */ ul, ol, dl { /* Due to variations between browsers, it's best practices to zero padding and margin on lists. For consistency, you can either specify the amounts you want here, or on the list items (LI, DT, DD) they contain. Remember that what you do here will cascade to the .nav list unless you write a more specific selector. */ padding: 0; margin: 0; } h1, h2, h3, h4, h5, h6, p { margin-top: 0; /* removing the top margin gets around an issue where margins can escape from their containing div. The remaining bottom margin will hold it away from any elements that follow. */ padding-right: 15px; padding-left: 15px; /* adding the padding to the sides of the elements within the divs, instead of the divs themselves, gets rid of any box model math. A nested div with side padding can also be used as an alternate method. */ font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 100%; border-top-width: thick; border-right-width: thick; border-bottom-width: thick; border-left-width: thick; } a img { /* this selector removes the default blue border displayed in some browsers around an image when it is surrounded by a link */ border: none; } /* ~~ Styling for your site's links must remain in this order - including the group of selectors that create the hover effect. ~~ */ a:link { color: #42413C; text-decoration: underline; /* unless you style your links to look extremely unique, it's best to provide underlines for quick visual identification */ } a:visited { color: #6E6C64; text-decoration: underline; } a:hover, a:active, a:focus { /* this group of selectors will give a keyboard navigator the same hover experience as the person using a mouse. */ text-decoration: none; } /* ~~this fixed width container surrounds the other divs~~ */ .container { width: 960px; background: #FFF; margin: 0 auto; /* the auto value on the sides, coupled with the width, centers the layout */ } /* ~~ the header is not given a width. It will extend the full width of your layout. It contains an image placeholder that should be replaced with your own linked logo ~~ */ .header { background: #ADB96E; font-size: xx-large; font-family: "Comic Sans MS", cursive; height:137px; } /* ~~ These are the columns for the layout. ~~ 1) Padding is only placed on the top and/or bottom of the divs. The elements within these divs have padding on their sides. This saves you from any "box model math". Keep in mind, if you add any side padding or border to the div itself, it will be added to the width you define to create the *total* width. You may also choose to remove the padding on the element in the div and place a second div within it with no width and the padding necessary for your design. You may also choose to remove the padding on the element in the div and place a second div within it with no width and the padding necessary for your design. 2) No margin has been given to the columns since they are all floated. If you must add margin, avoid placing it on the side you're floating toward (for example: a right margin on a div set to float right). Many times, padding can be used instead. For divs where this rule must be broken, you should add a "display:inline" declaration to the div's rule to tame a bug where some versions of Internet Explorer double the margin. 3) Since classes can be used multiple times in a document (and an element can also have multiple classes applied), the columns have been assigned class names instead of IDs. For example, two sidebar divs could be stacked if necessary. These can very easily be changed to IDs if that's your preference, as long as you'll only be using them once per document. 4) If you prefer your nav on the right instead of the left, simply float these columns the opposite direction (all right instead of all left) and they'll render in reverse order. There's no need to move the divs around in the HTML source. */ .sidebar1 { float: left; width: 180px; background: #EADCAE; padding-bottom: 10px; height:770px } .content { padding: 10px 0; width: 780px; float: left; } /* ~~ This grouped selector gives the lists in the .content area space ~~ */ .content ul, .content ol { padding: 0 15px 15px 40px; /* this padding mirrors the right padding in the headings and paragraph rule above. Padding was placed on the bottom for space between other elements on the lists and on the left to create the indention. These may be adjusted as you wish. */ } /* ~~ The navigation list styles (can be removed if you choose to use a premade flyout menu like Spry) ~~ */ ul.nav { list-style: none; /* this removes the list marker */ border-top: 4px solid #666; /* this creates the top border for the links - all others are placed using a bottom border on the LI */ margin-bottom: 4px solid #666; /* this creates the space between the navigation on the content below */ } ul.nav li { border-bottom: 4px solid #666; /* this creates the button separation */ } ul.nav a, ul.nav a:visited { /* grouping these selectors makes sure that your links retain their button look even after being visited */ padding: 5px 5px 5px 15px; display: block; /* this gives the link block properties causing it to fill the whole LI containing it. This causes the entire area to react to a mouse click. */ width: 160px; /*this width makes the entire button clickable for IE6. If you don't need to support IE6, it can be removed. Calculate the proper width by subtracting the padding on this link from the width of your sidebar container. */ text-decoration: none; background-image: url(/images/slat.png); } ul.nav a:hover, ul.nav a:active, ul.nav a:focus { /* this changes the background and text color for both mouse and keyboard navigators */ background-image: url(/images/slat1.png); color: #000; } /* ~~ The footer ~~ */ .footer { padding: 10px 0; background: #CCC49F; position: relative;/* this gives IE6 hasLayout to properly clear */ clear: both; /* this clear property forces the .container to understand where the columns end and contain them */ } /* ~~ miscellaneous float/clear classes ~~ */ .fltrt { /* this class can be used to float an element right in your page. The floated element must precede the element it should be next to on the page. */ float: right; margin-left: 8px; } .fltlft { /* this class can be used to float an element left in your page. The floated element must precede the element it should be next to on the page. */ float: left; margin-right: 8px; } .clearfloat { /* this class can be placed on a <br /> or empty div as the final element following the last floated div (within the #container) if the #footer is removed or taken out of the #container */ clear:both; height:0; font-size: 1px; line-height: 0px; } .container .sidebar1 .nav li a div { color: #000; padding: 0px; } #apDiv1 { position:relative; left:160px; top:-130px; width:772px; height:88px; z-index:1; } #ap12 { position:relative; top:-50px; left:00px; width:772px; height:88px; z-index:1; } #apDiv2 { position:relative; left:30px; top:30px; width:270px; height:270px; z-index:2; background-color: #CCCCCC; } --> </style></head> <body> <div class="container"> <div class="header"><a href="#"><img src="../images/Old Mil LOGO.jpg" alt="Insert Logo Here" name="Insert_logo" width="122" height="137" id="Insert_logo" style="background: #C6D580; display:block;" /> <div id="apDiv1"><span class="header">Old Mil<br /> Custom Woodworking, Inc. </span></div></a><!-- end .header --></div> <div class="sidebar1"> <ul class="nav"> <li><a href="/Products"> <div font color="black">Products</div></a></li> <li><a href="#"> <div font color="black">Coming Soon</div></a></li> <li><a href="#"> <div font color="black">Coming Soon</div></a></li> <li><a href="#"> <div font color="black">Coming Soon</div></a></li> </ul> <p> </p> <!-- end .sidebar1 --></div> <div class="content"> <h1> </h1> <form action="products.php" method="post" enctype="multipart/form-data" name="form1" id="form1"> <div id="apDiv2"> <p><label for="product1"></label> <label for="name">name</label> <input type="text" name="name" id="name" /> </p> <p>Picture <input type="file" name="product1" id="product1" /> </p> <p> <label for="Caption1">Caption</label> <input type="text" name="Caption1" id="Caption1" /> </p></div> <input name="submit" type="submit" value="Upload" /> </form> <h1><br /> <br /><br /><br /><br /><br /> </h1> <!-- end .content --></div> <p> </p> <p> </p> <div class="footer"> <p>Website made by <a href="http://www.aaronswebdesign.infiniteserve.com">Aaron's Web Design</a></p> <!-- end .footer --></div> <!-- end .container --></div> </body> </html> Hello all, I am using this script to upload file to FTP through php code, but its giving me FTP upload has failed! Can you help? Thanks <html> <head> <title>Untitled Document</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> <form action="upload.php" method="post" enctype="multipart/form-data" name="form1" > <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="14%">server name </td> <td width="75%"><input name="server" type="text" id="server">Write in the format "ftp.servername.com" </td> <td width="11%"> </td> </tr> <tr> <td>user name </td> <td><input name="username" type="text" id="username"></td> <td> </td> </tr> <tr> <td>password</td> <td><input name="password" type="password" id="password"></td> <td> </td> </tr> <tr> <td>File name </td> <td><input type="file" name="file"></td> <td> </td> </tr> <tr> <td><input type="submit" name="Submit" value="Upload"></td> <td> </td> <td> </td> </tr> </table> </form> </body> </html> "upload.php" <html> <head> <title>Untitled Document</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> <?php $ftp_server=$_POST['server']; $ftp_user_name=$_POST['username']; $ftp_user_pass=$_POST['password']; $source_file=$_FILES['file']['name'];// retrieve name of the file to be uploaded $destination_file=$source_file; // make a connection to the ftp server $conn_id = ftp_connect($ftp_server); // login with username and password $login_result = ftp_login($conn_id , $ftp_user_name , $ftp_user_pass); // check connection if((!$conn_id)||(!$login_result)){ echo "FTP connection has failed!" ; echo "Attempted to connect to $ftp_server for user $ftp_user_name" ; exit; }else{ echo "Connected to $ftp_server, for user $ftp_user_name" ; } // upload the file $upload = ftp_put($conn_id,$destination_file,$source_file,FTP_ASCII ); // check upload status if(!$upload){ echo "FTP upload has failed!" ; }else{ echo "Uploaded $source_file to $ftp_server as $destination_file" ; } // close the FTP stream ftp_close($conn_id); ?> </body> </html> hi there, Im running into a dead brainer here. I want to allow users to upload an article, and in this article have text and an image. So the article will have a title, image and content. Hard to describe, but my problem is this: Uploading these from a form, so that in the database they appear in just one row together, so the image and text is linked to the title of the article. How could I go about doing this, as the ID's of the articles will automatically be generated, im not sure how i could code is so that all of these are specific to their id's. I have this image upload script already from another use site i have developed and have start to re work it, but wondering how i could adapt this with a form with more than just the image upload in it. Sorry if sounds bit complicated, hard to word what im thinking thanks in advance <?php require("include/conn.php"); include "include/session.php"; // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file['type'], $valid_types)) return 1; return 0; } function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } $TARGET_PATH = "images/"; // Get POSTed variables $image = $_FILES['image']; $image['name'] = mysql_real_escape_string($image['name']); $TARGET_PATH .= $image['name']; // Make sure all the fields from the form have inputs if ($image['name'] == "" ) { $_SESSION['error'] = "All fields are required"; header("Location: addvox.php"); exit; } // Verify file is an image if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header("Location: addvox.php"); exit; } // move file into the directory and the path name into the database if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { $sql = "UPDATE vox SET image = '" . $image['name'] . //where id = 'VOX_ID'; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: user-page.php"); exit; } else { $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; exit; } ?> Hello everyone.i'm beginner in programming.How to make page that user can upload their own image.. my database table:product product_id (PK) product_price product_name product_picture anyone can help me..thank for advance:) I need to do an upload a file size up to 100MB. I tried editing the .htaccess but it seem not to be working either. Here is my .htaccess code: php_flag safe_mode off php_value max_execution_time 1000 php_value session.gc_maxlifetime 14000 php_value output_buffering on php_value upload_max_filesize 104857600 php_value post_max_size 104857600 Is there anything wrong with this? Do i need to edit anything from the processpage? Here is the size limit i define in my processpage: define ("MAX_SIZE","104857600"); Is this right? Please help me out with this. Thank you in ADVANCE!! |