PHP - Image Upload Size Issue
Hey there so I'm using the below code to upload images/files to my server via ftp. The issue I've found is that anything bigger than 200KB either stalls out and partially uploads or doesn't upload at all.
I've set my php.ini file to have upload_max_filesize = 1000M and post_max_size = 1000M. And still anything bigger than 200KB won't upload right. Any help would be appreciated. I'm using php version 5.2.14 fyi. Thanks so much. ---CODE--- <?if(!isset($_POST["submit"])){?> <!-- THE FORM ACTION IS ONTO ITSELF --> <form action="index.php" method="POST" enctype="multipart/form-data"> <input name="userfile" type="file" size="40"> <input type="submit" name="submit" value="Upload image" /> </form> <? } else { set_time_limit(30000);//i noticed that this had to be pretty big otherwise your upload was likely to stall out. $paths='/yourfilepath/yourfilepath/'; $filep=$_FILES['userfile']['tmp_name']; $ftp_server='ftp.yourdomain.com'; $ftp_user_name='your_user_name'; $ftp_user_pass='your_password'; $name=$_FILES['userfile']['name']; $conn_id = ftp_connect($ftp_server); $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); if ((!$conn_id) || (!$login_result)) { echo "FTP connection has encountered an error!"; echo "Attempted to connect to $ftp_server for user $ftp_user_name...."; exit; } else { echo ""; } $upload = ftp_put($conn_id, $paths.'/'.$name, $filep, FTP_BINARY); if (!$upload) { echo "FTP upload has encountered an error!"; } else { echo "Uploaded file with name $name Succsessfully "; } ftp_close($conn_id); } ?> Similar TutorialsIs there a way I can get the .jpg file in kilobytes from a remote url and check it to make sure it does not exceed 40 kilobytes before it saves the remote url into my database? Hi, I'm developing a code that uploads images. I need to verify if the image have the minimum size of 100*100 pixels before the upload. How can I do this? Best Regards, Sorry for my bad english. 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'> (1) What does this actually do? (compress it?) $image = imagecreatefromjpeg("image.jpg"); header('Content-Type: image/jpeg'); imagejpeg($image); By using this rather than displaying by using www.site.com/image.jpg it reduces file size of an image from 2.5mb to 0.5mb !! (2) ImageMagick can't get these results. Am I doing something wrong? If I change the pixel size of an image in ImageMagick then I can reduce its file size, but (1) above reduces file size regardless of changing pixel size. Hi I have an upload script which uploads an image then resizes The error Code: [Select] Fatal error: Allowed memory size of 20971520 bytes exhausted (tried to allocate 7776 bytes) in Dir/UploadScript.php on line 234 The code function $strNewFileName = date("YmdHis").rand(0,5000).".".$this->strFileExt; $this->strNewFileName = $strNewFileName; $strDir = $_SERVER['DOCUMENT_ROOT'].$this->strSaveDir.$strNewFileName; $strTNDir = $_SERVER['DOCUMENT_ROOT'].$this->strSaveDir."tn_".$strNewFileName; move_uploaded_file($this->arrUploadFile['tmp_name'], $strDir); $image_p = imagecreatetruecolor($this->intNewWidth, $this->intNewHeight); switch($this->strFileExt){ case "jpg": $image = imagecreatefromjpeg($strDir); break; case "gif": $image = imagecreatefromgif($strDir); break; case "png": $image = imagecreatefrompng($strDir); break; } imagecopyresampled($image_p, $image, 0, 0, 0, 0, $this->intNewWidth, $this->intNewHeight, $this->intCurWidth, $this->intCurHeight); $blnSuccessUpload = false; switch($this->strFileExt){ case "jpg": if(imagejpeg($image_p, $strTNDir)){ $blnSuccessUpload = true; } break; case "gif": if(imagegif($image_p, $strTNDir)){ $blnSuccessUpload = true; } break; case "png": if(imagepng($image_p, $strTNDir)){ $blnSuccessUpload = true; } } imagedestroy($image_p); return $blnSuccessUpload; the Line causing issues (234) is Code: [Select] $image = imagecreatefromjpeg($strDir); Now that image is created but the TN is not //Edit Just a note. I have ini_set('memory_limit', 16MB); if you notice the allocated memory is less than the memory allowed. Warning: imagejpeg() [function.imagejpeg]: Unable to open '/Applications/XAMPP/xamppfiles/htdocs/images/category/90f9f5fb6bd92875b85a69ed2f5749cc.jpg' for writing: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/admin/library/functions.php on line 254 getting this error when i try to upload a photo using my admin section of a shopping cart. cant figure it out. any help greatly appreciated. heres my code: Code: [Select] function copyImage($srcFile, $destFile, $w, $h, $quality = 75) { $tmpSrc = pathinfo(strtolower($srcFile)); $tmpDest = pathinfo(strtolower($destFile)); $size = getimagesize($srcFile); if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg") { $destFile = substr_replace($destFile, 'jpg', -3); $dest = imagecreatetruecolor($w, $h); imageantialias($dest, TRUE); } elseif ($tmpDest['extension'] == "png") { $dest = imagecreatetruecolor($w, $h); imageantialias($dest, TRUE); } else { return false; } switch($size[2]) { case 1: //GIF $src = imagecreatefromgif($srcFile); break; case 2: //JPEG $src = imagecreatefromjpeg($srcFile); break; case 3: //PNG $src = imagecreatefrompng($srcFile); break; default: return false; break; } imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]); switch($size[2]) { case 1: case 2: imagejpeg($dest,$destFile, $quality); break; case 3: imagepng($dest,$destFile); } return $destFile; } Hi Guys Probably a simple answer here that i'm missing. I've got a simple upload script for an image uploader that does various checks for security sake. One of the checks is on file size to make sure it doesn't exceed the upload limit set in php.ini . The limit is set at 2mb, so the script checks that the file doesn't exceed this limit. The problem occurs when I try to upload a file that far exceeds the limit (the one below is 3.5mb). When i do this the upload gets passed my script because the $_FILES['picture1']['size'] gets set to no value. A print_r of the files array shows: Code: [Select] [picture1] => Array ( [name] => DSC01468.JPG [type] => [tmp_name] => [error] => 1 [size] => 0 ) So what i wanted to know was whether this was normal? And should i simply do a check to see if the size value is empty? Any advice would be good! Thanks Drongo Hi guys, Im trying to resize and create thiumbnails while uploading an image but it doesnt work, as i am new to php and i have followed other tutorials, i might have made a mistake which i dont understand. i have a table called test (find attached image) and what i need is when i upload an image, it copies the location of both image and on fly created thumb into my database i appreciate your help & please excuse me for messed up code <?php session_start(); include ("../global.php"); //welcome messaage echo "Welcome, " .$_SESSION['username']."!<p>"; $username=$_SESSION['username']; //get user id & credit limit $query=mysql_query("SELECT id FROM users"); while($row = mysql_fetch_array($query)) { $id = $row['id']; echo $id; } $credit=mysql_query("SELECT credit FROM users"); while($row = mysql_fetch_array($credit)) { $creditcheck = $row['credit']; echo "your credit is: $creditcheck"; } $reference = rand(11111111,99999999); //image1 define ("MAX_SIZE","100"); define ("WIDTH","150"); define ("HEIGHT","100"); function make_thumb($img_nameone,$filenameone,$new_w,$new_h) { $ext=getExtension($img_nameone); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $src_imgone=imagecreatefromjpeg($img_nameone); if(!strcmp("png",$ext)) $src_imgone=imagecreatefrompng($img_nameone); $old_x=imageSX($src_imgone); $old_y=imageSY($src_imgone); $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } $dst_imgone=ImageCreateTrueColor($thumb_w,$thumb_h); imagecopyresampled($dst_imgone,$src_imgone,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); if(!strcmp("png",$ext)) imagepng($dst_imgone,$filenameone); else imagejpeg($dst_imgone,$filenameone); imagedestroy($dst_imgone); imagedestroy($src_imgone); function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } $errors=0; if ($creditcheck<=0) Header("Location: buy-credit.php"); else if ($creditcheck>=0){ if(isset($_POST['register'])) $submit = mysql_query("INSERT INTO test (reference) VALUES ('$reference')"); { $image=$_FILES['myfileone']['nameone']; if ($image) { $filename = stripslashes($_FILES['myfileone']['nameone']); $extension = getExtension($filenameone); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { $size=getimagesize($_FILES['myfileone']['tmp_name']); $sizekb=filesize($_FILES['myfileone']['tmp_name']); if ($sizekb > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } $image_nameone=time().'.'.$extension; $newname="rentimages/".$image_nameone; $copied = copy($_FILES['myfileone']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { $thumb_name='rentimages/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} if(isset($_POST['register']) && !$errors) { $locationone="rentimages/$nameone"; $image1 = mysql_query ("UPDATE test SET image1='$newname', thumb='$thumb_name' WHERE reference='$referenceran'"); } } } ?> <html> <body> <form action='imagetests.php' method='POST' enctype='multipart/form-data'> File: <input type='file' name='myfileone'><p /> <input type='submit' name='register' value='Update'> <p /> </body> </html> could someone help in how to resize a uploaded image size, say if someone is uploading a 1mb photo to my server, i wish for it to become 100kb and also resize its width and height? here is my code Code: [Select] //////////////////////////////////////uploader else if($action=="uploader") { echo "Upload your picture and copy the link <br/>after uploading to user it at gallery.<br/><br/>"; echo "<form method=\"post\" enctype=\"multipart/form-data\" action=\"index.php?action=uploaded&sid=$sid\">"; echo "Choose Pictu <br />"; echo "<input name=\"uploaded\" type=\"file\" /><br /><br />"; echo "<input type=\"submit\" value=\"Upload\" />"; echo "</form><br/>"; echo "<p align=\"center\">"; echo "<a href=\"index.php?action=main&sid=$sid\">Home</a>"; echo "</p>"; } //////////////////////////////////////uploader else if($action=="uploaded") { $blacklist = array(".php", ".php.jpg", ".php.jpeg", ".php.gif", ".php.png", ".phtml", ".php3", ".php4"); foreach ($blacklist as $item) { if(preg_match("/$item\$/i", $_FILES['uploaded']['name'])) { echo "<p align=\"center\">"; echo "Oops sorry we do not allow those files.<br/>"; echo "<a href=\"index.php?action=main&sid=$sid\">Home</a>"; echo "</p>"; exit; } } $target = "../images/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; if (file_exists("../images/" . $_FILES["uploaded"]["name"])) { echo "<p align=\"center\">"; echo $_FILES["file"]["name"] . "Oops file name already exists<br/> kindly rename your picture and upload again. <br/>"; echo "<a href=\"index.php?action=main&sid=$sid\">Home</a>"; echo "</p>"; }else{ //This is our size condition if ($uploaded_size > 25600){ echo "Your file is too large. We have a 25kb limit.<br/>"; $ok=0; } $types = array('image/jpeg', 'image/gif', 'image/png'); if (in_array($_FILES['uploaded']['type'], $types)) { // file is okay continue } else { $ok=0; } //Here we check that $ok was not set to 0 by an error if ($ok==0){ echo "<p align=\"center\">"; Echo "Sorry your file was not uploaded.<br/> It may be the wrong filetype. <br/>We only allow JPG, GIF, and PNG filetypes.<br/>"; echo "<a href=\"index.php?action=main&sid=$sid\">Home</a>"; echo "</p>"; } //If everything is ok we try to upload it else{ if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)){ echo "<p align=\"center\">"; echo "The file ". basename( $_FILES['uploadedfile']['name']). " Picture uploaded successfully.<br/><br/><b>$target <br/>"; echo "<a href=\"index.php?action=main&sid=$sid\">Home</a>"; echo "</p>"; } else{ echo "<p align=\"center\">"; echo "Sorry, there was a problem uploading your file.<br/>"; echo "<a href=\"index.php?action=main&sid=$sid\">Home</a>"; echo "</p>"; } } } } 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? 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); }
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 } Hi I am running debian lenny, apache2 php5. My fail upload fails for large file sizes. A 6.2 MB file uploads file, but a 10.2Mb file fails. I have set the Max file size to 50MB and max_execution to 600 etc in php.ini, but still have the same problems. I have noticed many others having similar problems. Is there a solution? 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. I'm trying to add a file size limit to my upload form-code (below) The script for creating a new file name for the image:
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $new_image_name = md5(uniqid()) . "." . $ext[count($ext) - 1]; $target_path = $target_path . $new_image_name;//set the target path with a new name of imageThe script creates a new file like: f6c9b8d9db05366c3504210cded9ddb2.jpgand moves the file to the "uploads" folder. And then the script also creates a thumbnail with the same file name and moves the file to the "thumbs" folder. The issue I am having is that the same ID code could happen again for a different image in the database, thus I would be calling a different original sized image than the thumbnail image. My question is: How to avoid this issue of the same ID code has happened again for a different file. What is the proper way to reference the anchor tag of the thumbnail image to its actual original sized image? With the script I have the thumbnail image would be coming from the "thumbs" folder and the anchor tag would get referenced to the "uploads" folder to get the original sized image. Edited by glassfish, 12 October 2014 - 05:51 AM. How can i edit just one image at on time with a multiple image upload form? I have the images being stored in a folder and the path being stored in MySQL. I also have the files being uploaded with a unique id. My issue is that I want to be able to pass the values of what is already in $name2 $name3 $name4 if I only want to edit $name1. I don't want to have to manually update the 4 images. Here is the PHP: Code: [Select] <?php require_once('storescripts/connect.php'); mysql_select_db($database_phpimage,$phpimage); $uploadDir = 'upload/'; if(isset($_POST['upload'])) { foreach ($_FILES as $file) { $fileName = $file['name']; $tmpName = $file['tmp_name']; $fileSize = $file['size']; $fileType = $file['type']; if ($fileName != ""){ $filePath = $uploadDir; $fileName = str_replace(" ", "_", $fileName); //Split the name into the base name and extension $pathInfo = pathinfo($fileName); $fileName_base = $pathInfo['fileName']; $fileName_ext = $pathInfo['extension']; //now we re-assemble the file name, sticking the output of uniqid into it //and keep doing this in a loop until we generate a name that //does not already exist (most likely we will get that first try) do { $fileName = $fileName_base . uniqid() . '.' . $fileName_ext; } while (file_exists($filePath.$fileName)); $file_names [] = $fileName; $result = move_uploaded_file($tmpName, $filePath.$fileName); } if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); } $fileinsert[] = $filePath; } } $mid = mysql_real_escape_string(trim($_POST['mid'])); $cat = mysql_real_escape_string(trim($_POST['cat'])); $item = mysql_real_escape_string(trim($_POST['item'])); $price = mysql_real_escape_string(trim($_POST['price'])); $about = mysql_real_escape_string(trim($_POST['about'])); $fields = array(); $values = array(); $updateVals = array(); for($i = 0; $i < 4; $i++) { $values[$i] = isset($file_names[$i]) ? mysql_real_escape_string($file_names[$i]) : ''; if($values[$i] != '') { $updateVals[] = 'name' . ($i + 1) . " = '{$values[$i]}'"; } } $updateNames = ''; if(count($updateVals)) { $updateNames = ", " . implode(', ', $updateVals); } $update = "INSERT INTO image (mid, cid, item, price, about, name1, name2, name3, name4) VALUES ('$mid', '$cat', '$item', '$price', '$about', '$values[0]', '$values[1]', '$values[2]', '$values[3]') ON DUPLICATE KEY UPDATE cid = '$cat', item = '$item', price = '$price', about = '$about' $updateNames"; $result = mysql_query($update) or die (mysql_error()); I am trying to run the following code to upload a file. (WAMP using Win XP). Once I select the file and click submit I get the error: "Forbidden... You don't have permission to access /< on this server." with URL http://localhost/<?=$PHP_SELF?> Code is below: <form action="<?=$PHP_SELF?>" method="post" enctype="multipart/form-data"> <br/><br/> Choose a file to upload:<br/> <input type="file" name="upload_file"> <br/> <input type="submit" name="submit" value="submit"> </form> TIA Hi
I am developing a website for fun to play around with, like a little fun project and am trying to work out how to upload multiple images that stores the filename in the database and the actual file on the server
I have managed to get it working if I upload just one image but can't work it out for multiple images
Can anyone point me in the right direction or advise where I need to adjust for multiple images upload
I know on the html form on the input tag needs to have multiple and then the name in the input tag be image[] but is as far as I get, it's the PHP I get stuck on
The html for the form is below
<form action="private-add-insert.php" method="post" enctype="multipart/form-data"> Car Make: <input type="text" name="make"> Car Model: <input type="text" name="model"> Exterior Colour: <input type="text" name="exteriorcolour"> Engine Size: <input type="text" name="enginesize"> Fuel Type: <input type="text" name="fueltype"> Year Registered: <input type="text" name="yearregistered"> Transmission: <input type="text" name="transmission"> Mileage: <input type="text" name="mileage"> Number of Doors: <input type="text" name="nodoors"> Body Style: <input type="text" name="bodystyle"> Price: <input type="text" name="price"> <br> <label>Upload Images</label> <input type="file" name="image[]" multiple/> <br /> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> <br /> <input type="submit" value="Submit Listing"> </form>Below is the PHP coding that processes the html form <?php ini_set('display_startup_errors',1); ini_set('display_errors',1); error_reporting(-1); ?> <?php // Start a session for error reporting session_start(); // Call our connection file require("includes/conn.php"); // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that's easy to read // I used this function during debugging but it serves no purpose at run time for this example function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } // Set some constants // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "private-listing-images/"; // Get our POSTed variables $make = $_POST['make']; $model = $_POST['model']; $exteriorcolour = $_POST['exteriorcolour']; $enginesize = $_POST['enginesize']; $fueltype = $_POST['fueltype']; $yearregistered = $_POST['yearregistered']; $transmission = $_POST['transmission']; $mileage = $_POST['mileage']; $nodoors = $_POST['nodoors']; $bodystyle = $_POST['bodystyle']; $price = $_POST['price']; $image = $_FILES['image']; // Sanitize our inputs $make = mysql_real_escape_string($make); $model = mysql_real_escape_string($model); $exteriorcolour = mysql_real_escape_string($exteriorcolour); $enginesize = mysql_real_escape_string($enginesize); $fueltype = mysql_real_escape_string($fueltype); $yearregistered = mysql_real_escape_string($yearregistered); $transmission = mysql_real_escape_string($transmission); $mileage = mysql_real_escape_string($mileage); $nodoors = mysql_real_escape_string($nodoors); $bodystyle = mysql_real_escape_string($bodystyle); $price = mysql_real_escape_string($price); $image['name'] = mysql_real_escape_string($image['name']); // Build our target path full string. This is where the file will be moved do // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, bmp or png"; header("Location: private-add-listing.php"); exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into privatelistings (make, model, exteriorcolour, enginesize, fueltype, yearregistered, transmission, mileage, nodoors, bodystyle, price, filename) values ('$make', '$model', '$exteriorcolour', '$enginesize', '$fueltype', '$yearregistered', '$transmission', '$mileage', '$nodoors', '$bodystyle', '$price', '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: private-add-listing-successfully.php?msg=Listing Added successfully"); exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: private-add-listing.php"); exit; } ?>I know the coding needs updating to mysqli and prevent sql injections but want to get it working first and then will do them parts Thank you in advance Kind regards Ian Ok, I have this code that is supposed to upload a csv file and save the contents into a specific sql table. I am getting an error when i hit submit that states the file is empty, meaning the csv file. I am thinking that the file isn't really being targeted i just don't know how to fix it. To start i have a php page with a the form and then i have another php page that is included in the form php page. The functions for submitting the csv info in the text file is located in the include file. here is the code: Code: [Select] $csv = new Quick_CSV_import(); $arr_encodings = $csv->get_encodings(); //take possible encodings list $arr_encodings["default"] = "[default database encoding]"; //set a default (when the default database encoding should be used) if(!isset($_POST["encoding"])) $_POST["encoding"] = "default"; //set default encoding for the first page show (no POST vars) if(isset($_POST["Go"]) && ""!=$_POST["Go"]) //form was submitted { $csv->file_name = $HTTP_POST_FILES['file_source']['tmp_name']; //optional parameters $csv->use_csv_header = isset($_POST["use_csv_header"]); $csv->field_separate_char = $_POST["field_separate_char"][0]; $csv->field_enclose_char = $_POST["field_enclose_char"][0]; $csv->field_escape_char = $_POST["field_escape_char"][0]; $csv->encoding = $_POST["encoding"]; //start import now $csv->import(); } else $_POST["use_csv_header"] = 1; ?> <tr> <td>Source CSV file to import:</td> <td rowspan="30" width="10px"> </td> <td><input type="file" name="file_source" id="file_source" class="edt" value="<?=$file_source?>"></td> </tr> and Code: [Select] class Quick_CSV_import { var $table_name = "tbl_product"; //where to import to var $file_name; //where to import from var $use_csv_header; //use first line of file OR generated columns names var $field_separate_char; //character to separate fields var $field_enclose_char; //character to enclose fields, which contain separator char into content var $field_escape_char; //char to escape special symbols var $error; //error message var $arr_csv_columns; //array of columns var $table_exists; //flag: does table for import exist var $encoding; //encoding table, used to parse the incoming file. Added in 1.5 version function Quick_CSV_import() { $this->file_name = $file_name; $this->arr_csv_columns = array(); $this->use_csv_header = true; $this->field_separate_char = ","; $this->field_enclose_char = "\""; $this->field_escape_char = "\\"; $this->table_exists = false; } function import() { if($this->table_name=="") $this->table_name = "temp_".date("d_m_Y_H_i_s"); $this->table_exists = false; $this->create_import_table(); if(empty($this->arr_csv_columns)) $this->get_csv_header_fields(); /* change start. Added in 1.5 version */ if("" != $this->encoding && "default" != $this->encoding) $this->set_encoding(); /* change end */ if($this->table_exists) { $sql = "LOAD DATA INFILE '".@mysql_escape_string($this->file_source). "' INTO TABLE `".$this-> table_name. "` FIELDS TERMINATED BY '".@mysql_escape_string($this->field_separate_char). "' OPTIONALLY ENCLOSED BY '".@mysql_escape_string($this->field_enclose_char). "' ESCAPED BY '".@mysql_escape_string($this->field_escape_char). "' ". ($this->use_csv_header ? " IGNORE 1 LINES " : "") ."(`".implode("`,`", $this->arr_csv_columns)."`)"; $res = @mysql_query($sql); $this->error = mysql_error(); } } //returns array of CSV file columns function get_csv_header_fields() { $this->arr_csv_columns = array(); $fpointer = fopen($file_name, "r"); if ($fpointer) { $arr = fgetcsv($fpointer, 10*1024, $this->field_separate_char); if(is_array($arr) && !empty($arr)) { if($this->use_csv_header) { foreach($arr as $val) if(trim($val)!="") $this->arr_csv_columns[] = $val; } else { $i = 1; foreach($arr as $val) if(trim($val)!="") $this->arr_csv_columns[] = "column".$i++; } } unset($arr); fclose($fpointer); } else $this->error = "file cannot be opened: ".(""==$this->file_name ? "[empty]" : @mysql_escape_string($this->file_name)); return $this->arr_csv_columns; } i just can't figure it out. could anyone help me out? the error i get says this: Warning: fopen() [function.fopen]: Filename cannot be empty in /Quick_CSV_import.php on line 83 |