PHP - Update Upload File Error , File Upload During Insert Is Disappear
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'");
Similar Tutorialsim doing smting basically wrong Code: [Select] <form action="" method="post"> <?php $x=1; $images = $_GET['images']; for( $i=0; $i<$images; $i++ ) { echo '<input name="ID" type="hidden" value="1234" /> <br> <input name="ImageURL['.$i.']" type="file" value=""/><br><br>'; } ?> <input name="submit" type="submit" /> <?php $con = mysql_connect("localhost","root","root"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_query("SET NAMES 'utf8'"); mysql_select_db("international", $con); if (isset($_POST['submit'])) for( $i=0; $i<$images; $i++ ) { $query=mysql_query("INSERT INTO images (ID,ImageURL) VALUES ('$_POST[ID]','$_POST[ImageURL]')"); exit; mysql_close($con); } ?></form> Code I'm using if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Successfully uploaded image!"; if (file_exists("img/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "img/" . $_FILES["file"]["name"]); echo "<a href='img/$filename'>Your File</a>; } } } else { echo "Invalid file"; } mysql_query("INSERT INTO $tbl (body, name, subject, ip, timestamp, img) VALUES ('$body', '$name', '$subject', '$ip', '$timestamp', '$imglink')"); mysql_query("INSERT INTO total (ip, subject, name, board) VALUES ('$ip','$subject','$name','$dfg')"); echo "<font color='red'><font size='15'><strong><center>Successfully posted to /$tbl/"; //print("<meta http-equiv='REFRESH' content='0;url=index.php?board=$tbl'>"); If I have the query on the top it runs, and the upload img doesn't && vice versa i need to upload files to a different folder dependint on option in form, make thumbnails, and store title and src for image and thumb in database table dependant on category. i think i'm pretty close, but there's still something wrong. Here is my upload form : Code: [Select] <form enctype="multipart/form-data" action="upload.php" method="POST"> Photo: <input type="file" name="photo"><br> Category: <select name="cat"> <option value="weddings">Weddings</option> <option value="music">Music</option> <option value="portraits">Portraits</option></select> Title: <input type="text" name="title"><br> <input type="submit" value="Upload photo"> </form> form processed by upload.php : Code: [Select] <?php require "db.php"; //Get form info $name=$_POST['name']; $title=$_POST['title']; $category=$_POST['cat']; $pic=($_FILES['photo']['name']); //set target dir source file width height $target = $cat."/"; $src = $target . basename( $_FILES['photo']['name']); $destination = $cat."/thumbs"; $thumbsrc = $destination . basename( $_FILES['photo']['name']); $width = 200; $height = 200; header("content-type: image/jpeg"); $src_img = imagecreatefromjpeg("$src"); $srcsize = getimagesize("$dest"); $dst_img = imagecreatetruecolor($width, $height); imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $width, $height, $srcsize[0], $srcsize[1]); imagejpeg($dst_img); //Unstert into db mysql_query("INSERT INTO `$category` VALUES ('$name', 'Stitle', '$src, $thumbsrc')") ; //move photo if(move_uploaded_file($_FILES['photo']['tmp_name'], $fulltarget)) { //Ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { //not ok echo "Sorry, there was a problem uploading your file."; } ?> call a script from main page Code: [Select] <div class="gallery"> <?php include "weddings/get.php" ?> </div> <div class="gallery"> <?php include "music/get.php" ?> </div> get.php displays links Code: [Select] <?php include "db.php"; $cat = weddings; $q = "SELECT id, title, src, thumbsrc FROM $cat"; $result = $mysqli->query($q) or die(mysqli_error($mysqli)); if ($result) { echo "<ul id='photos'> \n"; while ($row = $result->fetch_object()) { $title = $row->title; $src = $row->src; $thsrc = $row->thumbsrc; $id = $row->id; echo "<a href='$src' class="lightbox" rel="$cat" title="$name - $title"><img src='$thsrc' id='$id' alt='$name' /></a>": } echo "</ul>"; } ?> I think i'm going along the right sort of path, but i'm not sure. Hi. I have the following code: <?php $host=""; $username=""; $password=""; $db_name=""; $tbl_name="topic"; // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $name=$_POST['name']; $detail=$_POST['details']; $sql="INSERT INTO $tbl_name(topic, detail, datetime)VALUES('$name', '$detail', NOW())"; $result=mysql_query($sql); if($result){ echo("Topic created. "); $sql3="SELECT max(id) FROM $tbl_name"; $result3=mysql_query($sql3); $tbl_name2="top_img"; for($i=1; $i<11; $i++){ $uploaddir = '/imgs/'; $uploadfile = $uploaddir . basename($_FILES['img'.$i]['name']); echo '<pre>'; if (move_uploaded_file($_FILES['img'.$i]['tmp_name'], $uploadfile)) { echo "File is valid, and was successfully uploaded.\n"; } else { echo "Possible file upload attack!\n"; } }} echo 'Here is some more debugging info:'; print_r($_FILES); print "</pre>"; echo("<br><br><a href='site.html'>HOME</a>"); ?> And the error message: Quote Topic created. PHP Error Message Warning: move_uploaded_file(/imgs/Sunset.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/a7129718/public_html/test/add_topic.php on line 28 PHP Error Message Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/php73HyFd' to '/imgs/Sunset.jpg' in /home/a7129718/public_html/test/add_topic.php on line 28 Free Web Hosting Possible file upload attack! Possible file upload attack! Possible file upload attack! Possible file upload attack! Possible file upload attack! Possible file upload attack! Possible file upload attack! Possible file upload attack! Possible file upload attack! Possible file upload attack! Here is some more debugging info:Array ( [img1] => Array ( [name] => Sunset.jpg [type] => image/jpeg [tmp_name] => /tmp/php73HyFd [error] => 0 [size] => 71189 ) [img2] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 bla bla bla Any idea what the problem might be? Thanks in advance. Bye. Hi want to upload file using form's input type="file" then i want to display it on another page, As i am new to PHP i am doing this step by step so that I can test each step and go ahead. My first step is to upload file and check if its uploading in temp location.. I got same code from net.. I am using notepad++ thats why not sure abt syntax error, What I did is: <html> <body> <form action="index.php" method="POST" enctype="multipart/form-data"> Image: <input type="file" name="image"> <input type="submit" value="Upload"> </form> <?php mysql_connection("localhost","root","admin") or die(mysql_error()); mysql_select_db("searchdeals") or die(mysql_error()); echo $file = $_FILES['image']['tmp_name']; ?> </body> </html> hi, i am trying to code a file uploader in php using IIS server this is the code of the form: <html><body> <form method="post" enctype="multipart/form-data" action="processform.php"> <input type="hidden" name="MAX_FILE_SIZE" value="200000"> <input type="file" name="thefile"><br/> <input type="submit" value="Submit File...."> </form> </body></html> this is the code of processform.php <?php $upload_dir = "C:/Inetpub/wwwroot/cbt/upload/"; $upload_file = $upload_dir . basename($_FILES['thefile']['name']); if(copy($_FILE['thefile']['tmp_name'],$upload_file)){ echo "File copy was Successful!"; } else { echo "Oops... something went wrong..."; print_r($_FILES); } ?> now the problem is each time i try to click on the submit button after browsing any file it shows the message : Oops... something went wrong...Array ( [thefile] => Array ( [name] => 1.jpeg [type] => image/jpeg [tmp_name] => C:\temps\php13.tmp [error] => 0 [size] => 59592 ) ) help me guys...... wats the problem with the code ? Hello, i'm trying to upload a file through a page, on a local wamp server. Here's the code i'm using: Code: [Select] <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Upload" /> </form>This is the form i'm using to pass my file Code: [Select] <?php if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_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 "Stored in: " . $_FILES["file"]["tmp_name"] . "<br />"; if (move_uploaded_file($_FILES["file"]["tmp_name"], $_SERVER['DOCUMENT_ROOT']. "/template_example/slideshow/images/" . $_FILES["file"]["name"])) { echo "Stored in: " . $_SERVER['DOCUMENT_ROOT'] . "localhost/template_example/slideshow/images/" . $_FILES["file"]["name"]; } } ?> The problem comes up if i try to upload an image file of size 1,07 MB. upload_max_filesize on my php.ini is at 2M. I also tried changing it to 2000M just to see if thats the problem. The error code i'm getting is 2 which means: Value: "2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form." from what i got on the internet. My operating system is windows XP SP2 and i have wamp server installed. Please help! Can anyone help me to fix this two error?
#upload directory path mysqli_select_db($conn, "test2") or die(mysql_error()); Thank you !
Hi Guys, What I am doing is making a backup of a folder by zipping it on a server which is outside of web root, downloading a local copy to a web accessible place and then uploading the zip file back to the non web folder. I am using phpseclib's sftp to achieve this. The error I have is that when the file is uploaded to the non web area, the file is 0 bytes and cannot be used, the copy stored on the web accesible area is fine? The code I am using: Code: [Select] <?php if(isset($_GET['backup'])) { $worldname = $_GET['backup']; //checks to see if upload if(!is_dir("backups")) //create backup directory if not exist { mkdir("backups", 0777); } mkdir("backups/".$worldname, 0777); //make filename directory $main_dest = "backups/".$worldname.""; //set backup destination $delpath = "backups/"; //path which will be deleted later $sftp = new Net_SFTP($host); $sftp->login($root_user, $root_pass); //login to sftp $get = "/root/minecraft/".$worldname."/"; //get correct directory for backup get_folder($sftp, $get, $main_dest ); //execute command Zip('backups/'.$worldname.'','backups/'.$worldname.''.date("dmy-H:i").'.zip'); //make zip of folder $sftp->put('/root/minecraft/backups/'.$worldname.''.date("dmy-H:i").'.zip','backups/'.$worldname.' '.date("dmy-H:i").'.zip',NET_SFTP_LOCAL_FILE); //put zip file from web folder to root/backup folder rrmdir($delpath); //delete old folder (function below) //unlink('backups/'.$worldname.''.date("dmy-H:i").'.zip'); deletes web copy header('Location: index.php'); } The line which is causing the issue is: Quote $sftp->put('/root/minecraft/backups/'.$worldname.''.date("dmy-H:i").'.zip','backups/'.$worldname.' '.date("dmy-H:i").'.zip',NET_SFTP_LOCAL_FILE); The function is basically $remotefile, $data, $mode Can anyone take a guess at what is causing the issue? PHP max upload size is 200mb, the files are around 5mb, the timeout is 360 seconds? Cheers Dave[/code] Need some help with this script. I'm looking to limit the type of file you can upload to my server the script uploads ok but i when i try t view the uploaded file but i get an error cant find file extension for this file what am i doing wrong as i'm very new to php . Thank for your help in advance Code: [Select] <?php $allowedExtensions = array("jpg","jpeg","gif","png","bmp"); foreach ($_FILES as $image) { if ($image['tmp_name'] > '') { if (!in_array(end(explode(".", strtolower($image['name']))), $allowedExtensions)) { die($image['name'].' is an invalid file type!<br/>'. '<a href="javascript:history.go(-1);">'. '<< Go Back</a>'); } } } $target = "testimages/"; $target = $target . basename( $_FILES['image']['name']); // $company=$_POST['company']; $image=($_FILES['image']['name']); mysql_connect("localhost", "user", "pass") or die(mysql_error()) ; mysql_select_db("testupload") or die(mysql_error()) ; mysql_query("INSERT INTO `table` (company, image) VALUES ('$company', '$image')") ; if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { echo "Sorry, there was a problem uploading your file."; } ?> Hiya, Firstly, I'm a complete novice, apologies! But I have got my upload.php working which is nice. I will post the code below. However, I would now like to restrict the file size and file type to only word documents. I currently have a restriction of 200KB but it's not working - no idea why as I've looked at other similar codes and they look the same. Also, just to complicate things - can I stop files overwriting each other when uploaded? At the moment, if 2 people upload files with the same name one will overwrite the other. Is this too many questions in 1? Any help is very much appreciated! Code below: Code: [Select] <form enctype="multipart/form-data" action="careers.php" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form> <?php $target = "upload/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition if ($uploaded_size > 200) { echo "Your file is too large.<br>"; $ok=0; } //This is our limit file type condition if ($uploaded_type =="text/php") { echo "No PHP files<br>"; $ok=0; } //Here we check that $ok was not set to 0 by an error if ($ok==0) { Echo "Sorry your file was not uploaded"; } //If everything is ok we try to upload it else { if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "Your file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded."; } else { echo "Sorry, there was a problem uploading your file."; } } ?> In this multi file upload form, choose three images, click submit and preview the images on the preview page. If the user wishes to delete or replace an image, click edit and the form will go back to the previous page. Select the replace radio button for example on one of the three images and select a new image from the file input prompt and click submit. The form will go to the preview page again to display the images. During this process the image names are being input into a table and the images are being moved to a directory. The table is `id` AUTO_INCREMENT, `image0` `image1` `image2` `status` So input name='image[image0]' can be directed to table `image0` and so on. The code for keep and delete work fine, but how do I replace an image? I have two foreach blocks. The first one deletes the image file from the directory and deletes the image name from the table, but the second foreach dose not move the new image file into the directory. Thanks. <input type='radio' name='image[image0]' value='keep' checked='checked'/> <input type='radio' name='image[image0]' value='delete' /> <input type='radio' name='image[image0]' value='replace' /> <input type="file" name="image[]" /> <input type='radio' name='image[image1]' value='keep' checked='checked'/> <input type='radio' name='image[image1]' value='delete' /> <input type='radio' name='image[image1]' value='replace' /> <input type="file" name="image[]" /> <input type='radio' name='image[image2]' value='keep' checked='checked'/> <input type='radio' name='image[image2]' value='delete' /> <input type='radio' name='image[image2]' value='replace' /> <input type="file" name="image[]" /> <?php if (isset($_POST['status'])) { $status = $_POST['status']; $confirm_code = $status; #--------------------------- replace -------------------------------------------- if (isset($_POST['submitted']) && ($image = $_POST['image'])) { foreach($image as $imageKey => $imageValue) { if ($imageValue == 'replace') { $query = "SELECT $imageKey FROM table WHERE status = '$status' "; if($result = $db->query( $query )){ $row = $result->fetch_array(); } unlink( UPLOAD_DIR.$row[0] ); $query = "UPDATE table SET $imageKey = '' WHERE status = '$status' "; } } foreach($image as $imageKey => $imageValue) { if ($imageValue == 'replace') { $filenm = $_FILES['image']['name']; $file = $_FILES['image']['tmp_name']; move_uploaded_file($file, UPLOAD_DIR . $filenm); $filename[] = $filenm; $query = "INSERT INTO table VALUES ('','$filename[0]','$filename[1]','$filename[2]','$confirm_code')"; } } } } ?> I havent included the whole title as it wouldnt let me but I was wondering if someone could help me on this? I know this is possible as torrentflux caters for this but unsure of where to start. I dont want to allow file or directory uploads or creation in my /etc/php.ini file (this is turned off). Yet then torrentflux allows me to link a torrent from an external source (using legal downloads of course ) but then it uploads it on my server and creates folders on a per user basis. How is this possible can someone give me some pointers please? I look forward to any replies, Jeremy. So, I'm learning how to upload pictures into a system from my awesome PHP book. I've looked and looked through the script but I can't figure out whats wrong with it. Goal: The script is meant to save a full version of the image in the images folder and a thumbnail in the thumbnail folder. Bug: The full image does not appear in any folder, and the thumbnail is created but its put in the images folder. I've checked the GD library, and everything is supported. image_effect.php <?php //change this path to match your images directory $dir ='C:/x/xampp/htdocs/images'; //change this path to match your fonts directory and the desired font putenv('GDFONTPATH=' . 'C:/Windows/Fonts'); $font = 'arial'; // make sure the requested image is valid if (isset($_GET['id']) && ctype_digit($_GET['id']) && file_exists($dir . '/' . $_GET['id'] . '.jpg')) { $image = imagecreatefromjpeg($dir . '/' . $_GET['id'] . '.jpg'); } else { die('invalid image specified'); } // apply the filter $effect = (isset($_GET['e'])) ? $_GET['e'] : -1; switch ($effect) { case IMG_FILTER_NEGATE: imagefilter($image, IMG_FILTER_NEGATE); break; case IMG_FILTER_GRAYSCALE: imagefilter($image, IMG_FILTER_GRAYSCALE); break; case IMG_FILTER_EMBOSS: imagefilter($image, IMG_FILTER_EMBOSS); break; case IMG_FILTER_GAUSSIAN_BLUR: imagefilter($image, IMG_FILTER_GAUSSIAN_BLUR); break; } // add the caption if requested if (isset($_GET['capt'])) { imagettftext($image, 12, 0, 20, 20, 0, $font, $_GET['capt']); } //add the logo watermark if requested if (isset($_GET['logo'])) { // determine x and y position to center watermark list($width, $height) = getimagesize($dir . '/' . $_GET['id'] . '.jpg'); list($wmk_width, $wmk_height) = getimagesize('images/logo.png'); $x = ($width - $wmk_width) / 2; $y = ($height - $wmk_height) / 2; $wmk = imagecreatefrompng('images/logo.png'); imagecopymerge($image, $wmk, $x, $y, 0, 0, $wmk_width, $wmk_height, 20); imagedestroy($wmk); } // show the image header('Content-Type: image/jpeg'); imagejpeg($image, '', 100); ?> check_image.php <?php include 'db.inc.php'; //connect to MySQL $db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die ('Unable to connect. Check your connection parameters.'); mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db)); //change this path to match your images directory $dir ='C:/x/xampp/htdocs/images'; //change this path to match your thumbnail directory $thumbdir = $dir . '/thumbs'; //change this path to match your fonts directory and the desired font putenv('GDFONTPATH=' . 'C:/Windows/Fonts'); $font = 'arial'; // handle the uploaded image if ($_POST['submit'] == 'Upload') { //make sure the uploaded file transfer was successful if ($_FILES['uploadfile']['error'] != UPLOAD_ERR_OK) { switch ($_FILES['uploadfile']['error']) { case UPLOAD_ERR_INI_SIZE: die('The uploaded file exceeds the upload_max_filesize directive ' . 'in php.ini.'); break; case UPLOAD_ERR_FORM_SIZE: die('The uploaded file exceeds the MAX_FILE_SIZE directive that ' . 'was specified in the HTML form.'); break; case UPLOAD_ERR_PARTIAL: die('The uploaded file was only partially uploaded.'); break; case UPLOAD_ERR_NO_FILE: die('No file was uploaded.'); break; case UPLOAD_ERR_NO_TMP_DIR: die('The server is missing a temporary folder.'); break; case UPLOAD_ERR_CANT_WRITE: die('The server failed to write the uploaded file to disk.'); break; case UPLOAD_ERR_EXTENSION: die('File upload stopped by extension.'); break; } } //get info about the image being uploaded $image_caption = $_POST['caption']; $image_username = $_POST['username']; $image_date = @date('Y-m-d'); list($width, $height, $type, $attr) = getimagesize($_FILES['uploadfile']['tmp_name']); // make sure the uploaded file is really a supported image $error = 'The file you uploaded was not a supported filetype.'; switch ($type) { case IMAGETYPE_GIF: $image = imagecreatefromgif($_FILES['uploadfile']['tmp_name']) or die($error); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($_FILES['uploadfile']['tmp_name']) or die($error); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($_FILES['uploadfile']['tmp_name']) or die($error); break; default: die($error); } //insert information into image table $query = 'INSERT INTO images (image_caption, image_username, image_date) VALUES ("' . $image_caption . '", "' . $image_username . '", "' . $image_date . '")'; $result = mysql_query($query, $db) or die (mysql_error($db)); //retrieve the image_id that MySQL generated automatically when we inserted //the new record $last_id = mysql_insert_id(); // save the image to its final destination $image_id = $last_id; imagejpeg($image, $dir . '/' . $image_id . '.jpg'); imagedestroy($image); } else { // retrieve image information $query = 'SELECT image_id, image_caption, image_username, image_date FROM images WHERE image_id = ' . $_POST['id']; $result = mysql_query($query, $db) or die (mysql_error($db)); extract(mysql_fetch_assoc($result)); list($width, $height, $type, $attr) = getimagesize($dir . '/' . $image_id . '.jpg'); } if ($_POST['submit'] == 'Save') { // make sure the requested image is valid if (isset($_POST['id']) && ctype_digit($_POST['id']) && file_exists($dir . '/' . $_POST['id'] . '.jpg')) { $image = imagecreatefromjpeg($dir . '/' . $_POST['id'] . '.jpg'); } else { die('invalid image specified'); } // apply the filter $effect = (isset($_POST['effect'])) ? $_POST['effect'] : -1; switch ($effect) { case IMG_FILTER_NEGATE: imagefilter($image, IMG_FILTER_NEGATE); break; case IMG_FILTER_GRAYSCALE: imagefilter($image, IMG_FILTER_GRAYSCALE); break; case IMG_FILTER_EMBOSS: imagefilter($image, IMG_FILTER_EMBOSS); break; case IMG_FILTER_GAUSSIAN_BLUR: imagefilter($image, IMG_FILTER_GAUSSIAN_BLUR); break; } // add the caption if requested if (isset($_POST['emb_caption'])) { imagettftext($image, 12, 0, 20, 20, 0, $font, $image_caption); } //add the logo watermark if requested if (isset($_POST['emb_logo'])) { // determine x and y position to center watermark list($wmk_width, $wmk_height) = getimagesize('images/logo.png'); $x = ($width - $wmk_width) / 2; $y = ($height - $wmk_height) / 2; $wmk = imagecreatefrompng('images/logo.png'); imagecopymerge($image, $wmk, $x, $y, 0, 0, $wmk_width, $wmk_height, 20); imagedestroy($wmk); } // save the image with the filter applied imagejpeg($image, $dir . '/' . $_POST['id'] . '.jpg', 100); //set the dimensions for the thumbnail $thumb_width = $width * 0.10; $thumb_height = $height * 0.10; //create the thumbnail $thumb = imagecreatetruecolor($thumb_width, $thumb_height); imagecopyresampled($thumb, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height); imagejpeg($thumb, $dir . '/' . $_POST['id'] . '.jpg', 100); imagedestroy($thumb); ?> <html> <head> <title>Here is your pic!</title> </head> <body> <h1>Your image has been saved!</h1> <img src="images/<?php echo $_POST['id']; ?>.jpg" /> </body> </html> <?php } else { ?> <html> <head> <title>Here is your pic!</title> </head> <body> <h1>So how does it feel to be famous?</h1> <p>Here is the picture you just uploaded to our servers:</p> <?php if ($_POST['submit'] == 'Upload') { $imagename = 'images/' . $image_id . '.jpg'; } else { $imagename = 'image_effect.php?id=' . $image_id . '&e=' . $_POST['effect']; if (isset($_POST['emb_caption'])) { $imagename .= '&capt=' . urlencode($image_caption); } if (isset($_POST['emb_logo'])) { $imagename .= '&logo=1'; } } ?> <img src="<?php echo $imagename; ?>" style="float:left;"> <table> <tr><td>Image Saved as: </td><td><?php echo $image_id . '.jpg'; ?></td></tr> <tr><td>Height: </td><td><?php echo $height; ?></td></tr> <tr><td>Width: </td><td><?php echo $width; ?></td></tr> <tr><td>Upload Date: </td><td><?php echo $image_date; ?></td></tr> </table> <p>You may apply special options to your image below. Note: saving an image with any of the options applied <em>cannot be undone</em>.</p> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <div> <input type="hidden" name="id" value="<?php echo $image_id;?>"/> Filter: <select name="effect"> <option value="-1">None</option> <?php echo '<option value="' . IMG_FILTER_GRAYSCALE . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GRAYSCALE) { echo ' selected="selected"'; } echo '>Black and White</option>'; echo '<option value="' . IMG_FILTER_GAUSSIAN_BLUR . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GAUSSIAN_BLUR) { echo ' selected="selected"'; } echo '>Blur</option>'; echo '<option value="' . IMG_FILTER_EMBOSS . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_EMBOSS) { echo ' selected="selected"'; } echo '>Emboss</option>'; echo '<option value="' . IMG_FILTER_NEGATE . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_NEGATE) { echo ' selected="selected"'; } echo '>Negative</option>'; ?> </select> <br/><br/> <?php echo '<input type="checkbox" name="emb_caption"'; if (isset($_POST['emb_caption'])) { echo ' checked="checked"'; } echo '>Embed caption in image?'; echo '<br/><br/><input type="checkbox" name="emb_logo"'; if (isset($_POST['emb_logo'])) { echo ' checked="checked"'; } echo '>Embed watermarked logo in image?'; ?> <br/><br/> <input type="submit" value="Preview" name="submit" /> <input type="submit" value="Save" name="submit" /> </div> </form> </body> </html> <?php } ?> Any help appreciated. <td><label for='images'> <b>File to upload:</b> </label></td> <td><input type='file' name = 'drama_image' '<?php echo $row['drama_image']; ?>'/></ </tr> <?php $target_path = "images/"; $target_path = $target_path . basename( $_FILES['images']['name']); if(move_uploaded_file($_FILES['images']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['images']['name']). " has been uploaded"; } else{ echo $row['drama_image']; } ?> ['drama_image'] is the name of the file I wanna echo it out in the box of file upload so when I save , the default picture will still be there instead of being overwritten as the box does not have any value in it. 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 ?> HI All, I have a form submission that uploads a photo as well as submitting other data. I would like to change the name of the photo to the id of the person record (created automatically on by the database) then a hyphen, then their first name and lastname. (i am flexible on this). This file name will also need to be submitted into the person record so the photo and the person can be linked. I am struggling with this one - but here is the code i have so far.
<?php include 'includes/dbconn.php'; $target_dir = "img/people/"; $target_file = $target_dir . basename($_FILES["personHeadshot"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); if ($_SERVER['REQUEST_METHOD']=='POST'){ $fn = $_POST['fname']; $ln = $_POST['lname']; $ad1 = $_POST['ad1']; $ad2 = $_POST['ad2']; $city = $_POST['city']; $post = $_POST['postcode']; $tel = $_POST['phone']; $email = $_POST['email']; $crole = $_POST['comRole']; $OFA = $_POST['OFA']; $playerType = $_POST['playerType']; $team = $_POST['primaryTeam']; $stmt = $conn->prepare(" INSERT IGNORE INTO person (fname, lname, committee_role_id, player_type_id, team_id, ad1, ad2, city, postcode, mobile, email, on_field_auth_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) "); $stmt -> bind_param(ssiiissssssi, $fn, $ln, $crole, $playerType, $team, $ad1, $ad2, $city, $post, $tel, $email, $OFA); $stmt -> execute(); // Check if image file is a actual image or fake image //photo upload $check = getimagesize($_FILES["personHeadshot"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } //photo upload header("location: ../admin-people-list.php"); } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["personHeadshot"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["personHeadshot"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["personHeadshot"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } }
Hello! I have this validation script that seems to work great until I add the size validation. I'm ready to pull my hair out! Can someone tell me what I'm doing wrong? Code: [Select] if (isset($_POST['Submit'])) { $user_id = $userdata[user_id]; $number_of_file_fields = 0; $number_of_uploaded_files = 0; $number_of_moved_files = 0; $uploaded_files = array(); $max_filesize = 5242880; // Maximum filesize in BYTES (currently 5MB). $upload_directory = dirname(__file__) . '/'.$user_id.'/'; //set upload directory if (!is_dir($upload_directory)) { mkdir($upload_directory, 0777, true); } for ($i = 0; $i < count($_FILES['images']['name']); $i++) { $number_of_file_fields++; if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not $number_of_uploaded_files++; if($_FILES['images']['size'] > $max_filesize){ echo "<b class='red'>Max file size is 5MB.</b><br/>"; $sz = true; } $ext = validate_extension($_FILES['images']['name'][$i]); if (($ext == true) && ($sz == true)){ $uploaded_files[] = $_FILES['images']['name'][$i]; if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . $_FILES['images']['name'][$i])) { $number_of_moved_files++; } }else { echo "<b class='red'>File extention error. Only .doc, .pdf, .jpg and .gif files are allowed. </b><br/>"; } } } if ($number_of_uploaded_files >= 1){ echo "Number of files submitted:<b class='red>".$number_of_uploaded_files."</b><br/>"; echo "Number of successfully uploaded files:<b class='red>".$number_of_moved_files."</b><br/><br/>"; echo "Uploaded File Name(s):<br/>" . implode('<br/>', $uploaded_files); } } As of now it results in every uploaded file returning the error "Max file size is 5MB." Hey all So have been working on a file upload script, it was uploading the file but also adding the path name instead of NULL to mysql when no image was to upload, that is now fixed however now it won't upload the actual image to the directory. I tried undoing the mysql changes but it still won't upload the image to the directory. Am testing on my own computer using xampp so no file permission issues, plus it was working before. Any help much appreciated. Thanks <?php $product_code = mysqli_real_escape_string($conn, $_POST['product_code']); $product_name = mysqli_real_escape_string($conn, $_POST['product_name']); $category = mysqli_real_escape_string($conn, $_POST['category']); $filter = mysqli_real_escape_string($conn, $_POST['filter']); $description = mysqli_real_escape_string($conn, $_POST['description']); $specification = mysqli_real_escape_string($conn, $_POST['specification']); $price = mysqli_real_escape_string($conn, $_POST['price']); $target_dir = "../images/products/"; if (!isset ($_FILES["img1"]["name"])) { $target_file1 = NULL; } else { if (!empty($_FILES["img1"]["name"])) { $target_file1 = $target_dir . basename($_FILES["img1"]["name"]); } else { $target_file1 = NULL; } } if (!isset ($_FILES["img2"]["name"])) { $target_file2 = NULL; } else { if (!empty($_FILES["img2"]["name"])) { $target_file2 = $target_dir . basename($_FILES["img2"]["name"]); } else { $target_file2 = NULL; } } if (!isset ($_FILES["img3"]["name"])) { $target_file3 = NULL; } else { if (!empty($_FILES["img3"]["name"])) { $target_file3 = $target_dir . basename($_FILES["img3"]["name"]); } else { $target_file3 = NULL; } } if (!isset ($_FILES["img4"]["name"])) { $target_file4 = NULL; } else { if (!empty($_FILES["img4"]["name"])) { $target_file4 = $target_dir . basename($_FILES["img4"]["name"]); } else { $target_file4 = NULL; } } $uploadOk = 1; $imageFileType1 = strtolower(pathinfo($target_file1,PATHINFO_EXTENSION)); $imageFileType2= strtolower(pathinfo($target_file2,PATHINFO_EXTENSION)); $imageFileType3 = strtolower(pathinfo($target_file3,PATHINFO_EXTENSION)); $imageFileType4 = strtolower(pathinfo($target_file4,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check1 = getimagesize($_FILES["img1"]["tmp_name"]); $check2 = getimagesize($_FILES["img2"]["tmp_name"]); $check3 = getimagesize($_FILES["img3"]["tmp_name"]); $check4 = getimagesize($_FILES["img4"]["tmp_name"]); if($check1 !== false) { echo "File is an image - " . $check1["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file1)) { echo "Sorry, image one already exists."; $uploadOk = 0; } if($imageFileType1 != "jpg" && $imageFileType1 != "png" && $imageFileType1 != "jpeg" && $imageFileType1 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img1."; $uploadOk = 0; } if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img1"]["tmp_name"], $target_file1)) { echo "The file ". htmlspecialchars( basename( $_FILES["img1"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image one."; } } echo '<br />'; if($check2 !== false) { echo "File is an image - " . $check2["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file2)) { echo "Sorry, image two already exists."; $uploadOk = 0; } if($imageFileType2 != "jpg" && $imageFileType2 != "png" && $imageFileType2 != "jpeg" && $imageFileType2 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img2."; $uploadOk = 0; } if (isset ($target_file2)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img2"]["tmp_name"], $target_file2)) { echo "The file ". htmlspecialchars( basename( $_FILES["img1"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image two."; } } } echo '<br />'; if($check3 !== false) { echo "File is an image - " . $check3["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file3)) { echo "Sorry, image three already exists."; $uploadOk = 0; } if($imageFileType3 != "jpg" && $imageFileType3 != "png" && $imageFileType3 != "jpeg" && $imageFileType3 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img3."; $uploadOk = 0; } if (isset ($target_file3)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img3"]["tmp_name"], $target_file3)) { echo "The file ". htmlspecialchars( basename( $_FILES["img3"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image three."; } } } echo '<br />'; if($check4 !== false) { echo "File is an image - " . $check4["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file4)) { echo "Sorry, image four already exists."; $uploadOk = 0; } if($imageFileType4 != "jpg" && $imageFileType4 != "png" && $imageFileType4 != "jpeg" && $imageFileType4 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img4."; $uploadOk = 0; } if (isset ($target_file4)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img4"]["tmp_name"], $target_file4)) { echo "The file ". htmlspecialchars( basename( $_FILES["img4"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image four."; } } } } echo '<br />'; $image1 = basename($target_file1); $image2 = basename($target_file2); $image3 = basename($target_file3); $image4 = basename($target_file4); // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO products (product_code, product_name, category, filter, description, specification, img1, img2, img3, img4, price) VALUES('$product_code', '$product_name', '$category', '$filter', '$description', '$specification', '$image1', '$image2', '$image3', '$image4', '$price')"; if (mysqli_query($conn, $sql)) { echo "Product Added successfully, Now on to the Sizes"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } ?>
How do I Upload Multiple Files using a PHP form and script? 10 files at one time would be great. Ultimately I need a photo upload and management script. Here is my current single file upload form: <form action="upload.php" method="post" enctype="multipart/form-data"> <label for="file">Upload a Photo:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html> Here is the Php Script: <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 200000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]); echo "Stored in: " . "uploads/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?> |