PHP - Counting Files In Multiple Upload Script
Hi all,
I am having a few problems. Basically I have a multiple file upload script, that I can get successfully to save the images to a folder. However what I am trying to do is enter a record in the database for every file that is uploaded, giving it a picture id, album id and user id (p_id, a_id, u_id). From here I then want to rename the image to the p_id in the database(auto_increment). I am starting just by counting the amount of images uploaded and then creating a record. However I seem to have something wrong, as when I tried it to upload 1 image as a test it created 388,000 blank records! (just p_id as auto) Can someone explain what I am doing wrong? I am quite new to php. <?php $result = array(); $result['time'] = date('r'); $result['addr'] = substr_replace(gethostbyaddr($_SERVER['REMOTE_ADDR']), '******', 0, 6); $result['agent'] = $_SERVER['HTTP_USER_AGENT']; if (count($_GET)) { $result['get'] = $_GET; } if (count($_POST)) { $result['post'] = $_POST; } if (count($_FILES)) { $result['files'] = $_FILES; } // we kill an old file to keep the size small if (file_exists('script.log') && filesize('script.log') > 102400) { unlink('script.log'); } $log = @fopen('script.log', 'a'); if ($log) { fputs($log, print_r($result, true) . "\n---\n"); fclose($log); } // Validation $error = false; if (!isset($_FILES['Filedata']) || !is_uploaded_file($_FILES['Filedata']['tmp_name'])) { $error = 'Invalid Upload'; } else { include('../includes/config.php'); session_start(); $a_id = $_SESSION["a_id"]; $u_id = $_SESSION["id"]; $togo = $result['files']; $i=0; while ($i < $togo) { $query = mysql_query("INSERT into images (a_id,u_id) VALUES ('$a_id','$u_id')"); $i++; } } ?> Many Thanks Similar TutorialsHi 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 looked around all overr, but cant find what im looking for. Everything I have found is about uploading multile files, what I need to do is upload one file and copy it so there is 3 files. Here is an example of what I need to accomplish. Upload file picture1.jpg From picture1.jpg create 3 files - smallimage_picture1.jpg, largeimage_picture1.jpg & smallimage_picture1_thumb.jpg Each file will need to be copied to a /products directory and also an entry for each file name placed in mysql database table. I don't think this is as simple as it sounds to do in PHP, but i am very willing to learn so if anyone knows of a good tutorial that get get me started that would be super. regards DB
I have a hopefully small issue on a form submitting data to the mysql database table and email. The email side works fine as does the adding the data to the database table but if I upload two files, it stores the support ticket twice in the database table where as I want to store just once and the files be stored as a array in the database table. I got the code from the link https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/
<?php require_once "registerconfig.php"; if (isset($_POST['submit'])) { // File upload configuration $targetDir = "support-ticket-images/"; $allowTypes = array('pdf','doc','docx','jpg','png','jpeg','gif'); $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = ''; // Escape user inputs for security $ticket_subject = htmlentities($_POST['ticket_subject'], ENT_QUOTES); $ticket_message = strip_tags($_POST['ticket_message'], ENT_QUOTES); $ticket_status ='PENDING SUPPORT'; $username = htmlentities($_SESSION["user_name"], ENT_QUOTES); $user_id = htmlentities($_SESSION["user_id"], ENT_QUOTES); $fileNames = array_filter($_FILES['files']['name']); if(!empty($fileNames)){ foreach($_FILES['files']['name'] as $key=>$val){ // File upload path $fileName = basename($_FILES['files']['name'][$key]); $targetFilePath = $targetDir . $fileName; // Check whether file type is valid $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){ // Image db insert sql $insertValuesSQL .= "('".$ticket_subject."','".$ticket_message."','".$fileName."','".$ticket_status."','".$username."', '".$user_id."'),"; }else{ $errorUpload .= $_FILES['files']['name'][$key].' | '; } }else{ $errorUploadType .= $_FILES['files']['name'][$key].' | '; } } if(!empty($insertValuesSQL)){ $insertValuesSQL = trim($insertValuesSQL, ','); // Insert image file name into database $insert = $link->query("INSERT INTO DB TABLE NAME (ticket_subject, ticket_message, file_name, ticket_status, user_name, user_id) VALUES $insertValuesSQL"); if($insert){ $to = "emailaddress"; $subject = "A new support ticket has been submitted"; $message = " <strong>$username</strong> has just created a support ticket, below is the support ticket <br /><br /> <u>Support Ticket Details</u> <br /><br> <strong>Support Ticket Subject</strong>: $ticket_subject <br/><br><strong>Support Ticket Message</strong>: $ticket_message <p><strong><u>Support Ticket Files</u></strong> <br> <img src='$fileName'> "; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n"; // More headers $headers .= 'From: <noreply@emailaddress>' . "\r\n"; $mail=mail($to,$subject,$message,$headers); $errorUpload = !empty($errorUpload)?'Upload Error: '.trim($errorUpload, ' | '):''; $errorUploadType = !empty($errorUploadType)?'File Type Error: '.trim($errorUploadType, ' | '):''; $errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType; header("location: support-ticket-confirmation?user=$username"); }else{ $statusMsg = "Sorry, there was an error uploading your file."; } } }else{ $statusMsg = 'Please select files to upload.'; } // Display status message echo $statusMsg; } ?> The structure of the db table column is file_name, VARCHAR(255), latin1_swedish_ci, NOT NULL Hi All, I need some help blocking files that don't pass authentication from being uploaded to the server. Here is my script (below). It correctly throws errors, but regardless of error / no-error, the file is uploaded. For example, the only files allowed to be uploaded should be .png, .jpeg, .gif -- but I see .flv .docx etc in the destination folder. You'll see below a variable for each of the error messages. They basically say that the file name is too long, too big, not an allowed file type, or English characters only allowed in file title name. Again the errors work properly, but regardless files are uploaded to the "quiz_images" folder. What do I need to do to stop the upload if an error is triggered? Thank you for your help... here is the code snip: Code: [Select] $directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']); $uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'quiz_images/'; $fieldname = 'file'; if ($_POST[submit]) { if ($_POST[title] <> "") { $a = TRUE; } else { $a = FALSE; $content .= "<p>$enter_title</p>\n"; } if ($_POST[video] <> "") { $b = TRUE; } else { $b = FALSE; $content .= "<p>$enter_embed</p>\n"; } if ($_POST[description_text] <> "") { $c = TRUE; } else { $c = FALSE; $content .= "<p>$enter_description</p>\n"; } if ($_POST[submit] <> "") { $f = TRUE; } else { $f = FALSE; $content .= "<p>$sorry_error</p>\n"; } if (is_uploaded_file($_FILES[$fieldname]['tmp_name'])) { $g = TRUE; } else { $g = FALSE; $content .= "<p>$sorry_error</p>\n"; } if (getimagesize($_FILES[$fieldname]['tmp_name'])){ $h = TRUE; } else { $h = FALSE; $content .= "<p>$error2</p>\n"; } if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 50000)) { $i = TRUE; } else { $i = FALSE; $content .= "<p>$error2</p>\n"; } if(preg_match('#^[a-z0-9_\s-\.]*$#i', $pic) ) { $k = TRUE; } else { $k = FALSE; $content .= "<p>$error3</p>\n"; } $desc_length = strlen($pic); $limit = 40; if ($desc_length <= $limit) { $l = TRUE; } else { $l = FALSE; $content .= "<p>$error4</p>\n"; } $now = time(); while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name'])) { $now++; } if (move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)){ $j = TRUE; } else { $j = FALSE; $content .= "<p>$enter_thumb</p>\n"; } $pic=$now++.'-'.$_FILES[$fieldname]['name']; if ($a AND $b AND $c AND $f AND $g AND $h AND $i AND $j AND $k AND $l) {............ <!doctype html> <html> <head> <meta content="text/html; charset=utf-8" http-equiv="content-type"> <title>Untitled Document</title> </head> <body> <form action="upload_image.php" method="post" enctype="multipart/form-data"> <label>select page<input type="file" name="image"> <input type="submit" name="upload"> </label> </form> <?php if(isset($_POST['upload'])) { $image_name=$_FILES['image']['name']; //return the name ot image $image_type=$_FILES['image']['type']; //return the value of image $image_size=$_FILES['image']['size']; //return the size of image $image_tmp_name=$_FILES['image']['tmp_name'];//return the value if($image_name=='') { echo '<script type="text/javascript">alert("please select image")</script>'; exit(); } else { $ex=move_uploaded_file($image_tmp_name,"image/".$image_name); if($ex) { echo 'image upload done "<br>"'; echo $image_name.'<br>'; echo $image_size.'<br>'; echo $image_type.'<br>'; echo $image_tmp_name.'<br>'; } else { echo 'error'; } } } ?> </body> </html>I make this simple script for upload files like photo , It's work correctly ,but not upload the large files ex 8MB images 12MB images Edited by Ch0cu3r, 04 October 2014 - 09:50 AM. Modified topic title - changed download to upload Hello Everyone, I have been working on this add product script but cannot seem to get it to work when two files are uploaded. All the data is uploaded to a database, including the two images filenames and then the two files are added to the server to different locations. Here is the form: <form action="addnewproduct.php" method="post" name="addproduct" id="addproduct" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="10000000"> <table width="98%" border="0" cellspacing="0" cellpadding="5"> <tr> <td width="28%" valign="middle" class="style1 style2"><div align="right" class="style5">Product Title </div></td> <td width="72%" class="style5"><input class="form" type="text" name="title" accesskey="1" tabindex="1" /></td> </tr> <tr> <td valign="middle" class="style1 style2"><div align="right" class="style5">Category</div></td> <td class="style5"> <select class="form" name="cat" accesskey="2" tabindex="2"> <option value="Boards">Boards</option> <option value="Accessories">Accessories</option> <option value="Clothing">Clothing</option> </select> </td> </tr> <tr> <td valign="top" class="style5"><div align="right">Description</div></td> <td class="style5"><textarea class="form" name="description" cols="50" rows="5" accesskey="3" tabindex="3"></textarea></td> </tr> <tr> <td valign="top" class="style5"><div align="right">Price<br /> <span class="d">Including </span></div></td> <td class="style5"><input class="form" type="text" name="price" accesskey="4" tabindex="4" /></td> </tr> <tr> <td valign="top" class="style5"><div align="right">Paypal Link<br /> <span class="d">Including</span></div></td> <td class="style5"><input class="form" type="text" name="paypal" accesskey="5" tabindex="5" /></td> </tr> <tr> <td valign="top" class="style5"><div align="right">Thumbnail<br /> <span class="d">Image should be 100 x 100 </span></div></td> <td class="style5"> <input style="padding:2px; border:1px #999 solid; color:blue;" name="userfile[]" type="file" id="userfile[]"> </td> </tr> <tr> <td valign="top" class="style5"><div align="right">Image<br /> <span class="d">Image should be 300 x 450 </span></div></td> <td class="style5"><input style="padding:2px; border:1px #999 solid; color:blue;" name="userfile[]" type="file" id="userfile[]" /></td> </tr> <tr> <td valign="top" class="style5"><div align="right"></div></td> <td class="style5"><input class="form" type="submit" name="upload" value="upload" accesskey="6" tabindex="6" /></td> </tr> </table> </form> And here is the script: <?php $uploadDir = 'upload/'; $uploadDir2= "upload/big".$HTTP_POST_FILES['userfile']['name'][1]; copy($HTTP_POST_FILES['userfile']['tmp_name'][1], $uploadDir2); if(isset($_POST['upload'])) { $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $largeimage = $_FILES['userfile']['name'][1]; $filePath = $uploadDir . $fileName; $result = move_uploaded_file($tmpName, $filePath); if (!$result) { echo "Error uploading file"; exit; } include 'config.php'; include 'opendb.php'; if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); $largeimage = addslashes($largeimage); } $query = "INSERT INTO Products (title, description, price, paypal, cat, image, large) ". "VALUES ('$_POST[title]','$_POST[description]','$_POST[price]','$_POST[paypal]','$_POST[cat]','$fileName','$largeimage')"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); include 'closedb.php'; echo 'Product Uploaded'; ?> Not sure if this is the right forum, but I have a database that I will need to populate with a large number of rows (2000+). I have written a PHP script that uploads individual entries. Is it possible to use something like a spreadsheet where I can set out the rows/columns as they will appear in the database, and then upload in one go rather than uploading each row individually? Thanks for any observations and/or help. Hi all, As you will see this is my first post in I really hope somebody can nail this for me, as I have been working on this for some time and I cannot get it to work. Basically this is the final part of a CMS I'm building, and all was fine until I needed to build in an option of a multiple image uploader to accompany all other stock details. I have managed to nail the 'insert' part of the multiple image uploader in this case up to 4 images, and the code is below for this part, any help with improvements though will be greatly appreciated. Code: [Select] if(isset($_POST['btnsubmit'])) { $flag=$_POST['flag']; if ($flag==0) { $name=$_POST['txtname']; $desc1=$_POST['e1m1']; $meta=$_POST['txtmeta']; $sr=$_POST['srno1']; $name=$_POST['txtname']; $ref=$_POST['Ref']; $desc=$_POST['e1m1']; $maker=$_POST['Maker']; $date=$_POST['Date']; $weight=$_POST['Weight']; $height=$_POST['Height']; $depth=$_POST['Depth']; $width=$_POST['Width']; $price=$_POST['txtprice']; $sold=$_POST['txtsold']; $active=$_POST['active']; $pcats=$_POST['pcats']; $subcats=$_POST['subcats']; $str_str=''; $p=''; $j=0; for($i=0;$i<=3;$i++){ $j++; $p=$_REQUEST['p$j']; $file=$_FILES['pic']['name'][$i]; if(!empty($file) ){ $str_str.=",pic$j='$file'"; } else if(!empty($p))$str_str.=",pic$j='$p'"; $path1="imgdata/stock/".$file; copy($_FILES['pic']['tmp_name'][$i], $path1); } $q24=mysql_query("update stock set stock_Name='$name', stock_MetaTitle='$meta', parent_Category='$pcats', sub_Category='$subcats', stock_Image='imgdata/stock/$pic[0]', stock_Image2='imgdata/stock/$pic[1]', stock_Image3='imgdata/stock/$pic[2]', stock_Image4='imgdata/stock/$pic[3]', stock_Ref='$ref', stock_Description='$desc1', stock_Maker='$maker', stock_Date='$date', stock_Weight='$weight', stock_Height='$height', stock_Depth='$depth',stock_Width='$width', stock_Price='$price', stock_Sold='$sold', stock_Active='$active', stock_DateTime='$dt2' where stock_Id=$sr") or die (mysql_error()); $flag=1; $conf="Data Updated Successfully - Click <a href='http://www.accendsandbox.co.uk/adminSallam/admin_categories.php'>here</a> to continue"; $update="1"; Code: [Select] <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 1 (Main):</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 2:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 3:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 4:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <input type="submit" name="btnsubmit" value="Submit"> <input type="submit" name="btndelete" value="Delete" DEFANGED_OnClick="return check();"> <input type="hidden" name="srno1" value="<?= $rows["stock_Id"];?>"> <input type="hidden" name="action" value="Upload"> All seems to be fine above, I can upload 1,2,3 or 4 images and the image goes into the server and the path to the database. But I then needed the option for my client to be able to click to edit a certain stock and then aswel as edit the other details, if he wanted to change one pic, no pics or all 4 he could and when he clicked submit, if there was a new image it would change if not it would stay as it is. So here is my attempt and at the moment it doesnt work, so I'm looking for help of any kid and anything can change. Code: [Select] $name=$_POST['txtname']; $ref=$_POST['Ref']; $desc=$_POST['e1m1']; $maker=$_POST['Maker']; $date=$_POST['Date']; $weight=$_POST['Weight']; $height=$_POST['Height']; $depth=$_POST['Depth']; $width=$_POST['Width']; $price=$_POST['txtprice']; $sold=$_POST['txtsold']; $meta=$_POST['txtmeta']; $active=$_POST['active']; $pcats=$_POST['pcats']; $subcats=$_POST['subcats']; $pic1=''; for($i=0;$i<4;$i++){ if(isset($_FILES['pic1']['name'][$i]))$pic1[$i]=$_FILES['pic1']['name'][$i]; else $pic1[$i]=''; } for($i=0;$i<4;$i++){ if(isset($_FILES['pic1']['name'][$i]))$path1= "./imgdata/stock/".$_FILES['pic1']['name'][$i]; //echo $_FILES['pic1']['tmp_name'][$i]." :". $path1; if(!empty($_FILES['pic1']['name'][$i])&&isset($_FILES['pic1']['name'][$i]))copy($_FILES['pic1']['tmp_name'][$i], $path1); } $q=mysql_query("insert into stock (stock_Name, stock_MetaTitle, parent_Category, sub_Category, stock_Ref, stock_Description, stock_Maker, stock_Date, stock_Weight, stock_Height, stock_Depth, stock_Width, stock_Price, stock_Sold, stock_Image, stock_Image2, stock_Image3, stock_Image4, stock_Active, stock_DateTime) values('$name','$meta','$pcats','$subcats','$ref','$desc','$maker','$date','$weight','$height','$depth','$width','$price','$sold','imgdata/stock/$pic1[0]','imgdata/stock/$pic1[1]','imgdata/stock/$pic1[2]','imgdata/stock/$pic1[3]','$active','$dt2')") or die (mysql_error()); $conf="Data Inserted Successfully - Click <a href='http://www.accendsandbox.co.uk/adminSallam/admin_stock.php'>here</a> to continue"; $update=1; Code: [Select] <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 1 (Main):</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p1" value="<?php echo $pic1;?>" /> <img src="<?php echo $pic1;?>" height="100px" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 2:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p2" value="<?php echo $pic2;?>" /> <img src="<?php echo $pic2;?>" height="100px" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 3:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p3" value="<?php echo $pic3;?>" /> <img src="<?php echo $pic3;?>" height="100px" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 4:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p4" value="<?php echo $pic4;?>" /> <img src="<?php echo $pic4;?>" height="100px" /> </td> </tr> What happens above as its all on the same page, is when a stock item is selected to be edited the form to update the images changes to the image upload options above, instead of the original ones for a new stock item at the top of this post. I can provide anything you need to help me with this, so please can somebody take a look and see if it can be got working, as its been a long problem for me this. Cheers I know it needs a for loop, but i don't know where in the code i should be putting it? Code: [Select] function check_input($value) { // Stripslashes if (get_magic_quotes_gpc()) { $value = stripslashes($value); } // Quote if not a number if (!is_numeric($value)) { $value = "'" . mysql_real_escape_string($value) . "'"; } return $value; } $_POST = array_map('check_input', $_POST); $sql="INSERT INTO testimonials (CustomerName, Town, Testimonial, SortOrder, Images) VALUES ({$_POST['customername']}, {$_POST['town']}, {$_POST['testimonial']}, {$_POST['sort_order']}, '$imgname' )"; } if (!mysql_query($sql,$con)) { die("<br>Query: $sql<br>Error: " . mysql_error() . '<br>'); } echo "<p align=center><b>1 testimonial added</b></p>"; mysql_close($con); Thanks in Advance, Steve I know how to count the files: <?php $dir = $_SERVER[DOCUMENT_ROOT]."/api/sigs/cache/".$i[id]."/"; $files = scandir($dir); $result = count($files); printf("$result Signatures Generated"); ?> But i'm trying to make it so it only counts the files that were modified recently (That Day). So far I have managed to create an upload process which uploads a picture, updates the database on file location and then tries to upload the db a 2nd time to update the Thumbnails file location (i tried updating the thumbnails location in one go and for some reason this causes failure) But the main problem is that it doesn't upload some files Here is my upload.php <?php include 'dbconnect.php'; $statusMsg = ''; $Title = $conn -> real_escape_string($_POST['Title']) ; $BodyText = $conn -> real_escape_string($_POST['ThreadBody']) ; // File upload path $targetDir = "upload/"; $fileName = basename($_FILES["file"]["name"]); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); $Thumbnail = "upload/Thumbnails/'$fileName'"; if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){ // Allow certain file formats $allowTypes = array('jpg','png','jpeg','gif','pdf', "webm", "mp4"); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ // Insert image file name into database $insert = $conn->query("INSERT into Threads (Title, ThreadBody, filename) VALUES ('$Title', '$BodyText', '$fileName')"); if($insert){ $statusMsg = "The file ".$fileName. " has been uploaded successfully."; $targetFilePathArg = escapeshellarg($targetFilePath); $output=null; $retval=null; //exec("convert $targetFilePathArg -resize 300x200 ./upload/Thumbnails/'$fileName'", $output, $retval); exec("convert $targetFilePathArg -resize 200x200 $Thumbnail", $output, $retval); echo "REturned with status $retval and output:\n" ; if ($retval == null) { echo "Retval is null\n" ; echo "Thumbnail equals $Thumbnail\n" ; } }else{ $statusMsg = "File upload failed, please try again."; } }else{ $statusMsg = "Sorry, there was an error uploading your file."; } }else{ $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, mp4, webm & PDF files are allowed to upload.'; } }else{ $statusMsg = 'Please select a file to upload.'; } //Update SQL db by setting the thumbnail column to equal $Thumbnail $update = $conn->query("update Threads set thumbnail = '$Thumbnail' where filename = '$fileName'"); if($update){ $statusMsg = "Updated the thumbnail to sql correctly."; echo $statusMsg ; } else { echo "\n Failed to update Thumbnail. Thumbnail equals $Thumbnail" ; } // Display status message echo $statusMsg; ?> And this does work on most files however it is not working on a 9.9mb png file which is named "test.png" I tested on another 3.3 mb gif file and that failed too? For some reason it returns the following Updated the thumbnail to sql correctly.Updated the thumbnail to sql correctly. Whereas on the files it works on it returns REturned with status 0 and output: Retval is null Thumbnail equals upload/Thumbnails/'rainbow-trh-stache.gif' Failed to update Thumbnail. Thumbnail equals upload/Thumbnails/'rainbow-trh-stache.gif'The file rainbow-trh-stache.gif has been uploaded successfully. Any idea on why this is? Hello, all: been trying to convert this little single-file upload to multiple by naming each file form-field as "userfile[]" as it's supposed to automatically treat them as an array.. but no luck! Can you guide me as to what am I doing wrong?? appreciate the help! Code: [Select] <?php if (!isset($_REQUEST["seenform"])) { ?> <form enctype="multipart/form-data" action="#" method="post"> Upload file: <input name="userfile[]" type="file" id="userfile[]"> Upload file: <input name="userfile[]" type="file" id="userfile[]"> <input type="submit" value="Upload"> <input type="hidden" name="seenform"> </form> <?php } else { // upload begins $userfiles = array($_FILES['userfile']); foreach ($userfiles as $userfile) { // foreach begins $uploaded_dir = "uploads/"; $userfile = $_FILES['userfile']["name"]; $path = $uploaded_dir . $userfile; if (move_uploaded_file($_FILES['userfile']["tmp_name"], $path)) { print "$userfile file moved"; // do something with the file here } else { print "Move failed"; } } // foreach ends } // upload ends ?> I have code written for image uploading, but it doesn't allow multiple images on a single upload, and doesn't re-size. Anyone willing to share a good upload script that will do the following?: -Allow multiple image uploads (10+ per submission), -Re-size images on upload, and -Rename images. Thanks Brett My prof hasn't gotten back to me and he doesn't seem like even he knows how to do it so I'm posting here for some help. We've barely done any script writing yet and I can't seem to figure out how to go about doing it. He wants us to modify the existing script so that it generates a random number from 1 - 1000 and then counts the number of guesses and outputs how many guesses at the end. It won't open in the browser so I'm not sure what's wrong. Any help would be much appreciated!
This is what I have so far:
<?php if (!isset($_POST["guess"])) { $message = "Welcome to the guessing machine!"; $_POST["numtobeguessed"] = rand(1,1000); $_POST["counter"] = 0; } else if ($_POST["guess"] > $_POST["numtobeguessed"]) { $message = $_POST["guess"]." is too big! Try a smaller number."; $_POST["counter"]++; } else if ($_POST["guess"] < $_POST["numtobeguessed"]) { $message = $_POST["guess"]." is too small! Try a larger number."; $_POST["counter"]++; } else { // must be equivalent $message = "Well done! It took you '$_POST["counter"]' tries!"; } ?> <html> <head> <title>A PHP number guessing script</title> </head> <body> <h1><?php echo $message; ?></h1> <form action="" method="POST"> <p><strong>Type your guess he </strong> <input type="text" name="guess"></p> <input type="hidden" name="numtobeguessed" value="<?php echo $_POST["numtobeguessed"]; ?>" ></p> <input type="hidden" name="counter" value="<?php echo $_POST["counter"]; ?>" <p><input type="submit" value="submit your guess"/></p> </form> </body> </html> Hi I'm working with the following code to count the number of files in a directory, however, it doesn't seem to count files in subdirectories, does anyone have any ideas how I can get it to? Thanks! The code so far is as follows: <?php function numFilesInDir($directory, $includeDirs = false) { $files = glob($directory.'/*'); if($files === false) { user_error(__FUNCTION__."(): Invalid directory ($directory)"); return false; } $numFiles = count($files); if(!$includeDirs) //remove ! to count folders instead of files { $dirs = glob($directory.'/*', GLOB_ONLYDIR); $numFiles = $numFiles - count($dirs); } return $numFiles; } $numFiles = numFilesInDir('../media/Images'); if($numFiles === false) { echo "<p>Oops....something went wrong.</p>\n"; } else { echo "<p>There are $numFiles pictures in the Image folder.</p>\n"; } ?> I am looking to allow people to also upload pdf and doc ad txt files can you show me how to convert this script . Thanks. Code: [Select] [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"); if (in_array($file['type'], $valid_types)) return 1; return 0; } [/php] Good afternoon,
I wrote a script for uploading files to ftp server. When I lunch this on local server(wamp) it does upload files into ftp server.
When I run the same script on my host provider(iPage) it doesn't upload files. Any advices?
Have a look at the code please.
form
<code>
<form enctype="multipart/form-data" action="upload.php" method="post"> <table > <tr> <td> <input name="userfile" type="file"> </td> </tr> <tr> <td > <input type="Submit" value="Add file"> </td> </tr> </table> </form> </code> upload.php <code> <?php ###################################################################### /* For remote servers */ ini_set("max_execution_time", 100000000000); // execution time must be bigger for larger files $file = basename($_FILES['userfile']['name']); //$remote_file = "/home/users/web/b1729/ipg.marcinkopecnet/remote_upload/$file"; $remote_file = "/remote_upload/$file"; /* Define ftp server connection */ $ftp_server = "right_server"; $ftp_user_name = "right_username"; $ftp_user_pass = "right_password"; // set up basic connection $conn_id = ftp_connect($ftp_server, 21) or die ("Cannot connect to host"); // turn passive mode on ftp_pasv($conn_id, true); // login with username and password $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("Cannot login"); // upload a file if ($upload = ftp_put($conn_id, $remote_file, $_FILES['userfile']['tmp_name'], FTP_BINARY)) { // check upload status: print (!$upload) ? 'Cannot upload' : 'Upload complete'; print "\n"; //echo "successfully uploaded $file\n"; } else { echo "There was a problem while uploading $file\n"; } // close the connection ftp_close($conn_id); ###################################################################### ?> </code> Edited by MarcinUK, 04 September 2014 - 05:39 PM. Good day: I have a simple uploader form to upload video files. FLV and mpg files will upload without problems. But mp4, m4v, ogg and webm files will not upload. I get this error: Warning: copy() [function.copy]: Unable to access in /mounted-storage/home7/sub007/sc30390-PTUD/**********.com/admin123/insertvideo.php on line 32 Error Video not loaded. I have read about adding the files in config/mimes.php but I do not see that folder or files in my hosting service (which is servage). Any help will be appreciated. Thanks. I am using the following code to upload images for my products. How can I modify it to not only upload the product image, but upload it a 2nd time resized for thumbnail or is it even possible? Code: [Select] 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("images/" . $_FILES['file']['name'])) { echo $_FILES['file']['name'] . " already exists. "; } else { move_uploaded_file($_FILES['file']['tmp_name'], "images/$companyname/$materialdir/$prefix$modelnumber.jpg"); //"images/" . $companyname . "/" . $materialdir/$prefix$modelnumber . ".jpg"); //"images/" . $_FILES['file']['name']);//change to Timp folder // "C:/upload/" . $_FILES['file']['name']);//change to Timp folder //echo "Stored in: " . "C:/xampp/htdocs/Timp/UserLogin/upload/" . $_FILES["file"]["name"]; echo "Stored in: images/$companyname/$materialdir/$prefix$modelnumber.jpg"; } } $photo = "images/$companyname/$materialdir/$prefix$modelnumber.jpg"; |