PHP - Help With Adding File Size Limit To Upload Form
I'm trying to add a file size limit to my upload form-code (below)
Similar TutorialsHi guys, with code below i can upload pictures to database, however i need to limit the file upload. I have this code done with help of php freak forum and i am a newbie so can u help me please? thanks in advance if (isset($_POST['register']) && $_POST['register']){ //image1 $nameone=$_FILES['myfileone']['name']; if ($nameone) { $dst_filename = resize_upload_image($_FILES['myfileone'], "images/"); if ($dst_filename !== false) { extract($dst_filename); $image1 = mysql_query ("INSERT INTO img SET image='$img_filename', thumb='$thumb_filename', refimage='$reference'"); } } } ?> <form action='' method='POST' enctype='multipart/form-data'> <p>File: <input type='file' name='myfileone'> Hi, I wanted to realize an upload form for a max. file size of 5GB. Don't ask me why, but my friend needs that. Now I set up a webserver with ISPConfig and this interface provides a lot of features including openbasedir. Uploading files up to 80MB is no problem but choosing bigger files causes the following errors: [Mon Sep 12 23:39:03 2011] [warn] [client XX.XX.XXX.XXX] mod_fcgid: stderr: PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 97477678 bytes) in Unknown on line 0, referer: hxxp://www.mydomain.com/kontakt-upload.html [Mon Sep 12 23:39:03 2011] [error] [client XX.XX.XXX.XXX] Premature end of script headers: file-uploader.php, referer: hxxp://www.mydomain.com/kontakt-upload.html [Mon Sep 12 23:39:03 2011] [warn] [client XX.XX.XXX.XXX] (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server, referer: hxxp://www.mydomain.com/kontakt-upload.html [Mon Sep 12 23:39:03 2011] [error] [client XX.XX.XXX.XXX] Premature end of script headers: index.php, referer: hxxp://www.mydomain.com/kontakt-upload.html As I see the upload get's buffered in the PHP Memory area instead directly to the harddrive. How could I fix that? Hi Chaps, I'm using readfile to force the download of a file: set_time_limit(0); $file = 'monkey.gif'; if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); exit; } flush(); And this works fine, however, I do have some software installation files that could be downloaded (these are in excess of 280Mb). I have checked php.ini: Quote memory_limit = 128M post_max_size = 300M But Internet Explorer hangs and then crashes. Is there a way to allow big files to download using this method, or is there another way of forcing the download, without php 'reading' the file first? I'm guessing that the problem lies with the memory_limit being smaller than the file size. Is it a good idea to increase the memory_limit to eg. 280Mb? Cheers I have a simple script which records search terms and writes them to an external file. I would like to limit this file size. The Use: I have a search page where people can search for PDF files. I would like to have a 'cloud tag' or list of the most recent terms searched at the bottom of the page. Here is my script which works beautifully: <?php $pattern = "/filetype:(\w+)/"; // filteype:(wildcard for word) to grab the file extension along with the word filetype: if ( $_GET['q'] == "" ) { $term = ""; } else { $term = preg_replace("$pattern", '', $_GET['q']); // get rid of the filetype parameter } $searched = $term . ", "; $fopen = fopen("searched.html", "a"); fwrite($fopen, $searched); fclose($fopen); ?> The above code grabs the search term when the SERP page is opened, and writes it to a file. I will later use phpInclude to put the contents of that file on the bottom of my search engine page. The problem is that after a million searches, this file will be huge! Question: How can I limit the file size and organize these search terms so that the most recent ones appear on the page? 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." Unless buffer overflows or breaking out of code to perform a new command are problems that have been solved.... I am trying to figure out the proper PHP method for setting a boundary on a variable within a script. I have this variable $name which is fed a value from $_POST['name'] from a form field. Now this form field is limited in the HTML to accept only 20 characters, but someone could easily edit the form or outgoing post data. So I want to know how to limit the variable size in the script. In other languages it could be something like this: var name(20). So how do I do that in PHP? I've got a basic form for users on the site to fill out a form and upload a single image which is resized and saved to a directory on the server. I've tried the form numerous times and with images usually under 1MB the form successfully submits, data is queried and the image uploaded is resized and saved. However, recently I tried uploading larger sized images (1.2mb, 2.4mb, 3mb) and the script would seem to break. It wouldn't query any information, save any images, etc. If you check my code attached, I have errors ready to output at all levels and not even any errors show up. When I hit submit after attempting to upload a larger file usually over 1MB, the page refreshes back to PHP_SELF as if it submitted but returns absolutely no message, alert or error and the form which was on the page is now gone. I checked my PHP.ini file and my max file size upload is set at 32mb. Is there anything else with file size restrictions that I could be missing that is allowing this script to crash without even sending me any errors? if(!empty($_POST['submitFeature'])) { // set variables $featurename = mysql_real_escape_string($_POST['featurename']); $featuredesc = mysql_real_escape_string($_POST['featuredesc']); $name = mysql_real_escape_string($_POST['name']); $email = mysql_real_escape_string($_POST['email']); $email2 = mysql_real_escape_string($_POST['email2']); $age = mysql_real_escape_string($_POST['age']); $city = mysql_real_escape_string($_POST['city']); $state = mysql_real_escape_string($_POST['state']); $src = $_FILES['featureupload']['tmp_name']; $featuresize = $_FILES['featureupload']['size']; $limitsize = 1000000; // 1 - A. REQUIRED FIELDS VERIFICATION if(!empty($featurename) && !empty($name) && !empty($email) && !empty($email2) && !empty($city) && !empty($state) && ($email == $email2) && !empty($_FILES['featureupload']['tmp_name']) && ($featuresize < $limitsize)) { // 2 - A. SANITIZE AND VALIDATE EMAIL $email = filter_var($email, FILTER_SANITIZE_EMAIL); if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { print ' <ul class="errorlist"> <li class="alert">Error!</li> <li>Invalid Email Address</li> </ul> '; } else { // 3 - A. VALIDATE IMAGE EXTENSION // verify that image uploaded is proper extension $fname = strtolower($_FILES['featureupload']['name']); // grab uploaded image's filename and lowercase the extension (ex: .JPG) if(preg_match('/[.](jpg)|(gif)|(png)$/', $fname)) { // set image variables $path_image = 'submissions/'; $final_width_of_image = 550; $randomappend=rand(0000,9999); // generate random number to append to filename $src = $_FILES['featureupload']['tmp_name']; // grab the src for where the image is temporarily held $filefull = $randomappend . $fname; // initiate new file name for submission's full image $target = $path_image . $filefull; // set variable for submission image's new location with appended name $path_image_thumb = 'submissions/thumbs/'; $final_width_of_thumb = 166; $final_height_of_thumb = 120; $filethumb = $randomappend . $fname; // initiate new file name for submission's thumbnail $target_thumb = $path_image_thumb . $filethumb; // set variable for thumbnail's new location with appended name move_uploaded_file($src, $target); if(preg_match('/[.](jpg)$/', $filefull)){ $img = imagecreatefromjpeg($path_image . $filefull); } else if (preg_match('/[.](gif)$/', $filefull)){ $img = imagecreatefromgif($path_image . $filefull); } else if (preg_match('/[.](png)$/', $filefull)){ $img = imagecreatefrompng($path_image . $filefull); } // FULL SIZE IMAGE $ox = imagesx($img); $oy = imagesy($img); $imgx = $final_width_of_image; $imgy = floor($oy * ($final_width_of_image / $ox)); $imgm = imagecreatetruecolor($imgx, $imgy); imagecopyresampled($imgm, $img, 0,0,0,0,$imgx,$imgy,$ox,$oy); if(!file_exists($path_image)){ if(!mkdir($path_image)){ die("There was a problem."); } } imagejpeg($imgm, $path_image . $filefull, 80); // END FULL SIZE IMAGE // THUMBNAIL $tox = imagesx($img); $toy = imagesy($img); $tx = $final_width_of_thumb; $ty = $final_height_of_thumb; $tm = imagecreatetruecolor($tx, $ty); imagecopyresampled($tm, $img, 0,0,0,0,$tx,$ty,$tox,$toy); if(!file_exists($path_image_thumb)){ if(!mkdir($path_image_thumb)){ die("There was a problem."); } } imagejpeg($tm, $path_image_thumb . $filethumb, 80); // END THUMBNAIL // query the actual post forms $q = "INSERT INTO submissions (id, name, age, email, city, state, country, featurename, featuredesc, featureimg, featurethumb, postdate, approved) VALUES ('', '$name', '$age', '$email', '$city', '$state', '', '$featurename', '$featuredesc', '$target', '$target_thumb', NOW(), 'NO')"; $r = mysql_query($q); if($r) { echo '<script language="JavaScript">'; echo 'alert("Successfully added a submission.")'; echo '</script>'; } else { echo '<script language="JavaScript">'; echo 'alert("Submission was not added. Please try again.")'; echo '</script>'; } } else { echo '<script language="JavaScript">'; echo 'alert("Unacceptable image extension.")'; echo '</script>'; } // 3 - B. VALIDATE IMAGE EXTENSION } // 2 - B. END SANITIZE AND VALIDATE EMAIL // 1 - B. END REQUIRED FIELDS VERIFICATION } else { print ' <ul class="errorlist"> <li class="alert">Please fill out the required fields.</li> '; if (empty($name)) { echo ' <li>* Full Name</li>' . "\n"; $errorname = 'TRUE'; } if (empty($email)) { echo ' <li>* Email</li>' . "\n"; $erroremail = 'TRUE'; } if (empty($email2)) { echo ' <li>* Confirm Email</li>' . "\n"; $erroremail2 = 'TRUE'; } if (empty($city)) { echo ' <li>* City</li>' . "\n"; $errorcity = 'TRUE'; } if (empty($state)) { echo ' <li>* State</li>' . "\n"; $errorstate = 'TRUE'; } if ($email != $email2) { echo ' <li>* Emails do not match.</li>' . "\n"; } if (empty($_FILES['featureupload']['tmp_name'])) { echo ' <li>* You did not upload a feature.</li>' . "\n"; $errorfile = 'TRUE'; } if (empty($featurename)) { echo ' <li>* Feature Name</li>' . "\n"; $errorfeature = 'TRUE'; } if ($featuresize >= $limitsize) { echo ' <li>* File size is too large.</li>' . "\n"; } print ' </ul> '; } // 1 - B. END REQUIRED FIELDS ERROR CODES } how to put code for check file size before upload in the if issertfile .the file is in format pdf or docs $targetDirg= "folder/pda-semakan/gambar/"; if(isset($_FILES['gambar'])){ $fileNameg = $_FILES['gambar']['name']; $targetFilePathg = $targetDirg . $fileNameg; //$main_tmp1 = $_FILES['surat']['tmp_name']; $moveg =move_uploaded_file($_FILES["gambar"]["tmp_name"], $targetFilePathg); }
Hi: I have a site hosted (shared) on 1and1.com hosting, and they seem to have a file upload limit of 2MB. Is there a way to overwrite this? I have been trying a .htaccess and php.ini file, but can't get it to work. The folder with the upload form is called "admin," in the ROOT of the site. Been trying (in both the ROOT and the "admin" folder): php.ini Code: [Select] ; Maximum size of POST data that PHP will accept. post_max_size = 8M ; Maximum allowed size for uploaded files. upload_max_filesize = 8M ini_set('memory_limit','128M'); .htaccess (in both the ROOT and the "admin" folder): Code: [Select] php_value memory_limit 24M That is all the code in each file - am I missing some code? Can this be done? Thank you. Can someone help me add a filter to my script that reads txt files from subfolders, I want it to only read txt files that are <= a certain KB size Code: [Select] 1.<?php 2.set_time_limit(0); // set unlimited execution time 3. 4. 5.$base_folder = $_POST['base_folder']; 6.$article_to_capture = (int)$_POST['article_to_capture']; 7. 8.$words = explode(',', $_POST['words']); 9. 10. 11.// print_r($words); die(''); 12. 13. 14.if(!is_dir($base_folder)) 15. die('Invalid base folder. Please go <a href="step1.php"><strong>back</strong></a> and enter correct folder.'); 16. 17.?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 18.<html> 19.<head> 20.<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 21.<title>Artcle Scraper Step 2</title> 22.<style type="text/css"> 23.<!-- 24.body { 25. font-family: Verdana, Arial, Helvetica, sans-serif; 26. font-size: 12px; 27. color: #333333; 28.} 29.--> 30.</style> 31.</head> 32. 33.<body> 34.<h2>Step 2 : Processing the content of the folder. </h2> 35.<table width="100%" border="0" cellpadding="2" cellspacing="1" bgcolor="#CCCCCC"> 36. <tr bgcolor="#FFFFFF"> 37. <th width="10%"> </td> 38. <th width="30%">BASE FOLDER NAME</td> 39. <th width="50%"> <?php echo $base_folder;?></td> 40. <th width="10%"> </td> 41. </tr> 42.<?php 43. 44.$subfolder_arr = scandir($base_folder); 45. 46.//print_r($arr1); 47. 48.$total_subfolders = sizeof($subfolder_arr); 49.$subfolder_count = 0; 50.$file_count = 0; 51.$report = ""; 52. 53.$fp = fopen('articles.csv', 'w+'); 54. 55.for($i=0; $i< $total_subfolders; $i++){ 56. $file_name = $subfolder_arr[$i]; 57. 58. if($file_name=='.'||$file_name=='..') 59. continue; 60. 61. $sub_folder_name = $base_folder ."\\". $file_name; 62. $file_type = is_dir($sub_folder_name) ? 'dir' : 'file'; 63. if($file_type=='dir'){ 64. $sub_folder_count++; 65. $rpeort .= "Processing folder $sub_folder_count $sub_folder_name \r\n"; 66. $msg = "Processing folder $sub_folder_count $sub_folder_name \r\n"; 67.?> 68. <tr bgcolor="#FFFFFF"><td> </td><td colspan="2"> 69. <?php echo $msg;?> 70. </td><td> </td></tr> 71. <tr bgcolor="#FFFFFF"><td> </td><td colspan="2"> 72. <table width="90%" cellpadding="0" cellspacing="0" border="1" bordercolorlight="#0000FF"> 73.<?php 74. // process sub folder 75. $column1 = $file_name; 76. $column2 = '{'; 77. $column3 = '{'; 78. $first = true; 79. $files_arr = scandir($sub_folder_name); 80. $article_processed =0; // article_processed in current sub folder 81. foreach($files_arr as $key=>$val){ 82. 83. if(is_file($sub_folder_name.'\\'.$val) ) 84. { if( substr($val,-4)=='.txt' ) 85. { 86. $article_processed++; 87. 88. if($article_to_capture==0 || $article_processed <= $article_to_capture ){ 89. 90. if($first==true) $first=false; 91. else 92. { $column2 .= '|'; $column3 .= '|'; } 93. 94. // read file get title and body 95. $file_content = file($sub_folder_name.'\\'.$val); 96. $file_title = rtrim($file_content[0]); 97. 98. $file_content[0] = ''; 99. 100. $file_arr_size = sizeof($file_content); 101. $words_arr_size = sizeof($words); 102. $t=1; 103. while($t < $file_arr_size){ 104. $file_content[$t] = rtrim($file_content[$t]); 105. //echo $file_content[$t]; 106. //die('inside'); 107. if( $words_arr_size>0 ){ 108. //die('inside'); 109. $temp = str_replace($words, "", $file_content[$t]); 110. $file_content[$t] = $temp; 111. } 112. $t++; 113. //if($t>=3) die('aa'); 114. } 115. $file_body = implode('',$file_content); 116. 117. $column2 .= $file_title; 118. $column3 .= $file_body; 119. 120. ?> 121. <tr><td> 122. <?php //print_r($files_arr); 123. echo $val ."\r\n"; 124. ?> 125. </td></tr> 126. <?php 127. } //end if .txt 128. } // article processed 129. } // end if is_file 130. } // end foreach 131.?> 132.</table> 133.</td><td> </td></tr> 134.<?php $column2 .= '}'; 135. $column3 .= '}'; 136. 137. // write to csv / excel file 138. $erro = fputcsv ($fp, array($column1,$column2,$column3) ); 139. 140. } //end if filetype 141. else{ 142. 143. } 144.} // end for 145. 146.fclose($fp); 147. 148.?> <tr bgcolor="#FFFFFF"> 149. <td> </td> 150. <td colspan=""> File Generated. 151. Download it <a href="articles.csv" target="_blank">HERE</a></td> 152. <td> </td> 153. </tr> 154.</table> 155.</body> 156.</html> Hello, I am making an upload script and I want to restrict all file types except png, jpg, and gif. I can't seem to figure it out and help would be appreciated!! <?php $target = "images/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition if ($uploaded_size > 230000) { echo "Your file is too large.<br>"; $ok=0; } if (!($uploaded_type=="image/gif")) { echo "You may only upload GIF 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 "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else { echo "Sorry, there was a problem uploading your file."; } } ?> Hey guys!
I'm trying to add an upload feature to my contact form. I had one before that simply added the image under the text in the email not as an actual attachment and it was pretty easy but I lost the code and can’t seem to find it again. But I seem to be having a problem finding a form that can help me add this. As of now the code in HTML has the upload but the PHP doesn’t at all.
If anyone could help me add the rest of the PHP code I'd really appreciate it!
HTML:
<form name="htmlform" method="post" action="oc.php"><label for="fname"><p>Full Name:</p></label> <input type="text" name="fname" maxlength="50" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td valign="top"> <label for="phone"> <p>Phone Number: </p></label> <input type="text" name="phone" maxlength="50" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td valign="top"> <label for="email"> <p> Email Address: </p></label> <input type="text" name="email" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> </tr> <tr> <td> <h4>DELIVERY INFORMATION:</h4> <label for="address"> <p>Address: </p></label> <input type="text" name="address" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="city"> <p>City: </p></label> <input type="text" name="city" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="state"> <p>State: </p></label> <input type="text" name="state" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="zip"> <p>Zip Code: </p></label> <input type="text" name="zip" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <h4>INFORMATION:</h4> <label for="first"> <p>First Name: </p></label> <input type="text" name="first" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="last"> <p>Last Name: </p></label> <input type="text" name="last" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="rec"> <p>Recommendation ID Number: </p></label> <input type="text" name="rec" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="exp"> <p>Recommendation Experation Date: </p></label> <input type="text" name="exp" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="doc"> <p>Doctors Name: </p></label> <input type="text" name="doc" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="docphone"> <p>Doctors Phone Number: </p></label> <input type="text" name="docphone" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="ver"> <p>Verification Website: </p></label> <input type="text" name="ver" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> </td> </tr> <tr> <td valign="top"><label for="message"><p>How did you hear about us?</p></label><textarea name="message" id="message" style="background-color:#fff; color:#000;" cols="45"/></textarea></td> </tr> <tr> <td colspan="2" style="text-align:left"> <p> Upload Recommendation:</p> <input type="file" name="pic" id="pic"> <br /> <p> Upload California State ID:</p> <input type="file" name="id" id="id"> <br /> <br /> <input type="image" value="submit"img src="img/sub.png" onmouseover="this.src='img/sub1.png'" onmouseout="this.src='img/sub.png'" /> </form>PHP: <?php // first clean up the input values foreach($_POST as $key => $value) { if(ini_get('magic_quotes_gpc')) $_POST[$key] = stripslashes($_POST[$key]); $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key])); } $ip=$_SERVER['REMOTE_ADDR']; $email_to = "info@example.com"; $email_subject = "Register"; $email_message .= "Full Name: ".$_POST["fname"]."\n"; $email_message .= "Phone Number: ".$_POST["phone"]."\n"; $email_message .= "Email Address: ".$_POST["email"]."\n"; $email_message .= "Address: ".$_POST["address"]."\n"; $email_message .= "City: ".$_POST["city"]."\n"; $email_message .= "State: ".$_POST["state"]."\n"; $email_message .= "Zip Code: ".$_POST["zip"]."\n"; $email_message .= "First Name: ".$_POST["first"]."\n"; $email_message .= "Last Name: ".$_POST["last"]."\n"; $email_message .= "Recommendation ID Number: ".$_POST["rec"]."\n"; $email_message .= "Recommendation Exp Date: ".$_POST["exp"]."\n"; $email_message .= "Doctors Name: ".$_POST["doc"]."\n"; $email_message .= "Doctors Phone Number: ".$_POST["docphone"]."\n"; $email_message .= "Verification Website: ".$_POST["ver"]."\n"; $email_message .= "Message: ".$_POST["message"]."\n"; $userEmail = filter_var( $_POST['email'],FILTER_VALIDATE_EMAIL ); if( ! $userEmail ){ exit; } //email headers $headers = 'From: '.$_POST["email"]."\r\n". 'Reply-To: '.$_POST["email"]."\r\n" . 'X-Mailer: PHP/' . phpversion(); echo (mail($email_to, $email_subject, $email_message, $headers) ? "<html><head><meta http-equiv='Refresh' content='0; url=http://www..com/thankyou.html'><body bgcolor='#fff'> ":"<html><body bgcolor='#fff'><center><font color='white'><h2>We're sorry, something went wrong.</h2></font><p><font color='white'>Please return to <a href='http://www..com'></a>.</font></p></center></body></html>"); $ip=$_SERVER['REMOTE_ADDR']; $email_to = $_POST["email"]; $email_subject = "420 In Action"; $email_message1 = "Welcome! Sincerely, "; //email headers $headers = 'From: '.$_POST["email"]."\r\n". 'Reply-To: '.$_POST["email"]."\r\n" . 'X-Mailer: PHP/' . phpversion(); echo (mail($email_to, $email_subject, $email_message1, $headers) ? "":""); exit(); // test input values for errors $errors = array(); if(strlen($fname) < 2) { if(!$fname) { $errors[] = "You must enter a name."; } else { $errors[] = "Name must be at least 2 characters."; } } if(!$email) { $errors[] = "You must enter an email."; } else if (!validEmail($email)) { $errors[] = "You must enter a valid email."; } if($errors) { // output errors to browser and die with a failure message $errortext = ""; foreach($errors as $error) { $errortext .= "<li>".$error."</li>"; } die("<span class='failure'>The following errors occured:<ul>". $errortext ."</ul></span>"); } // check to see if email is valid function validEmail($email) { $isValid = true; $atIndex = strrpos($email, "@"); if (is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen < 1 || $localLen > 64) { $isValid = false; } // local part length exceeded else if ($domainLen < 1 || $domainLen > 255) { $isValid = false; } // domain part length exceeded else if ($local[0] == '.' || $local[$localLen-1] == '.') { $isValid = false; } // local part starts or ends with '.' else if (preg_match('/\\.\\./', $local)) { $isValid = false; } // local part has two consecutive dots else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { $isValid = false; } // character not valid in domain part else if (preg_match('/\\.\\./', $domain)) { $isValid = false; } // domain part has two consecutive dots else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; } } if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) { $isValid = false; } // domain not found in DNS } return $isValid; } ?> Hi, I have a basic form that lets people enter details Code: [Select] <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Second name: <input type="text" name="sname" /> <input type="submit" /> </form> And the standard insert in sql command. Im now looking to add a image uplad field the the same form. I have tried several methods off the internet but i cant get any to work. I would like the form to upload the image into the directory '../images' and then save the path to the file in the database, e.g. 'images/picture.jpg'. Can anyone point me in the right direction please. Im guessing i will have to use the file input type but i cant get any of it to work. Thanks Hello: I wanted to learn how to add a file browse/save and send photo to a contact form. Form works fine, but I am trying to add this so a user can upload and send a photo of his or her artwork along with the contact information. Can someone tell me how this work? My other attempts failed so I'm trying to start with a clean form. This is the code I currently have: Code: [Select] <?php $error = NULL; $myDate = NULL; $FullName = NULL; $Address = NULL; $City = NULL; $State = NULL; $Zip = NULL; $Phone = NULL; $Email = NULL; $Website = NULL; $Comments = NULL; if(isset($_POST['submit'])) { $myDate = $_POST['myDate']; $FullName = $_POST['FullName']; $Address = $_POST['Address']; $City = $_POST['City']; $State = $_POST['State']; $Zip = $_POST['Zip']; $Phone = $_POST['Phone']; $Email = $_POST['Email']; $Website = $_POST['Website']; $Comments = $_POST['Comments']; if(empty($FullName)) { $error .= '<div style=\'margin-bottom: 6px;\'>- Enter your Name.</div>'; } if(empty($Email) || !preg_match('~^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$~',$Email)) { $error .= '<div style=\'margin-bottom: 6px;\'>- Enter a valid Email.</div>'; } if($error == NULL) { $sql = sprintf("INSERT INTO myContactData(myDate,FullName,Address,City,State,Zip,Phone,Email,Website,Comments) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')", mysql_real_escape_string($myDate), mysql_real_escape_string($FullName), mysql_real_escape_string($Address), mysql_real_escape_string($City), mysql_real_escape_string($State), mysql_real_escape_string($Zip), mysql_real_escape_string($Phone), mysql_real_escape_string($Email), mysql_real_escape_string($Website), mysql_real_escape_string($Comments)); if(mysql_query($sql)) { $error .= '<div style=\'margin-bottom: 6px;\'>Thank you for contacting us. We will reply to your inquiry shortly.<br /><br /></div>'; mail( "mt@gmail.com", "Contact Request", "Date Sent: $myDate\n Full Name: $FullName\n Address: $Address\n City: $City\n State: $State\n Zip: $Zip\n Phone: $Phone\n Email: $Email\n Website: $Website\n Comments: $Comments\n", "From: $Email" ); unset($FullName); unset($Address); unset($City); unset($State); unset($Zip); unset($Phone); unset($Email); unset($Website); unset($Comments); } else { $error .= 'There was an error in our Database, please Try again!'; } } } ?> <form name="myform" action="" method="post"> <input type="hidden" name="myDate" size="45" maxlength="50" value="<?php echo date("F j, Y"); ?>" /> <div id="tableFormDiv"> <fieldset><span class="floatLeftFormWidth"><span class="textErrorItalic">* - Required</span></span> <span class="floatFormLeft"> </span></fieldset> <?php echo '<span class="textError">' . $error . '</span>';?> <fieldset><span class="floatLeftFormWidth"><span class="textErrorItalic">*</span> Full Name:</span> <span class="floatFormLeft"><input type="text" name="FullName" size="45" maxlength="50" value="<?php echo $FullName; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Address:</span> <span class="floatFormLeft"><input type="text" name="Address" size="45" maxlength="50" value="<?php echo $Address; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">City:</span> <span class="floatFormLeft"><input type="text" name="City" size="45" maxlength="50" value="<?php echo $City; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">State:</span> <span class="floatFormLeft"><input type="text" name="State" size="45" maxlength="50" value="<?php echo $State; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Zip:</span> <span class="floatFormLeft"><input type="text" name="Zip" size="45" maxlength="50" value="<?php echo $Zip; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Phone:</span> <span class="floatFormLeft"><input type="text" name="Phone" size="45" maxlength="50" value="<?php echo $Phone; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth"><span class="textErrorItalic">*</span> Email:</span> <span class="floatFormLeft"><input type="text" name="Email" size="45" maxlength="50" value="<?php echo $Email; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Website:</span> <span class="floatFormLeft"><input type="text" name="Website" size="45" maxlength="50" value="<?php echo $Website; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Comments:</span> <span class="floatFormLeft"><textarea name="Comments" cols="40" rows="10"><?php echo $Comments; ?></textarea></span></fieldset> </div> <input type="submit" name="submit" value="Submit" class="submitButton" /><br /> </form> Thanks very much! I tried to add a second file upload to my previously properly functioning form, but after adding it, now when I submit the form, it submits the data twice. It appears to be submitting the file right on the first insert, but on the second insert, the second image is not inserted, but just blank. Can anyone help me figure out why? I must have done something wrong in my insert statement or second file statement. Here is the page itself which contains the form: http://midwestcreativeconsulting.com/jhrevell/add/ And below is my insert page: Code: [Select] <?php $dbhost = 'localhost'; $dbuser = 'username'; $dbpass = 'password'; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); $dbname = 'jhrevell_jewelry'; mysql_select_db($dbname); $name = $_POST['name']; $metal = $_POST['metal']; $desc = $_POST['desc']; $item_no = $_POST['item_no']; $cut = $_POST['cut']; $color = $_POST['color']; $carats = $_POST['carats']; $clarity = $_POST['clarity']; $size = $_POST['size']; $type = $_POST['type']; $other = $_POST['other']; $total = $_POST['total']; $certificate = $_POST['certificate']; $value = $_POST['value']; //if ((($_FILES["file"]["type"] == "image/gif") //|| ($_FILES["file"]["type"] == "image/jpeg") //|| ($_FILES["file"]["type"] == "image/pjpeg")) //&& ($_FILES["file"]["size"] < 20000)) // { 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"], "upload/" . $_FILES["file"]["name"]); //echo "Stored in: " . "http://www.webdesignsbyliz.com/wdbl_wordpress/wp-content/themes/twentyten_2/upload/" . $_FILES["file"]["name"]; $image = $_FILES["file"]["name"]; $query = "INSERT INTO gallery VALUES ('', '$cut', '$color', '$carats', '$clarity', '$size', '$metal', '$other', '$total', '$certificate', '$value', '$image', '$name', '$desc', '$item_no', '$type', '$image2')"; $query_res = mysql_query($query) or die(mysql_error()); } } //} // IMAGE 2 // //if ((($_FILES["file"]["type"] == "image/gif") //|| ($_FILES["file"]["type"] == "image/jpeg") //|| ($_FILES["file"]["type"] == "image/pjpeg")) //&& ($_FILES["file"]["size"] < 20000)) // { if ($_FILES["file2"]["error"] > 0) { echo "Return Code: " . $_FILES["file2"]["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["file2"]["name"])) { echo $_FILES["file2"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file2"]["tmp_name"], "upload/" . $_FILES["file2"]["name"]); //echo "Stored in: " . "http://www.webdesignsbyliz.com/wdbl_wordpress/wp-content/themes/twentyten_2/upload/" . $_FILES["file"]["name"]; $image2 = $_FILES["file2"]["name"]; $query = "INSERT INTO gallery VALUES ('', '$cut', '$color', '$carats', '$clarity', '$size', '$metal', '$other', '$total', '$certificate', '$value', '$image', '$name', '$desc', '$item_no', '$type', '$image2')"; $query_res = mysql_query($query) or die(mysql_error()); } } //} echo '<script language="Javascript">'; echo 'window.location="http://midwestcreativeconsulting.com/jhrevell/collections"'; echo '</script>'; ?> Can anyone see what could be causing it to insert the record twice? Having some issues getting this to work properly... I keep getting my own error message I know where it fails, but I can't seem to figure out why it fails. The test file I'm using is an MP3 file, which is why I'm here asking if anyone other than I can shed some experienced light on this :p Code: [Select] File Upload Failed! No File Exists!The file type or extension you are trying to upload is not allowed! You can only upload MP3 files to the server! My upload form looks like: <?php session_start(); define('PITCHFORK', true); if(!isset($_SESSION['USERS_AUTHENTICATED'])) { die("You must be logged in to do that"); } if(isset($_POST['upload'])) { include("config.php"); include("classes/class.media.upload.php"); $file = $_GET['file']; $upload = new Upload; $upload->doAudio($file); } ?> <!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>PITCHFORK Login</title> <link rel="stylesheet" href="style/login.css" type="text/css" media="all"> <meta name="robots" content="noindex,nofollow"> </head> <body> <div id="login"><h1><a title="A SpaazZ Industries Concept"></a></h1> <form name="loginform" id="loginform" action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <p> <label>File (one at a time for now)<br> <input name="file" id="user_login" class="input" size="20" tabindex="10" type="file" /> </label> </p> <p> </p> <?php if(isset($_SESSION['errMessage'])) { echo("<div id=\"login_error\"><strong>ERROR</strong>:<br />"); echo($_SESSION['errMessage']); unset($_SESSION['errMessage']); echo("</div>"); } ?> <p class="submit"> <input name="upload" id="submit" class="button-primary" value="Upload File" tabindex="100" type="submit"> </p> </form> </div> </body> </html> My Upload Class looks liks: <?php // TO DO : ERROR HANDLING // AJAX INTERFACING session_start(); define('PITCHFORK', true); class Upload { // The path to local (relivent to the user uploading - on their computer) file var $file; public function doAudio($file) { $target_path = $_SESSION['USERS_Media_Folder']."/"; // Set at login in class.users.php $flag = 0; // Safety net, if this gets to 1 at any point in the process, we don't upload. $filename = $_FILES[$file]['name']; $filesize = $_FILES[$file]['size']; $mimetype = $_FILES[$file]['type']; $filename = htmlentities($filename); $filesize = htmlentities($filesize); $mimetype = htmlentities($mimetype); $target_path = $target_path . basename( $filename ); if($filename != ""){ echo "Beginning upload process for file named: ".$filename."<br>"; echo "Filesize: ".$filesize."<br>"; echo "Type: ".$mimetype."<br><br>"; } //First generate a MD5 hash of what the new file name will be //Force a MP3 extention on the file we are uploading $hashedfilename = md5_file($filename); $hashedfilename = $hashedfilename.".mp3"; //Check for empty file if($filename == ""){ $_SESSION['errMessage'] .= "No File Exists!"; $flag = $flag + 1; } //Now we check that the file doesn't already exist. $existname = $target_path.$hashedfilename; if(file_exists($existname)) { if($flag == 0) { $_SESSION['errMessage'] .= "Your file already exists on the server! Please choose another file to upload or rename the file on your computer and try uploading it again!"; } $flag = $flag + 1; } //Whitelisted files - Only allow files with MP3 extention onto server... $whitelist = array(".mp3"); foreach ($whitelist as $ending) { if(substr($filename, -(strlen($ending))) != $ending) { $_SESSION['errMessage'] .= "The file type or extention you are trying to upload is not allowed! You can only upload MP3 files to the server!"; $flag++; } } //Now we check the filesize. If it is too big or too small then we reject it //MP3 files should be at least 1MB and no more than 6.5 MB if($filesize > 6920600) { //File is too large if($flag == 0) { $_SESSION['errMessage'] .= "The file you are trying to upload is too large! Your file can be up to 6.5 MB in size only. Please upload a smaller MP3 file or encode your file with a lower bitrate."; } $flag = $flag + 1; } if($filesize < 1048600) { //File is too small if($flag == 0) { $_SESSION['errMessage'] .= "The file you are trying to upload is too small! Your file has been marked as suspicious because our system has determined that it is too small to be a valid MP3 file. Valid MP3 files must be bigger than 1 MB and smaller than 6.5 MB."; } $flag = $flag + 1; } //Check the mimetype of the file if($mimetype != "audio/x-mp3" and $mimetype != "audio/mpeg") { if($flag == 0) { $_SESSION['errMessage'] .= "The file you are trying to upload does not contain expected data. Are you sure that the file is an MP3?"; } $flag = $flag + 1; } //Check that the file really is an MP3 file by reading the first few characters of the file $f = @fopen($_FILES[$file]['tmp_name'],'r'); $s = @fread($f,3); @fclose($f); if($s != "ID3") { if($flag == 0){ $_SESSION['errMessage'] .= "The file you are attempting to upload does not appear to be a valid MP3 file."; } $flag++; } //All checks are done, actually move the file... if($flag == 0) { if(move_uploaded_file($_FILES[$file]['tmp_name'], $target_path)) { //Change the filename to MD5 hash and FORCE a MP3 extention. if(@file_exists($target_path.$filename)) { //Rename the file to an MD5 version rename($target_path.$filename, $target_path.$hashedfilename); echo "The file ". basename( $filename ). " has been uploaded. Your file is <a href='$target_path$hashedfilename'>here</a>."; } else{ echo "There was an error uploading the file, please try again!"; } } else { echo "There was an error uploading the file, please try again!"; } } else { echo "File Upload Failed!<br>"; if($error != "") { echo $error; } } } // Close function doAudio } // Close Class audioUpload ?> 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 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 I have a form which has a variable size, depending on the number of rows in a table. For each row there are about ten fields, and I simply show them all for each row. I've recently started having a trouble in that if I create a form with more than 400 elements, then the $_POST variable is truncated at 400. Is this normal? Do I have to limit the size of the $_POST array? Not by MB, which must be trivial for me, but for the number of array elements? I've looked over it a couple times and I still get the error. Here's the code <?php require('header.php'); require('links.php'); $name = mysql_real_escape_string($_POST['file']); $url = mysql_real_escape_string($_POST['file']); $filename = $_FILES['file']['name']; $temp = $_FILES['file']['tmp_name']; $error = $_FILES['file']['error']; $sql = "insert into books set name='$name', url='$url'"; if(isset($_POST['submit'])) { if($error > 0) { die("Error uploading file! Code $error."); }else{ move_uploaded_file($temp,"/center/resources/books/".$filename); mysql_query($sql); } } ?> <form method='post' enctype='multipart/form-data'> Book Name<input type="text" name="name"></br> File<input type="file" name="file"></br> <input type="submit" name="submit" value="Upload"> </form> |