PHP - Upload Script Not Working
Similar TutorialsHello 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'; ?> I want to let users select and upload a file. The select form and upload sritp work when they are on different pages, but I want them on the same page with the upload script executing only if the form has been submitted. Here the upload form <!--select the file --> <form enctype="multipart/form-data" action="manage_files.php" method="POST">Please choose a file to upload: <input name="uploaded" type="file" /><input type="submit" value="Upload" /></form> ... and here's the upload code... <!--upload the file --> <?php if (isset($_POST['submit'])) { $target = "safes/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition //if ($uploaded_size > 350000) //{ //echo "Your file is too large.<br>"; //$ok=0; //} //if (!($uploaded_type=="application/zip")) { //echo "You may only upload ZIP 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 "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else { echo "Sorry, there was a problem uploading your file."; } } } ?> What am I missing? Thanks for any help! 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 I currently have the following script used on my site to upload files. When the linked web page executes it, however, I receive the infamous Parse Error - Unexpected '<' in x:/xxxx. The problem lies in Line 11 where I attempt to define a command that will display a message box to the user upon successful file upload. The syntax is not correct and I was hoping someone would be able to help me with it. Here is the contents of the PHP file. <?php // Where the file is going to be placed $target_path = $_SERVER['DOCUMENT_ROOT'] . "/file_uploads/"; /*Add the original filename to our target path. Result is "uploads/filename.extension"*/ $target_path=$target_path.basename($_FILES['file']['name']); //Move file to upload directory if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) { echo <script type="text/javascript">alert("Upload was successful. Thank you for your contribution")</script>; } else{ echo "There was a problem submitting the file. Plese try again!"; } ?> Thank you in advance for any help. Hi i have found this code : <?php if (isset($_POST['submit_bilde'])) { $error = 'Wrong image file..'; define( 'THUMBNAIL_IMAGE_MAX_WIDTH', 250 ); define( 'THUMBNAIL_IMAGE_MAX_HEIGHT', 250 ); function generate_image_thumbnail( $source_image_path, $thumbnail_image_path ) { list( $source_image_width, $source_image_height, $source_image_type ) = getimagesize( $source_image_path ); switch ( $source_image_type ) { case IMAGETYPE_GIF: $source_gd_image = imagecreatefromgif( $source_image_path ); break; case IMAGETYPE_JPEG: $source_gd_image = imagecreatefromjpeg( $source_image_path ); break; case IMAGETYPE_PNG: $source_gd_image = imagecreatefrompng( $source_image_path ); break; } if ( $source_gd_image === false ) { return false; } $thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH; $thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT; $source_aspect_ratio = $source_image_width / $source_image_height; $thumbnail_aspect_ratio = $thumbnail_image_width / $thumbnail_image_height; if ( $source_image_width <= $thumbnail_image_width && $source_image_height <= $thumbnail_image_height ) { $thumbnail_image_width = $source_image_width; $thumbnail_image_height = $source_image_height; } elseif ( $thumbnail_aspect_ratio > $source_aspect_ratio ) { $thumbnail_image_width = ( int ) ( $thumbnail_image_height * $source_aspect_ratio ); } else { $thumbnail_image_height = ( int ) ( $thumbnail_image_width / $source_aspect_ratio ); } $thumbnail_gd_image = imagecreatetruecolor( $thumbnail_image_width, $thumbnail_image_height ); imagecopyresampled( $thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height ); imagejpeg( $thumbnail_gd_image, $thumbnail_image_path, 100 ); imagedestroy( $source_gd_image ); imagedestroy( $thumbnail_gd_image ); return true; } define( 'UPLOADED_IMAGE_DESTINATION', 'annonsebilder/orginaler/' ); define( 'THUMBNAIL_IMAGE_DESTINATION', 'annonsebilder/thumbs/' ); function process_image_upload( $field ) { $temp_image_path = $_FILES[ $field ][ 'tmp_name' ]; $temp_image_name = $_FILES[ $field ][ 'name' ]; list( , , $temp_image_type ) = getimagesize( $temp_image_path ); if ( $temp_image_type === NULL ) { return false; } switch ( $temp_image_type ) { case IMAGETYPE_JPEG: break; default: return false; } $uploaded_image_path = UPLOADED_IMAGE_DESTINATION . $temp_image_name; move_uploaded_file( $temp_image_path, $uploaded_image_path ); $random_digit=rand(0000000000000,9999999999999); $thumbnail_image_path = THUMBNAIL_IMAGE_DESTINATION . preg_replace( '{\\.[^\\.]+$}', '.jpg', $annonse_ref.'_'.$random_digit.'.jpg' ); $result = generate_image_thumbnail( $uploaded_image_path, $thumbnail_image_path ); return $result ? array( $uploaded_image_path, $thumbnail_image_path ) : false; } for ( $i = 1; $i <= 5; $i++ ) { if ( $_FILES[ 'Image' . $i ][ 'error' ] == 0 ) { $result = process_image_upload( 'Image' . $i ); } } if ( $result === false ) { echo $error; } else { //THIS ECHO SHIT IS KILLIN' ME!!! echo '<br />1: '.$result['1'] ; echo '<br />2: '.$result['2']; echo '<br />3: '.$result['3']; echo '<br />4: '.$result['4']; echo '<br />5: '.$result['5']; } } if (!isset($_POST['submit_bilde'])) { ?> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="Image1"><br> <input type="file" name="Image2"><br> <input type="file" name="Image3"><br> <input type="file" name="Image4"><br> <input type="file" name="Image5"><br><br> <input type="submit" value="GOOOOOOOO!!!!" name="submit_bilde"> </form> <?}?> and if you look in the code there is a part where i want to echo the uploaded files' path's.. I only se one of those 5 files listet in the "echo"-thing :p Can someone please, please, please help me to echo ALL the 5 images path?? Ive been trying to make a simple uploader script for a friend of mines website im working on, but its just not working and I know im doing everything right! Here is the code: <?php $target_path = "http://adiscountsignco.com/admin/uploads/"; $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); if(move_uploaded_file($_FILES['uploadedfile']['tmp'], $target_path)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } ?> So, I created in the admin directory both a directory name "tmp" and a directory named "uploads" , however its still not working? Its just giving me the "there was an error uploading the file, please try again!" error in the else statement. I just dont get it, did i miss something? Im new at working with $_file, im not a total noob at php but ive never worked with this before and it is really pissing me off! Thanks!!!! Hey Guys, I have a php script that update's franchise information using a mysql table. Note: Ter = Territory, ie. the territory that franchise covers. <?php include('config.php'); if (isset($_GET['Ter']) ) { $ter = (int) $_GET['Ter']; if (isset($_POST['submitted'])) { //Photo Upload //This is the directory where images will be saved $target = "images/"; $target = $target . basename( $_FILES['photo']['name']); //This gets all the other information from the form $photo =($_FILES['photo']['name']); //Pause Photo Upload foreach($_POST AS $key => $value) { $_POST[$key] = mysql_real_escape_string($value); } $sql= "UPDATE `ter` SET `Ter` = '{$_POST['Ter']}' , `BranchName` = '{$_POST['BranchName']}' , `BranchAddress` = '{$_POST['BranchAddress']}' , `BranchTel` = '{$_POST['BranchTel']}' , `BranchEmail` = '{$_POST['BranchEmail']}' , `BranchLink` = '{$_POST['BranchLink']}' , `Theme` = '{$_POST['Theme']}' , `LocalInfo` = '{$_POST['LocalInfo']}' , `BranchInfo` = '{$_POST['BranchInfo']}' , `photo` = '{$_POST['photo']}' WHERE `Ter` = '$ter' "; mysql_query($sql) or die(mysql_error()); //Unpause Photo Upload //Writes the photo to the server move_uploaded_file($_FILES['photo']['tmp_name'], $target); //End of Photo Upload echo (mysql_affected_rows()) ? "Edited Branch.<br />" : "Nothing changed. <br />"; } $row = mysql_fetch_array ( mysql_query("SELECT * FROM `ter` WHERE `Ter` = '$ter' ")); ?> In phpmyadmin I can see my table and it has the correct image name displayed in the photo column. So you would assume its worked. But when I look in the 'images/' location no image has been uploaded. So I think there is an error with the upload part but cant figure out whats wrong. Cheers, S Hi Guys, I got this method to upload an image once, now nothing is uploading at all and I cant seem to figure out why. I set permissions of both the script and image upload directory to www:/data and 777, but its still not working. When I print the return from basename, it show's 0, which means the file is uploaded.. But it not:( Here is my method. function add_product() { if($_SERVER['REQUEST_METHOD'] == "POST") { //get the form data $data['product'] = array( "name" => $this->input->post('name'), "title" => $this->input->post('title'), "description" => $this->input->post('description'), "status" => $this->input->post('live'), "url" => str_replace(" ", '-',$this->input->post('name')), "preview_image" => $this->input->post('preview_image'), "body_image" => $this->input->post('body_image') ); //add the record the the DB $this->load->model('products_model'); $return = $this->products_model->add_product($data); //upload the images $name = $_FILES['preview_image']['name']; $target = '/var/www/www.example.com/content/product_img/'; $upload = $target.basename($name); switch ($_FILES['preview_image']['error']) { case 1: print '<p> The file is bigger than this PHP installation allows</p>'; break; case 2: print '<p> The file is bigger than this form allows</p>'; break; case 3: print '<p> Only part of the file was uploaded</p>'; break; case 4: print '<p> No file was uploaded</p>'; break; } echo img('content/product_image/'.$name); //upload the images $name2 = $_FILES['body_image']['name']; $target2 = '/var/www/www.example.com/content/product_img/'; $upload2 = $target2.basename($name2); switch ($_FILES['preview_image']['error']) { case 1: print '<p> The file is bigger than this PHP installation allows</p>'; break; case 2: print '<p> The file is bigger than this form allows</p>'; break; case 3: print '<p> Only part of the file was uploaded</p>'; break; case 4: print '<p> No file was uploaded</p>'; break; } echo img('content/product_image/'.$name); //redirect to edit view //redirect('admin/edit_product/'.$return); //testing //print_r($data); } else { $data['title'] = 'Add Product :: FSG'; $data['main_content'] = 'admin/add_product'; $data['user'] = $this->facebook_connect->user; $data['user_id'] = $this->facebook_connect->user_id; $this->load->view('includes/template', $data); } } Here is the html for the form. <form action="<?php echo site_url();?>admin/add_product" method="post" enctype="multipart/form-data"> <div class="fieldset"> <h2 class="legend"> Product Information </h2> <ul class="form-list"> <li class="fields"> <div class="name"> <div class="field"> <label for="name" class="required"><em>*</em>Product Name</label> <div class="input-box"> <input type="text" id="name" name="name" value="New Product" title="Product Name" class="input-text required-entry" /> </div> </div> <div class="field title"> <label for="title" class="required"><em>*</em>Product Title</label> <div class="input-box"> <input type="text" id="title" name="title" value="Title Used On Heading" title="Product Title" class="input-text required-entry" /> </div> </div> </div> </li> <li> <label for="email" class="required"><em>*</em>Product Description</label> <div class="input-box"> <textarea id="description" name="description">Write a 3 to 5 Paragraph summary of product</textarea> </div> </li> <li class="control"> <input type="checkbox" name="live" id="live" value="1" title="Live Product" class="checkbox" /><label for="live_product">Publish Product</label> </li> </ul> </div> <div class="fieldset"> <h2 class="legend"> Product Images </h2> <ul class="form-list"> <li> <label for="preview_image" class="required"><em>*</em>Preview Image :: 240 X 166 Pixels</label> <div class="input-box"> <input type="file" name="preview_image"> </div> </li> <li class="fields"> <div class="field"> <label for="body_image" class="required"><em>*</em>Description Image :: 320 X 320 Pixels</label> <div class="input-box"> <input type="file" name="body_image"> </div> </div> </li> </ul> </div> <div class="buttons-set"> <p class="required"> * Required Fields </p> </p><button type="submit" title="Submit" class="button"><span><span>Submit</span></span></button> </div> </form> form Code: [Select] <form action="<?php $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post" ><input type="file" name="photo" value="" size="30" /><input type="submit" name="ssubmit" value="Submit" /></form> Code: [Select] $tmpname = $_FILES['photo']['tmp_name']; $readphoto = fopen($tmpname, 'r'); $photo = fread($readphoto, filesize($tmpname)); $photo = addslashes($photo); fclose($readphoto); $query = "INSERT INTO student (PHOTO) ". "VALUES ('$photo')"; mysql_query($query) or die('Error, query failed.'); echo "Student information submitted."; i keep getting "Error, query failed"... what did i do wrong? I can't seem to get this file system to upload. It's returning an error about directory not writable. I have also verified it's 777 on the server, so I know permissions are right. File Class Code: [Select] <?php /** * Uploader is a file transfer class. it can upload files and images. * It also can resize and crop images. * Works on PHP 5 * @author Alaa Al-Hussein * @link http://www.freelancer-id.com/projects * @version 1.0 * */ class uploader{ /** * Array, The file object as $_FILES['element']. * String, file location. */ public $source; /** * Destination file location as folder. */ public $destDir; /** * Directory for Resized images. */ public $resizeDir; /** * Directory for Cropped images. */ public $cropDir; /** * stores information for uploading file */ private $info = ''; /** * Enabling autoName will generate an auto file name for the uploaded file. */ public $generateAutoName = true; /** * Handles the error when it occurs. */ private $errorMsg = ''; /** * new width for resizing and cropping. */ public $newWidth; /** * new height for resizing and cropping. */ public $newHeight; /** * TOP postion to cropping image. */ public $top = 0; /** * LEFT position for cropping image. */ public $left = 0; /** * JPG quality (0 - 100). used for image resizing or cropping. */ public $quality = 60; public function __construct(){ //nothing } /** * Uploads the file to the server. * @param Array $_FILES[] */ public function upload($source){ if($source != ""){ $this->source = $source; } if(is_array($this->source)){ if($this->fileExists()){ return false; } // Check for auto-name generation. If it's set then generate the name automatically. if ($this->generateAutoName == true) { $this->autoName(); } return $this->copyFile(); } else { return $this->source; } } /** * return the error messages. * @return String messages. */ public function getError(){ return $this->errorMsg; } /** * Get uploading information. */ public function getInfo(){ return $this->info; } /** * Auto Name */ private function autoName() { $num = rand(0, 2000000); $num2 = rand(0, 2000000); $this->source['name'] = $num . $num2 . $this->source['name']; return $this->source; } /** * Get Image Sizes * Returns an array of variables pertaining to properties of the image. * USE THIS ON IMAGES ONLY */ public function getImageSize() { // Get the size information of the provided image. $image_size = getimagesize($this->getTemp()); // Setup the height/width so they can be returned in a readable format $return_array['width'] = $image_size[0]; $return_array['height'] = $image_size[1]; // Return the array of new data. return $return_array; } /** * Copy the uploaded file to destination. */ private function copyFile(){ if(!$this->isWritable()){ $this->errorMsg .= '<div>Error, the directory: ('.$this->destDir.') is not writable. Please fix the permission to be able to upload.</div>'; return false; } if(copy($this->source['tmp_name'],$this->destDir . $this->source['name'])){ // Done. $this->info .= '<div>file was uploaded successfully.</div>'; } else { $this->errorMsg .= '<div>Error, the file was not uploaded correctly because of an internal error. Please try again, if you see this message again, please contact web admin.</div>'; } } /** * Checks if the file was uploaded. * @return boolean */ private function uploaded(){ if($this->source['tmp_name']=="" || $this->source['error'] !=0){ $this->errorMsg .= '<div>Error, file was not uploaded to the server. Please try again.</div>'; return false; } else return true; } /** * Prepares the directory. */ private function preDir(){ if($this->destDir!="" && substr($this->destDir, -1,1) != "/"){ $this->destDir = $this->destDir . '/'; } if($this->resizeDir!="" && substr($this->resizeDir, -1,1) != "/"){ $this->destDir = $this->resizeDir . '/'; } if($this->cropDir!="" && substr($this->cropDir, -1,1) != "/"){ $this->destDir = $this->cropDir . '/'; } } /** * Check if the folder is writable or not. * @return boolean */ private function isWritable(){ $err = false; if(!is_writeable($this->destDir) && $this->destDir!=""){ $this->errorMsg .= '<div>Error, the directory ('.$this->destDir.') is not writeable. File could not be uploaded.</div>'; $err = true; } if(!is_writeable($this->resizeDir) && $this->resizeDir!=""){ $this->errorMsg .= '<div>Error, the directory ('.$this->resizeDir.') is not writeable. File could not be resized.</div>'; $err = true; } if(!is_writeable($this->cropDir) && $this->cropDir!=""){ $this->errorMsg .= '<div>Error, the directory ('.$this->cropDir.') is not writeable. File could not be cropped.</div>'; $err = true; } if($err == true){ return false; } else { return true; } } /** * Checks if the file exists on the server * @return boolean */ private function fileExists(){ $this->preDir(); if(file_exists($this->destDir.$this->source)){ $this->errorMsg .= '<div>Upload error because file already exists.</div>'; return true; } else { return false; } } /** /586742130./8532 Crops image. * @return String fileName or False on error */ public function crop($file='',$width='',$height='',$top='',$left=''){ if($file!=""){ $this->source = $file;} if ($width != '') $this->newWidth = $width; if ($height != '') $this->newHeight = $height; if ($top != '') $this->top = $top; if ($left != '') $this->left = $left; return $this->_resize_crop(true); } /** * Resizes an image. * @return String fileName or False on error */ public function resize($file='',$width='',$height=''){ if($file!=""){ $this->source = $file; } if($width != '') $this->newWidth = $width; if($height != '') $this->newHeight = $height; return $this->_resize_crop(false); } /** * Get the Temp file location for the file. * If the Source was a file location, it returns the same file location. * @return String Temp File Location */ private function getTemp(){ if(is_array($this->source)){ return $this->source['tmp_name']; } else { return $this->source; } } /** * Get the File location. * If the source was a file location, it returns the same file location. * @return String File Location */ private function getFile(){ if(is_array($this->source)){ return $this->source['name']; } else { return $this->source; } } /** * Resize or crop- the image. * @param boolean $crop * @return String fileName False on error */ private function _resize_crop ($crop) { $ext = explode(".",$this->getFile()); $ext = strtolower(end($ext)); list($width, $height) = getimagesize($this->getTemp()); if(!$crop){ $ratio = $width/$height; if ($this->newWidth/$this->newHeight > $ratio) { $this->newWidth = $this->newHeight*$ratio; } else { $this->newHeight = $this->newWidth/$ratio; } } $normal = imagecreatetruecolor($this->newWidth, $this->newHeight); if($ext == "jpg") { $src = imagecreatefromjpeg($this->getTemp()); } else if($ext == "gif") { $src = imagecreatefromgif ($this->getTemp()); } else if($ext == "png") { $src = imagecreatefrompng ($this->getTemp()); } if($crop){ //$pre = 'part_'; //We want to overwrite file, so comment this out. if(imagecopy($normal, $src, 0, 0, $this->top, $this->left, $this->newWidth, $this->newHeight)){ $this->info .= '<div>image was cropped and saved.</div>'; } $dir = $this->cropDir; } else { //$pre = 'thumb_'; //We want to overwrite file, so comment this out. if(imagecopyresampled($normal, $src, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $width, $height)){ $this->info .= '<div>image was resized and saved.</div>'; } $dir = $this->resizeDir; } if($ext == "jpg" || $ext == "jpeg") { imagejpeg($normal, $dir . $pre . $this->getFile(), $this->quality); } else if($ext == "gif") { imagegif ($normal, $dir . $pre . $this->getFile()); } else if($ext == "png") { imagepng ($normal, $dir . $pre . $this->getFile(),0); } imagedestroy($src); return $src; } } /* Examples Section */ /* Let me explain first how to manage an image to be uploaded and then to be cropped or resized. <?php $uploader = new uploader(); // Setting properties then Uploading the image $uploader->source = $_FILES['field_image']; $uploader->destDir = "images/"; $uploader->upload(); // ===================== // Or you may use this too $uploader->destDir = "images/"; $uploader->upload($_FILES['field_image']); ?> Note: upload() returns the file name uploaded. To get error messages, use this code: <?php echo $uploader->getError(); // This function will return all errors occured while uploading the image. But it's not printing it to print it where ever you want. ?> And to get Information messages use this code: <?php echo $uploader->getInfo(); // This function will return all information to let the user print it where ever he wants. ?> After uploading this image, we may resize it. To do that use the following code: <?php $uploader->newWidth = 75; // in Pexels. $uploader->newHeight = 75; $uploader->resizeDir = "images/resized/"; $uploader->resize(); ?> You may also use this syntax: <?php // $uploader->resize($file,$width,$height); // $file could has a value of "" (nothing), in this case we use the last uploader file. // if the $file has a String value (file url) it will resize this new file. $uploader->resizeDir = "images/resized/"; $uploader->resize('',75,75); // Or you may upload and resize in the same line: $uploader->resizeDir = "images/resized/"; $uploader->resize($uploader->upload(),75,75); ?> Crop this image after uploading it: <?php $uploader->cropDir = "images/cropped/"; $uploader->newWidth = 75; $uploader->newHeight = 75; $uploader->top = 20; // Default is ZERO.. This used to set the cropping top location from the original image. $uploader->left = 40; // Default is ZERO.. This used to set the cropping left location from the original image. $uploader->crop(); // You may also use this: // $uploader->crop($file,$width,$height,$top,$left); $uploader->cropDir = "images/cropped/"; $uploader->crop('',75,75,20,40); ?> */ ?> Upload Function Code: [Select] <?php /* END STANDARD FUNCTIONS */ /* General function to deal with image uploads site_wide. */ function upload_image($file, $dir, $table, $fieldname, $id, $exists, &$data) { // Get image information if ($file['tmp_name'] != '' && $file['name'] != '') { if ($exists == 1) { // Delete Associated Image $imageSQL = "SELECT " . $fieldname . " FROM " . $table . " WHERE product_id = '" . $id . "'"; $imageQuery = mysql_query($imageSQL); while($row = mysql_fetch_array($imageQuery, MYSQL_ASSOC)) { if ($row[$fieldname] != '') { $tmpdirectory = '../assets/' . $dir . '/'.$row[$fieldname]; if (file_exists($tmpdirectory)) { unlink($tmpdirectory); } } } } $directory = '../assets/' . $dir . '/'; // Default DIR // Upload $uploader = new uploader; $uploader->destDir = $directory; $uploader->generateAutoName = true; $file_name = $uploader->upload($file); $image_sizes = $uploader->getImageSize(); echo $uploader->getInfo(); } // Check if image was uploaded and if so database name. if ($uploader->source['name'] != '') { $data[$fieldname] = $uploader->source['name']; }else { if ($exists == 1) { $tmpSelect = "SELECT " . $fieldname . " FROM " . $table . " WHERE product_id = '".$id."'"; $tmpQuery = mysql_query($tmpSelect); if ($row = mysql_fetch_array($tmpQuery, MYSQL_ASSOC)) { $data[$fieldname] = $row[$fieldname]; }else { $data[$fieldname] = NULL; } }else { $data[$fieldname] = NULL; } } } ?> Code to call function Code: [Select] <?php // Upload all images $picture_1 = $_FILES['picture_one']; if ($picture_1['tmp_name'] != '' && $picture_1['name'] != '') { $functions->upload_image($picture_1, 'product_pictures', 'products', 'picture_1', $product_id, $exists, &$data); } ?> At this point I have done all of the debugging I can and it's not working out. Any advice is appreciated. Hi Guys, I found this upload script a while ago and I'm sure the last time I used it, it worked perfectly but for some reason '$path1' keeps returning as blank. I'm not very good with file uploads, can anyone help me out please? Code: [Select] if ($_POST['customBackground']) { $path1= '/upload/' . date(U). $HTTP_POST_FILES['customBackground']['name'][0]; if(empty($path1)) { $message = '<p class="red size10font">Background field cannot be blank!</p>';} else { //copy file to where you want to store file copy($HTTP_POST_FILES['customBackground']['tmp_name'][0], $path1); } } The field it is being populated from is <input class="fullwidth biggun" name="customBackground" type="file" id="customBackground" size="70" value=""> Thank you in advance. Hey.. this is something I found online, and something mine combined, and it works perfectly... When I upload pic, it uploads it where I want to, and it makes thumbnail where I want to, BUT it resize the original and the thumbnail, so I end up with two same sized images, and I want one thumbnail, and you click it, it shows a bigger ( original ) picture.. Can anyone see an error in this code?? Code: [Select] <?php function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } define ("MAX_SIZE","5000"); $errors=0; if(isset($_POST['submit'])) { $image =$_FILES["file"]["name"]; $uploadedfile = $_FILES['file']['tmp_name']; if ($image) { $filename = stripslashes($_FILES['file']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { echo ' Unknown Image extension '; $errors=1; } else { $size=filesize($_FILES['file']['tmp_name']); if ($size > MAX_SIZE*1024) { echo "You have exceeded the size limit"; $errors=1; } if($extension=="jpg" || $extension=="jpeg" ) { $uploadedfile = $_FILES['file']['tmp_name']; $src = imagecreatefromjpeg($uploadedfile); } else if($extension=="png") { $uploadedfile = $_FILES['file']['tmp_name']; $src = imagecreatefrompng($uploadedfile); } else { $src = imagecreatefromgif($uploadedfile); } list($width,$height)=getimagesize($uploadedfile); $newwidth=200; $newheight=($height/$width)*$newwidth; $tmp=imagecreatetruecolor($newwidth,$newheight); $newwidth1=200; $newheight1=($height/$width)*$newwidth1; $tmp1=imagecreatetruecolor($newwidth1,$newheight1); imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight, $width,$height); imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1, $width,$height); $thumbnail = "thumbnail". $_FILES['file']['name']; $filename = "upload/". $_FILES['file']['name']; $filename1 = "thumbnail/".$thumbnail; imagejpeg($tmp,$filename,100); imagejpeg($tmp1,$filename1,100); imagedestroy($src); imagedestroy($tmp); imagedestroy($tmp1); } } } //If no errors registred, print the success message if(!$errors) { header("Location: main.php"); } ?> Hi guys I am using the code below to upload a series of images to a site, however the records are not being added to the database nor the images being uploaded, but it is doing the redirect at the bottom of the script. Any ideas what is going wrong <?php include('../includes/connect_inc.php'); include("config.inc.php"); set_time_limit(1200); // initialization $result_final = ""; $counter = 0; // List of our known photo types $known_photo_types = array( 'image/pjpeg' => 'jpg', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/bmp' => 'bmp', 'image/x-png' => 'png' ); // GD Function List $gd_function_suffix = array( 'image/pjpeg' => 'JPEG', 'image/jpeg' => 'JPEG', 'image/gif' => 'GIF', 'image/bmp' => 'WBMP', 'image/x-png' => 'PNG' ); // Fetch the photo array sent by preupload.php $photos_uploaded = $_FILES['photo_filename']; // Fetch the photo caption array $photo_caption = $_POST['photo_caption']; while( $counter <= count($photos_uploaded) ) { if($photos_uploaded['size'][$counter] > 0) { if(!array_key_exists($photos_uploaded['type'][$counter], $known_photo_types)) { $result_final .= "File ".($counter+1)." is not a photo<br />"; } else { mysql_query( "INSERT INTO gallery_photos(`photo_filename`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" )or die(mysql_error()); $new_id = mysql_insert_id(); $filetype = $photos_uploaded['type'][$counter]; $extention = $known_photo_types[$filetype]; $filename = $new_id.".".$extention; mysql_query( "UPDATE gallery_photos SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" ); // Store the orignal file copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$filename); // Let's get the Thumbnail size $size = GetImageSize( $images_dir."/".$filename ); if($size[0] > $size[1]) { $thumbnail_width = 100; $thumbnail_height = (int)(100 * $size[1] / $size[0]); } else { $thumbnail_width = (int)(100 * $size[0] / $size[1]); $thumbnail_height = 100; } // Build Thumbnail with GD 1.x.x, you can use the other described methods too $function_suffix = $gd_function_suffix[$filetype]; $function_to_read = "ImageCreateFrom".$function_suffix; $function_to_write = "Image".$function_suffix; // Read the source file $source_handle = $function_to_read ( $images_dir."/".$filename ); if($source_handle) { // Let's create an blank image for the thumbnail $destination_handle = ImageCreate ( $thumbnail_width, $thumbnail_height ); // Now we resize it ImageCopyResized( $destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $size[0], $size[1] ); } // Let's save the thumbnail $function_to_write( $destination_handle, $images_dir."/tb_".$filename ); ImageDestroy($destination_handle ); // $result_final .= "<img src='".$images_dir. "/tb_".$filename."' /> File ".($counter+1)." Added<br />"; } } $counter++; } // Print Result header("Location: add-photos.php"); ?> I have a form that includes uploading a headshot. This is the form handling f ($_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']; $dob = $_POST['dateOfBirth']; if(!empty($_FILES['fileToUpload'])){ $errors= array(); $file_name = $_FILES['personHeadshot']['name']; $file_size =$_FILES['personHeadshot']['size']; $file_tmp =$_FILES['personHeadshot']['tmp_name']; $file_type=$_FILES['personHeadshot']['type']; $file_ext=strtolower(end(explode('.',$_FILES['personHeadshot']['name']))); $newFileName = $fn."-".$ln.".".$file_ext; $extensions= array("jpeg","jpg","png"); if(in_array($file_ext,$extensions)=== false){ $errors[]="extension not allowed, please choose a JPEG or PNG file."; } if($file_size > 2097152){ $errors[]='File size must be smaller than 2 MB'; } if(empty($errors)==true){ move_uploaded_file($file_tmp,"img/people/".$newFileName); echo "Success"; }else{ print_r($errors); } $personHeadshot = $newFileName; } $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, image, dob) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) "); $stmt -> bind_param('ssiiissssssiss', $fn, $ln, $crole, $playerType, $team, $ad1, $ad2, $city, $post, $tel, $email, $OFA, $personHeadshot, $dob); $stmt -> execute(); header("location: admin-people-list.php"); } I also have this file <?php $target_dir = "img/people/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["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["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?> This was working locally but now i have uploaded it i cannot get it to work. All of the person data gets put into the DB asside from the file name I appreciate you may need more info to help me which i will provide on request Hey guys!! i'm after a bit of help with a script i am using for simple image upload to server. At the moment the script works fine and will allow upload of JPG files, i want to extend on this to allow GIF and PNG files to be uploaded aswell. This is the script i am using... <?php //?heck that we have a file if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 600Kb $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 600000)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/uploads/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { echo "Upload Complete! You can use the following link in the IMS:" .$newname; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } } else { echo "Error: Only .jpg images under 600Kb are accepted for upload"; } } else { echo "Error: No file uploaded"; } // $sessionid=session_id() //$newname=$_SESSION['session_name'] header( 'Location: success.php?newname1='.$filename ) ; ?> Any help would be appriciated!! ta!! jonny I need to set my script here to change the CHMOD settings to 644. The images that are uploaded into the Yahoo server are not able to be accessed. I believe this is the CHMOD, however I have never worked with CHMOD. Please help, or if you notice an error in my coding please let me know. Code: [Select] <?php $Name = $_POST['Name']; $Pic = $_FILES["file"] ["name"]; if ((($_FILES["file"] ["type"] == "image/gif") || ($_FILES["file"] ["type"] == "image/jpeg") || ($_FILES["file"] ["type"] == "image/pjpeg")) && ($_FILES["file"] ["size"] < 100000)) { if ($_FILES["file"] ["error"] > 0) { echo "Return Code: " . $_FILES["file"] ["error"] . "<br />"; } else { if (file_exists("../Graphics/" . $_FILES["file"] ["name"])) { include("../Admin/photos.php"); echo $_FILES["file"] ["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"] ["tmp_name"], "../Graphics/" . $_FILES["file"] ["name"]); chmod("$pic",0644); } } } else { echo "<font size='5' face='Arial'><b>Invalid file</b></font>"; } $Category = $_POST['Category']; include('database.php'); mysql_select_db("bluemoonmastiff", $con); $good_data = $_POST; foreach($good_data as $field => $value) { if($field != "submitted") { $field_array[] = $field; $clean = strip_tags(trim($value)); $escaped = mysqli_real_escape_string($cxn,$clean); $value_array[] = $escaped; } } $fields = implode(",",$field_array); $values = implode('","',$value_array); $sql = "INSERT INTO gallery SET Name='$Name',PicAddress='Graphics/$Pic',Category='$Category'"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "<font size='5' face='Arial'><b>Picture Upload Complete</b></font>"; ?> Here's the upload script: <?php //This is the directory where images will be saved $target = "images/"; $target = $target . basename( $_FILES['photo']['name']); //This gets all the other information from the form $name=$_POST['name']; $email=$_POST['email']; $phone=$_POST['phone']; $pic=($_FILES['photo']['name']); // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()) ; mysql_select_db("Database_Name") or die(mysql_error()) ; //Writes the information to the database mysql_query("INSERT INTO `employees` VALUES ('$name', '$email', '$phone', '$pic')") ; //Writes the photo to the server if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { //Tells you if its all ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { //Gives and error if its not echo "Sorry, there was a problem uploading your file."; } ?> Wouldn't I need a username pw for it access images, where it's supposed to upload it? Or does it simply upload it to a file called images in the same folder as the upload.php is in? Thank you! Hi All Not so much help as here is a handy class for uploading images Please feel free to find security bugs and let me know. Also feel free to use it if you want. http://onlyican.com/test_samples/bl_upload_img.phps To use the class, simply use the following require_once('bl_upload_img.php'); $objUploadImg = new UploadImg(); //Set values here if you wish such as $objUploadImg->setFormField('myFormField'); // The Name from <input type="file" name="myFormField" /> $objUploadImg->setSaveDirMain($_SERVER['DOCUMENT_ROOT'].'/MyImageFolder'; //Make sure to set the permissions //You can change most settings, just look at the function setDetaultValues() to get the function name //Now upload the image if($objUploadImg->uploadImage()){ $strFileName = $objUploadImg->getFileNameMain(); }else{ echo 'Error uploading Image<br />'.$objUploadImg->getErrorMessage(); } Hello, I'm planning on making a website where people are able to upload files and directly link to them. Ideally, I want to keep the same file names that the people use when they upload the file. I was planning on keeping the directory that stored all of the files outside of the www directory and disable execute permissions. However, how would I avoid file overwriting with the same file name? |