PHP - Limit File Size (fwrite)
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? Similar TutorialsHi 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 Hi 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'> I'm trying to add a file size limit to my upload form-code (below) 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? 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? 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? Hi, I am trying to save some content with form which has php code in it. i.e $submittedphpcode <?php echo 'test'; ?> my code to save that $submittedphpcode $file = "file.php"; $ourFileHandle = fopen($filefile, 'w+') or die("can't open file"); fwrite($ourFileHandle, "$submittedphpcode"); fclose($ourFileHandle); and i am getting this file created with slashes <?php\r\n\r\necho \'test\';\r\n\r\n?> i tried with stripslashes but it just remove \ not r n , i need to keep spaces etc. any help on how to save it as php file properly? Thanks hi all i'm trying to make a quick and simple '.htaccess' installer and i'm using fopen/fwrite to do this but i'm getting an error: Quote Parse error: parse error in /var/www/test.php on line 12 here's the code: Code: [Select] <?PHP $File = ".htaccess"; $fh = fopen($File, 'a'); $Data = "\n#test write <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/javascript application/javascript application/x-javascript text/x-js text/ecmascript application/ecmascript text/vbscript text/fluffscript AddOutputFilterByType DEFLATE image/svg+xml application/x-font-ttf application/x-font font/opentype font/otf font/ttf application/x-font-truetype application/x-font-opentype application/vnd.ms-fontobject application/vnd.oasis.opendocument.formula-template AddOutputFilterByType DEFLATE text/xml application/xml </IfModule> <IfModule mod_expires.c> <FilesMatch "\.(ico|gif|jpg|JPG|jpeg|png|PNG|swf|css|js|html?|xml|txt)$"> ExpiresActive On ExpiresDefault "access plus 1 month" </FilesMatch> </IfModule> #test write\n"; fwrite($fh, $Data); fclose($fh); ?> how do i include the code in the $Data string bit? Hey guys, I have a script that is run once a week to fetch some user info for a large number of accounts. The code I have now writes the info correctly, but I was wondering if there was an easy way to have the accountdata.txt file completely wiped before new updated info is written to it, as opposed to deleting it manually every week. $FileName = "accountdata.txt"; $f=fopen($FileName,"a+"); fwrite($f, $UserKey[$i]." ".$SigKey[$i]."\n"); $f=fclose; I could in theory just open the file and delete everything in it manually, save it and then run this script, but I'm always looking for more ways to make things efficient, and come a time when it's run more than once a week it'd be nice to have all that automated. So in summary, I need it to delete all data (if any) from the accountdata.txt file before it writes anything to it. Thanks. Hey, I am pretty new to php. I am creating a simple website to handle a http get I need to do for a Android Application. I can write to a file but I am unable to open it in a browser. It just shows a blank page. When I download it from my browser (Firefox) to my hard drive (Windows 7) using my ftp I can view the .txt file. All i want to do is write to a text file. Any help would be nice. Sorry for sparse information. I am hosting it on 000webhost.com. Thanks My Code: 3 files blank "data.txt", index.html, process.php Index.html Code: [Select] <html><body> <h4>Tizag Art Supply Order Form</h4> <form action="process.php" method="post"> <select name="item"> <option>Paint</option> <option>Brushes</option> <option>Erasers</option> </select> Quantity: <input name="quantity" type="text" /> <input type="submit" /> </form> </body></html> process.php <html><body> <?php $quantity = $_POST['quantity']; $item = $_POST['item']; $myFile = "data.txt"; $fh = fopen($myFile, 'at') or die("can't open file"); $stringData = "Bobby Bopper"; fwrite($fh, $stringData); $stringData = "Tracy Tanner"; fwrite($fh, $stringData); fclose($fh); echo "You ordered ". $quantity . " " . $item . ".<br />"; echo "Thank you for ordering from Tizag Art Supplies!"; ?> </body></html> Hi there, I am trying to create a file using fwrite function, but for something reason all I get is a blank file with no content inside. Here is the code, go to the bottom where the fwrite function is called: <?php //Get Nohay Albums function function GetAlbums($cattype){ if ((isset($_GET['year']))||(isset($_GET['reciter']))){ //nothing displayed } else{ $query = "SELECT COUNT(Topic), SUM(Hits) AS totalhits, FileFormat, Speaker, Language, Year, FileType, Cat FROM nauhey WHERE Cat='".addslashes($cattype)."' AND Year='".date('Y')."' GROUP By Speaker, Year"; $result = mysql_query($query) or die (mysql_error()); //<!------------ Create Cache -------------!> //folder where cache is saved $path = "cache/"; //Page name format: FunctionName_Category_Year.html $pagename = $path."getalbums_".$cattype.".html"; $cacheFile = fopen($pagename, "w"); if ($cacheFile == FALSE){ die ("Unable to create cache file"); } //Get HTML in a variable $obstart = ob_start(); if ($obstart == FALSE){ die ("Unable to buffer cache content!"); } //<!------------ Cache closed -------------!> if ($cattype = strtolower('nauhey')){ while ($row = mysql_fetch_array($result)){ echo ("<div class='container'>"); echo ("<img src=\"http://localhost/HAQMOLAAALI/backed up/haqmolaali/images/".$row['FileFormat'].".gif\">"); echo ("<b style=\"font-size:10px; color:#000066; position:absolute; margin-left: 500px;\">DOWNLOADS: ".$row['totalhits']."</b>"); echo (" <a href=\"nohay.php?reciter=".urlencode($row['Speaker'])."&year=".urlencode($row['Year'])."\">".$row['Speaker']." Vol ".$row['Year']."</a> <b style=\"font-size:10px; color:#000000;\">(".strtoupper($row['Language']).")</b>"."\n"); echo ("<div class='small'><b>Year: ".$row['Year']." | Language: ".ucfirst($row['Language'])." | Tracks: ".$row['COUNT(Topic)']."</b></div>"); echo ("</div>"); }//while loop closed } else { while ($row = mysql_fetch_array($result)){ echo ("<div class='container'>"); echo ("<img src=\"http://localhost/HAQMOLAAALI/backed up/haqmolaali/images/".$row['FileFormat'].".gif\">"); echo ("<b style=\"font-size:10px; color:#000066; position:absolute; margin-left: 500px;\">DOWNLOADS: ".$row['totalhits']."</b>"); echo (" <a href=\"majlis.php?reciter=".urlencode($row['Speaker'])."&year=".urlencode($row['Year'])."\">".$row['Speaker']." Vol ".$row['Year']."</a> <b style=\"font-size:10px; color:#000000;\">(".strtoupper($row['Language']).")</b>"); echo ("<div class='small'><b>Year: ".$row['Year']." | Language: ".ucfirst($row['Language'])." | Lectures in series: ".$row['COUNT(Topic)']."</b></div>"); echo ("</div>"); } } //<!------------ Cache Code -------------!> $cacheContent = ob_get_contents(); //Write to cache file fwrite ($cacheFile, $cacheContent) or die ("Cannot write cache content to file!"); fclose ($cacheFile); ob_flush(); ob_end_clean(); //<!------------ Cache Closed-------------!> } } GetAlbums("nauhey"); ?> When I execute the function, I get my self-made error "Cannot write cache content to file!". Help would be much appreciated. Thank you. So I really don't think I need to paste the code but Code: [Select] <?php session_start(); ?> <?php $new_thread_page_path = 'general_discussion_threads/' . $_POST['thread_title'] . '.php'; $new_table_link = '<a href="' . $new_thread_page_path . '"' . 'class="hover" border="0" style="text-decoration:none">' . $_POST['thread_title'] . '</a>'; ?> <?php date_default_timezone_set('EST'); $date = date("m/d/y"); $hour = date("g"); $minute = date("i"); $second = date("s"); $am_pm = date("a"); $full_date = $date . ' ' . $hour . ":" . $minute . ":" . $second . $am_pm; $place_holder = '<!--the_place_holder-->'; $current_page_path = 'general_discussion_home.php'; $open_current_page = fopen($current_page_path, 'rb'); $contents_of_current_page = fread($open_current_page, filesize($current_page_path)); $template_path = 'general_discussion_threads/template.php'; $open_template = fopen($template_path, 'rb'); $template_contents = fread($open_template, filesize($template_path)); $new_thread_page_path = 'general_discussion_threads/' . $_POST['thread_title'] . '.php'; $list_file_path = 'general_discussion_threads/thread_list.txt'; $list_open = fopen($list_file_path, 'rb'); $list_open_write = fopen($list_file_path, 'a'); $open_new_thread_page = fopen($new_thread_page_path, 'w+'); $list_contents = fread($list_open, filesize($list_file_path)); $thread_exists_test = substr_count($list_contents, '<' . strtolower($_POST['thread_title'] . '>')); $invalid_character_test = substr_count($_POST['thread_title'], '<'); $invalid_character_test1 = substr_count($_POST['thread_title'], '>'); $the_users_info = $_SESSION['the_user']; $the_username1 = strstr($_SESSION['the_user'], '.'); $the_username1_wipe = str_replace($the_username1, '', $the_users_info); $the_username = str_replace('.', '', $the_username1_wipe); if (isset($_POST['new_thread_post'])) { if (($_SESSION['logged_in'] == '1') && ($invalid_character_test1 == '0') && ($invalid_character_test == '0') && ($thread_exists_test == '0') && ($_POST['thread_title'] != '') && ($_POST['thread_title'] != 'Enter the title of your Thread...')) { fwrite($open_new_thread_page, '<?php $the_thread_title = ' . '\'' . $_POST['thread_title'] . '\'' . '; ?>' . $template_contents); fclose($open_new_thread_page); fwrite($list_open_write, '<' . strtolower($_POST['thread_title']) . '>'); fclose($list_open_write); $new_contents =str_replace($place_holder, '<tr><td align="center">' . $new_table_link . '</td>' . '<td align="center">' . '<font color="#66CC00">' . $full_date . '</font>' . '</td>' . '<td align="center">' . '<font color="#66CC00">' . $the_username . '<font>' . '</td>' . '</tr>' . $place_holder, $contents_of_current_page); $open_current_page = fopen($current_page_path, 'w'); fwrite($open_current_page, $new_contents); fclose($open_current_page); $_SESSION['gd_error'] = 'Thread created succesfully!'; } elseif ($_SESSION['logged_in'] != '1') { $_SESSION['gd_error'] = 'You need to be logged in!'; } elseif ($invalid_character_test != '0') { $_SESSION['gd_error'] = 'Thread title contains invalid characters!'; } elseif ($invalid_character_test1 != '0') { $_SESSION['gd_error'] = 'Thread title contains invalid characters!'; } elseif ($thread_exists_test != '0') { $_SESSION['gd_error'] = 'Thread title unavailable!'; } elseif ($_POST['thread_title'] == '') { $_SESSION['gd_error'] = 'You must make a thread title!'; } elseif ($_POST['thread_title'] == 'Enter the title of your Thread...') { $_SESSION['gd_error'] = 'You must make a thread title!'; } } ?> So what all this does is based on user input it creates a new html page based off of the template with a few different variables based on input. Then it makes a new row and 3 cells in the home pages thread table that link to the page say who made it and what time they made it. Now it all works PERFECT (Im suprised how perfect on the first try actually) except for 1 tiny flaw which i think might be php not me but im not sure. The fwrite creates a new file but if the input contains any question marks (?) the link will work but no file will be created. For everyother character on teh standard keyboard its fine but not the question mark. What gives? thanks yall! MOD EDIT: <code></code> tags changed to proper [code] . . . [/code] BBCode tags. Can't figure out why the page wont save after clicking save. $KOHDE="index.php?s=admin"; $LOMAKE_W = 400; $TEXTAREA_W = 50; $TEXTAREA_H = 20; $LOMAKE = mysql_real_escape_string($_GET["l"]); $LOMAKE2 = mysql_real_escape_string($_POST["lomake"]); after a few more lines... elseif ($LOMAKE2 == "etusivu"){ #Etusivun muokkaus $teksti = stripslashes($_POST["teksti"]); $f = fopen("etusivu.php", "w"); fwrite($f, $teksti); fclose($f); } elseif ($LOMAKE == "etusivu"){ #Etusivun muokkaus echo "<h1>Edit home page</h1>"; $f = file("etusivu.php"); echo "<form action='$KOHDE' method='post'> <textarea name='teksti' cols='$TEXTAREA_W' rows='$TEXTAREA_H'>"; for ($i = 0; $i < count($f); $i++){ $f[$i] = str_replace("\"", "''", $f[$i]); echo $f[$i]; } echo "</textarea> <input type='hidden' value='etusivu' name='lomake'/> <br><input type='submit' value='Save'/> </form><br/>"; html_ohje(); } I can't see where it has gone wrong. Can anyone help? I have this code which uploads fine but I am trying to limit the type of files users can upload. For some reason this code still let any file type to be uploaded being very new to php any help would be Appreciated. Quote Code: [Select] <?php if ((($_FILES["image"]["type"] == "image/gif") || ($_FILES["image"]["type"] == "image/jpeg") || ($_FILES["image"]["type"] == "image/pjpeg")) && ($_FILES["image"]["size"] < 20000)) { if ($_FILES["image"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["image"]["name"] . "<br />"; echo "Type: " . $_FILES["image"]["type"] . "<br />"; echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["image"]["tmp_name"]; } } $target = "testimages/"; $target = $target . basename( $_FILES['image']['name']); // $company=$_POST['company']; $image=($_FILES['image']['name']); mysql_connect("localhost", "user", "pass") 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."; } ?> Hello! I have this validation script that seems to work great until I add the size validation. I'm ready to pull my hair out! Can someone tell me what I'm doing wrong? Code: [Select] if (isset($_POST['Submit'])) { $user_id = $userdata[user_id]; $number_of_file_fields = 0; $number_of_uploaded_files = 0; $number_of_moved_files = 0; $uploaded_files = array(); $max_filesize = 5242880; // Maximum filesize in BYTES (currently 5MB). $upload_directory = dirname(__file__) . '/'.$user_id.'/'; //set upload directory if (!is_dir($upload_directory)) { mkdir($upload_directory, 0777, true); } for ($i = 0; $i < count($_FILES['images']['name']); $i++) { $number_of_file_fields++; if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not $number_of_uploaded_files++; if($_FILES['images']['size'] > $max_filesize){ echo "<b class='red'>Max file size is 5MB.</b><br/>"; $sz = true; } $ext = validate_extension($_FILES['images']['name'][$i]); if (($ext == true) && ($sz == true)){ $uploaded_files[] = $_FILES['images']['name'][$i]; if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . $_FILES['images']['name'][$i])) { $number_of_moved_files++; } }else { echo "<b class='red'>File extention error. Only .doc, .pdf, .jpg and .gif files are allowed. </b><br/>"; } } } if ($number_of_uploaded_files >= 1){ echo "Number of files submitted:<b class='red>".$number_of_uploaded_files."</b><br/>"; echo "Number of successfully uploaded files:<b class='red>".$number_of_moved_files."</b><br/><br/>"; echo "Uploaded File Name(s):<br/>" . implode('<br/>', $uploaded_files); } } As of now it results in every uploaded file returning the error "Max file size is 5MB." i want to display the size of a file but i round it off to the nearest kb. I am using... ($_FILES["file"]["size"]/1024/1024)."mb" i am geting it return something like this.... 1.0313243865967mb and i want it to be more like 1.03mb any idears??? I need to check a file's size with php and ssh. Everything I've seen online for remote files uses curl and port 80. I'll be checking a LAN computer that isn't running a webserver, but is running an SSH server. How can I do this? I've tried this: Code: [Select] <?php $tomorrow = date ('n-j-y'); echo system(ssh root@192.168.2.169 ls -lah "/MacRadio X/WMIS Logs/WMIS $tomorrow Log" | awk {print $5}); ?> but it didn't work. I got a T_VARIAABLE error. This was the same command I used right from the command line, and it worked. I'll also need to add a check to the file size, and if it's less than 175K, send me an email...but I'll work on that after I have the first part working. Thanks! What's the maximum file size I can upload through a regular form ? If it's server dependant, how do I find out my max ? I tried to handle a 550MB file (on localhost) - I only wanted to show the filename, but it hung up for about 10secs, then returned nothing. $file="../myclients/clients/".$company_name."/Download/".$file_name; $size = filesize($path); // not working i try with function also function formatbytes($file, $type) { switch($type){ case "KB": $filesize = filesize($file) * .0009765625; // bytes to KB break; case "MB": $filesize = (filesize($file) * .0009765625) * .0009765625; // bytes to MB break; case "GB": $filesize = ((filesize($file) * .0009765625) * .0009765625) * .0009765625; // bytes to GB break; } if($filesize <= 0){ return $filesize = 'unknown file size';} else{return round($filesize, 2).' '.$type;} } echo formatbytes($file, "KB"); uploaded file size is 488 kb but it showing "unknown file size" please help me. 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 } |