PHP - Upload One File And Create Multiple Files
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 Similar TutorialsHi 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
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 Hey guys, im uploading up to 48 PNG images from one page, this works fine when theres only a few images, but doesnt work the more there are. Is there any reason for this? Is it to do with php.ini or is that per file, not for the whole upload? Thanks. Danny. So I'm a little confused and hoping someone can help me understand. I have a form that I use to upload a file, html with browse button, etc. The php file creates a directory based on the a value (lastname) from the form, so the folder files creates a directory named the value lastname. My problem is that I can't get the upload function to put the file in the newly created directory. So here is the upload script. $foldername = $_POST['lastname']; // Desired folder structure $structure = 'files/'.$foldername.''; // To create the nested structure, the $recursive parameter // to mkdir() must be specified. if (!mkdir($structure, 0777, true)) { die('Failed to create folders...'); } $target = "files/"; $target = $target . basename( $_FILES['userfile']['name']) ; if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target)) { echo "<center>The file ". basename( $_FILES['userfile']['name']). " has been uploaded.</center>"; } else { echo "No File was uploaded"; } So when I edited the target, it just changed the filename . What should I change in the code above to upload the file to the new directory? Thanks again, Sanchez 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 ?> 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." Hello i need help, I am creating a small social networking website in which i want dat a user can upload music files as well with some descriptions ,the description and file path should be stored in database and the mp3 file should be stored in a seprate folder i want a PHP script for this. If any one knows it then please help me. I am trying to convert 6 files into a single 1 php file. I have attached the original files. I need help because I don't know where I am going wrong. this what I have done so far : <?php session_start(); if ($_SESSION['ON'] =="FALSE" || $_SESSION['ON']==null) { header( 'Location: index.php?error=invalid-login' ); session_unset(); session_destroy(); exit(); } ?> <html><head><meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>LOGIN WEB SESSION</title> <link rel="stylesheet" type="text/css" href="loginsession.css" /> </head> <body> <?php // If the step is one, show the correct form // if ($step == 0) { echo '<form action="index.php?step=2" method="post"> <table> <tr><td width="100">Username:</td><td width="200"><input type="text" name="username"></td></tr> <tr><td width="100">Password:</td><td width="200"><input type="password" name="password"></td></tr> <tr><td colspan="2" align="center"><input type="submit" value="Login"></td></tr> </table> </form>'; } else if ($step == 1) { // Create the step 2 section of the page // function clean($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } $user = clean($_POST['username']); $pass = clean($_POST['password']); if ($user == "webdeveloper" && $pass == "master") { session_start(); $_SESSION['username'] = $user; $_SESSION['password'] = $pass; $_SESSION['ON']="TRUE"; $lifetime=600; setcookie(session_name(),session_id(),time()+$lifetime); header( 'Location: index.php?step=2' ) ; exit(); } else { header( 'Location: index.php' ); session_destroy(); exit(); } } else if ($step == 2) <div>LOGIN WELCOME</div> <div> HERE IS YOUR USER DATA:<br /> <label class="data">username:'; <?php echo $_SESSION['username'] ?> <br> password: <?php echo $_SESSION['password'] ?> <br></label> HERE IS YOUR SESSION DATA:<br /> <label class="data"> <?php echo (session_name().": ".session_id()) ?><br> <?php echo ("SESSION DATA: ".session_encode() )?> </label> </div>index.php?step=3">Logoff</a></div> } else if ($step == 3) { // Create the step 4 section of the page // header( 'Location: index.php' ); session_start(); session_unset(); session_destroy(); exit(); } ?> </body> </html> This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=357764.0 Hi Guys, I need help for in storing data from PHP from array in mysql. I'm very new to PHP/Mysql and have started learing it just few weeks back. I'm tryting to build a website for myself. I'm having tough time trying to insert the data from Form in mysql. I have a form where user update the company name and insert there product name with there image. I want to rename the image with the corresponding text field value and insert the upload path in the table. my FORM Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <style type="text/css"> body,td,th { color: #000; font-family: Tahoma, Geneva, sans-serif; font-size: 80%; } body { background-color: #9CF; } table { background: #CCF; } th { font: bold normal 16px/normal "Times New Roman", Times, serif; text-transform: capitalize; color: #00F; background: #FFC; } td { font: bold 14px Georgia, "Times New Roman", Times, serif; text-transform: capitalize; color: #3A00FF; background: #FF9; } </style> </head> <body> <form action="upload-file1.php" method="post" enctype="multipart/form-data" name="form"> <strong>Company Name:</strong> <input name="product" type="text" /> <br /> <table> <tr bgcolor="#FF9900"> <th colspan="3" bgcolor="#CCFFFF">filter </th> <th colspan="5" bgcolor="#CCFFFF">heater</th> </tr> <tr><td>filter1</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater1: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> <tr><td>filter2</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater2: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> <tr><td>filter3</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater3: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> <tr><td>filter4</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater4: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> <tr><td>filter5</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater5: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> </table> <br /> <br /> <input name="submit" type="submit" value="submit" /> </form> </body> </html> my PHP Code Code: [Select] <?php require("connect.php"); ?> <?php $product = $_POST['product']; echo $product; if(isset($_POST["submit"])){ $sql = "INSERT INTO company (product) VALUES ('$product')"; $query = mysql_query($sql) OR DIE(mysql_error()); $comp_id = mysql_insert_id(); echo $sql; } ?> <?php function filter() { if(isset($_POST['submit'])) { foreach($_POST['filter'] as $key => $val) { if(trim($val) != '') $filter[] = $val; } $total_records_filter = count($filter); for($i = 0; $i < $total_records_filter; $i++) { $prod_val = $filter[$i]; $sql_prod = "INSERT INTO filter(filter_id, filter) VALUES('', '$prod_val')"; echo $sql_prod.'<br>'; mysql_query($sql_prod) OR die(mysql_error()); } } } filter(); function heater() { if(isset($_POST['submit'])) { foreach($_POST['heater'] as $key => $val) { if(trim($val) != '') $heater[] = $val; } $total_records_heater = count($heater); for($i = 0; $i < $total_records_heater; $i++) { $dir_val = $heater[$i]; $sql_dir = "INSERT INTO heater(heater_id, heater) VALUES('', '$dir_val')"; echo $sql_dir.'<br>'; mysql_query($sql_dir) OR die(mysql_error()); } } } heater(); ?> <?php mysql_close($link)?> My Table structure company comp_id int(5) PK product varchar(50) No filter filter_id int(5) PK filter varchar(25) No filter_path varchar(100) No heater heater_id int(5) PK heater varchar(25) No heater_path varchar(100) No company_filter id int(5) PK comp_id int(5) PK FK (From company table) filter_id int(5) PK FK (From filter table) company_heater id int(5) PK comp_id int(5) PK FK (From company table) heater_id int(5) PK FK (From heater table) Regards BW Hi can someone assist me with adding a second upload that grabs all files from within a directory. 1. user select .csv file (coding down for that) 2. user select folder with .docx files in side (this folder will only have docx files) 3. on submit .csv and all .docx files are upload to /temp_docx/ folder 4. the .csv has a matching docx_id that relates to the .docx file name (ex file 1.docx == docx_id = 1 in the csv file) so every time an insert is done a move_file happens and 1.docx would be moved to /docx_files/ 5. and if there is ever an error or no match at the end output all errors. I think the part where i'm stuck and confused the most is handling the second upload where all docx files in the folder are upload and looped through moving and inserting Code: [Select] <?php if(isset($_POST['submit'])) { $filename = file_get_contents($_FILES['uploadedfile']['tmp_name']); $handle = fopen("$filename", "r"); while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) { $import="INSERT into kmmb_member1(docx_id,no_ahli,no_pin,nama,no_ic_baru,no_ic_lama) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')"; mysql_query($import) or die(mysql_error()); } fclose($handle); print "Import done"; } else { print "<form action='import.php' method='post'>"; print "Type file name to import:<br />"; print "Select csv file: <input name='uploadedfile' type='file' /><br />"; print "<input type='submit' name='submit' value='submit' /></form>"; } ?> ok so say I have a file with .. this information in one file Code: [Select] 548402354 7e99c2c49be0ad1a95fd3b4a2f65fc941e9cf194 548402225 9e0b2788f21a317eb76159f3e0c4e4a090492f2a 548402329 1aa382935c94d73f58bdb3203686cc0124fb3443 548402596 c41655fa8f14346cbd8a656a18ecb82caa3c1f9c 548402535 558e1ee14f2423681668a168a3980304ac54bd15 548402456 48ee03332c417cab51eaec13b415fde8c0b6a641 548400202 5bf3400e3c074eb8b42a962dc7e60777d2b2848a 548400842 cc672d4785ec5b9e22db7b60e203286c840c4f37 548400682 547c8ac38243b0f9a94609177d0dd12194059aa5 548400810 54afebbb3e884fea5563c017b18dd390ff1ff034 548400581 ec7305326b5514cbf05ab4a78647ed756da9db55 548400431 b3dcaa272c759ebe4e5b00053ef390b21b23f60c and I want to take and split the contents into 6 different files.. So it would take the first 2 lines and write to filename 1.txt, then it would take the 2 lines after that and write a file named 2.txt, so on and so forth Any help is appreciated, thanks 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 Hello, I'm working on a script which should read lines from a file keyword.txt create a new file with that variable name, insert the content close and loop through all the lines in the keyword file. The loop itself works but now that i'm adding the fopen fwrite and fclose i'm running into trouble. I'm not that great a coder and have pieced this together so far. I'd appreciate any suggestions on how to fix the fopen and other file functions to create unique files using the keywords from the file Thanks in advance <?php $read_file = file('keywords.txt'); foreach($read_file as $var) { $file = fopen($var, "x"); $content = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <html xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> <title>This is the title</title> </head> <body> <h2>The keyword is $var</h2> <p><p> </body> </html>"; fwrite($file, $content); fclose($file); } ?> files that upload during insert/submit form was gone , only files upload during the update remain , is the way query for update multiple files is wrong ? $targetDir1= "folder/pda-semakan/ic/"; if(isset($_FILES['ic'])){ $fileName1 = $_FILES['ic']['name']; $targetFilePath1 = $targetDir1 . $fileName1; //$main_tmp2 = $_FILES['ic']['tmp_name']; $move2 =move_uploaded_file($_FILES["ic"]["tmp_name"], $targetFilePath1); } $targetDir2= "folder/pda-semakan/sijil_lahir/"; if(isset($_FILES['sijilkelahiran'])){ $fileName2 = $_FILES['sijilkelahiran']['name']; $targetFilePath2 = $targetDir2 . $fileName2; $move3 =move_uploaded_file($_FILES["sijilkelahiran"]["tmp_name"], $targetFilePath2); } $targetDir3= "folder/pda-semakan/sijil_spm/"; if(isset($_FILES['sijilspm'])){ $fileName3 = $_FILES['sijilspm']['name']; $targetFilePath3 = $targetDir3 . $fileName3; $move4 =move_uploaded_file($_FILES["sijilspm"]["tmp_name"], $targetFilePath3); } $query1=("UPDATE semakan_dokumen set student_id='$noMatrik', email= '$stdEmail', surat_tawaran='$fileName', ic='$fileName1',sijil_lahir='$fileName2',sijil_spm= '$fileName3' where email= '$stdEmail'");
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? I have code written for image uploading, but it doesn't allow multiple images on a single upload, and doesn't re-size. Anyone willing to share a good upload script that will do the following?: -Allow multiple image uploads (10+ per submission), -Re-size images on upload, and -Rename images. Thanks Brett Hi everyone, I have a page that i use to upload images to my website, i got a bit fed up of uploading one at a time so i decided to add multiple file fields to the form to upload multiple images at the same time. Im having a few problems, iv read up he http://www.php.net/manual/en/features.file-upload.multiple.php and it seems all i have to do is add [] to the form names to turn them into arrays. However when i come to upload the images, i keep getting the "$error[] = "Incorrect format!...." error from the code below. I cant seem to figure out what the problem is. Could anybody please point me in the right direction? <?php session_start(); $id = $_SESSION['id']; $connect = mysql_connect("localhost","leemp5_admin","p7031521"); mysql_select_db("leemp5_database"); $query = mysql_query("SELECT * FROM users WHERE id='$id'"); $row = mysql_fetch_assoc($query); $username = $row['username']; $submit = $_POST['submit']; $type = $_FILES['image']['type']; $size = $_FILES['image']['size']; $max_size = "1000"; $width = "100"; $height = "100"; $error = array(); function make_thumb($image_name,$filename,$new_width,$new_height) { $ext=getExtension($image_name); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $source_image=imagecreatefromjpeg($image_name); if(!strcmp("png",$ext)) $source_image=imagecreatefrompng($image_name); if(!strcmp("gif",$ext)) $source_image=imagecreatefromgif($image_name); $old_x=imageSX($source_image); $old_y=imageSY($source_image); $ratio1=$old_x/$new_width; $ratio2=$old_y/$new_height; if($ratio1>$ratio2) { $thumb_width=$new_width; $thumb_height=$old_y/$ratio1; } else { $thumb_height=$new_height; $thumb_width=$old_x/$ratio2; } $destination_image=ImageCreateTrueColor($thumb_width,$thumb_height); imagecopyresampled($destination_image,$source_image,0,0,0,0,$thumb_width,$thumb_height,$old_x,$old_y); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) { imagejpeg($destination_image,$filename); } if(!strcmp("png",$ext)) { imagepng($destination_image,$filename); } if(!strcmp("gif",$ext)) { imagegif($destination_image,$filename); } imagedestroy($destination_image); imagedestroy($source_image); } function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } if($submit) { $image=$_FILES['image']['name']; if ($image) { $filename = stripslashes($_FILES['image']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $error[] = "Incorrect format! Please make sure your image is a .jpg, .jpeg, .png or .gif file."; } else { $size=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); if ($sizekb > $max_size*1024) { $error[] = "Your image is too big! The maximum upload size is 1MB."; } else { $image_name=time().'.'.$extension; $newname="uploads/" . $username . "/images/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { $error[] = "There was an error uploading your image. Please try again!"; } else { $thumb_name='uploads/' . $username . '/images/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,$width,$height); } } } } else { $error[] = "Please select an image to upload!"; } if(empty($error)) { echo "Upload Successfully!<br />"; echo '<img src="'.$thumb_name.'">'; mysql_query("INSERT INTO images VALUES ('','$username','$image_name','','','','','uploads/$username/images/$image_name','uploads/$username/images/thumbs/thumb_$image_name','$type','$size')"); } else { echo implode($error); } } ?> <form method="post" enctype="multipart/form-data" action="upload_images.php"> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="submit" name="submit" value="Upload"> </form> Thanks 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. 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. |