PHP - Uploading Images Help
Ok I have finally got rid of my syntax errors with this upload script. Now im getting the error uploading your image.
My folders are called project_files and project_thumbs. This is my script <?php $results = ""; error_reporting(E_ALL); ini_set("display_errors", 1); //Auto Thumbnail Function function create_thumbnail($source,$destination, $thumb_width) { $size = getimagesize($source); $width = $size[0]; $height = $size[1]; $x = 0; $y = 0; if($width> $height) { $x = ceil(($width - $height) / 2 ); $width = $height; } elseif($height> $width) { $y = ceil(($height - $width) / 2); $height = $width; } $new_image = imagecreatetruecolor($thumb_width,$thumb_width) or die('Cannot initialize new GD image stream'); $extension = get_image_extension($source); if($extension=='jpg' || $extension=='jpeg') $image = imagecreatefromjpeg($source); if($extension=='gif') $image = imagecreatefromgif($source); if($extension=='png') $image = imagecreatefrompng($source); imagecopyresampled($new_image,$image,0,0,$x,$y,$thumb_width, $thumb_width,$width,$height); if($extension=='jpg' || $extension=='jpeg') imagejpeg($new_image,$destination); if($extension=='gif') imagegif($new_image,$destination); if($extension=='png') imagepng($new_image,$destination); } //Get Extension Function function get_image_extension($name) { $name = strtolower($name); $i = strrpos($name,"."); if (!$i) { return ""; } $l = strlen($name) - $i; $extension = substr($name,$i+1,$l); return $extension; } //Random Name Function function random_name($length) { $characters = "abcdefghijklmnopqrstuvwxyz01234567890"; $name = ""; for ($i = 0; $i < $length; $i++) { $name .= $characters[mt_rand(0, strlen($characters) - 1)]; } return "image-".$name; } $images_location = "/project_files/"; $thumbs_location = "/project_thumbs/"; $thumb_width = "100"; $maximum_size = "5000000"; //Check And Save Image if($_POST) { if($_FILES['image']['name'] == ""){ $results = "Please select the image you would like to upload by clicking browse"; } else{ $size=filesize($_FILES['image']['tmp_name']); $filename = stripslashes($_FILES['image']['name']); $extension = get_image_extension($filename); if($size > $maximum_size) { $results = "Your file size exceeds the maximum file size!"; } else if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $results = "Only the following extensions are allowed. 'jpg', 'jpeg', 'png', 'gif'."; } else { $image_random_name=random_name(15).".".$extension; $copy = @copy($_FILES['image']['tmp_name'], $images_location.$image_random_name); if (!$copy) { $results = "Error while uploadin your image! Please try again!"; } else{ create_thumbnail($images_location.$image_random_name,$thumbs_location.$image_random_name, $thumb_width); $results = "Your image has been uploaded!"; } } } } ?> and the form Code: [Select] <html> <head> <title>test</title> </head> <body> <?php echo $results; ?> <form action="#" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="5000000" /> <input type="file" name="image" /> <input type="submit" value="Upload Image" /> </form> </body> </html> Similar TutorialsHi, I have this upload script that uploads a file and writes path to DB: Code: [Select] <?php $uploadDir = '../uploads/'; if(isset($_POST['upload'])) { foreach ($_FILES as $file) { $fileName = $file['name']; $tmpName = $file['tmp_name']; $fileSize = $file['size']; $fileType = $file['type']; if($fileName==""){ $filePath = '../img/none.jpg'; } else{ $filePath = $uploadDir . $fileName; } if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); } $fileinsert[]=$filePath; } ?> this works fine for a single image, but I eed to upload 2 images with a single submission....any ideas how to do this? Thanks Hi guys I have got this code here, giving quite a few errors and was wondering if anyone could help me sort it out, the script (should) run straight away just have to edit the database connect, I've tried manually creating the table and taking out the create table but when I try and upload an image I get these errors: Warning: move_uploaded_file(latest.img) [function.move-uploaded-file]: failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/php/image.php on line 23 Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/Applications/XAMPP/xamppfiles/temp/php2lgspw' to 'latest.img' in /Applications/XAMPP/xamppfiles/htdocs/php/image.php on line 23 Warning: fopen(latest.img) [function.fopen]: failed to open stream: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/php/image.php on line 24 Warning: filesize() [function.filesize]: stat failed for latest.img in /Applications/XAMPP/xamppfiles/htdocs/php/image.php on line 25 Warning: fread() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/php/image.php on line 25 here is the code: Code: [Select] <?php // Connect to database $errmsg = ""; if (! @mysql_connect("localhost","root","")) { $errmsg = "Cannot connect to database"; } @mysql_select_db("test"); // First run ONLY - need to create table by uncommenting this // Or with silent @ we can let it fail every subsequent time ;-) $q = < < <CREATE create table pix ( pid int primary key not null auto_increment, title text, imgdata longblob) CREATE; @mysql_query($q); // Insert any new image into database if ($_REQUEST[completed] == 1) { // Need to add - check for large upload. Otherwise the code // will just duplicate old file ;-) // ALSO - note that latest.img must be public write and in a // live appliaction should be in another (safe!) directory. move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img"); $instr = fopen("latest.img","rb"); $image = addslashes(fread($instr,filesize("latest.img"))); if (strlen($image) < 149000) { mysql_query ("insert into pix (title, imgdata) values (\"". $_REQUEST[whatsit]. "\", \"". $image. "\")"); } else { $errmsg = "Too large!"; } } // Find out about latest image $gotten = @mysql_query("select * from pix order by pid desc limit 1"); if ($row = @mysql_fetch_assoc($gotten)) { $title = htmlspecialchars($row[title]); $bytes = $row[imgdata]; } else { $errmsg = "There is no image in the database yet"; $title = "no database image available"; // Put up a picture of our training centre $instr = fopen("../wellimg/ctco.jpg","rb"); $bytes = fread($instr,filesize("../wellimg/ctco.jpg")); } // If this is the image request, send out the image if ($_REQUEST[gim] == 1) { header("Content-type: image/jpeg"); print $bytes; exit (); } ?> <html><head> <title>Upload an image to a database</title> <body bgcolor=white><h2>Here's the latest picture</h2> <font color=red><?= $errmsg ?></font> <center><img src=?gim=1 width=144><br> <b><?= $title ?></center> <hr> <h2>Please upload a new picture and title</h2> <form enctype=multipart/form-data method=post> <input type=hidden name=MAX_FILE_SIZE value=150000> <input type=hidden name=completed value=1> Please choose an image to upload: <input type=file name=imagefile><br> Please enter the title of that pictu <input name=whatsit><br> then: <input type=submit></form><br> <hr> By Graham Ellis - graham@wellho.net </body> </html> Hey, I was wondering if there is a way to use PHP to resize images when they are a above a size limit? Im not referring to file size here, but rather the width by height ratio. As currently i upload images and echo them with: Code: [Select] style="width:250px;height:200px;" But this means my server is loading large images when i would rather resize them down upon upload to reduce loading times... Is this possible in php ? I want users to be allowed to upload images to a table in a database but I cannot seem to find a suitable way to implementing using the code I already have, here is the code below; Code: [Select] <?php error_reporting(E_ALL ^ E_NOTICE); ini_set("display_errors", 1); require_once ('./includes/config.inc.php'); require_once (MYSQL); $add_cat_errors = array(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (!empty($_POST['product'])) { $prod = mysqli_real_escape_string($dbc, strip_tags($_POST['product'])); } else { $add_cat_errors['product'] = 'Please enter a Product Name!'; } if (filter_var($_POST['prod_descr'])) { $prod_descr = mysqli_real_escape_string($dbc, strip_tags($_POST['prod_descr'])); } else { $add_cat_errors['prod_descr'] = 'Please enter a Product Description!'; } // Check for a category: if (filter_var($_POST['cat'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $catID = $_POST['cat']; } else { // No category selected. $add_page_errors['cat'] = 'Please select a category!'; } if (filter_var($_POST['price'])) { $price = mysqli_real_escape_string($dbc, strip_tags($_POST['price'])); } else { $add_cat_errors['price'] = 'Please enter a Product Description!'; } if (filter_var($_POST['stock'])) { $stock = mysqli_real_escape_string($dbc, strip_tags($_POST['stock'])); } else { $add_cat_errors['stock'] = 'Please enter a Product Description!'; } if (empty($add_cat_errors)) { $query = "INSERT INTO product (product, prod_descr, catID, price, image, stock) VALUES ('$prod', '$prod_descr', '$catID', '$price', '$image', '$stock')"; $r = mysqli_query ($dbc, $query); if (mysqli_affected_rows($dbc) == 1) { echo '<p>Record Successfully Added!!!!!</p>'; $_POST = array(); } else { trigger_error('OH NOOOOO!!!!'); } } } require_once ('./includes/form_functions.inc.php'); ?> <form action="add_product.php" method="post"> Product Name: <?php create_form_input('product', 'text', $add_cat_errors);?> Product Description: <?php create_form_input ('prod_descr', 'text', $add_cat_errors);?> Category: <select name="cat"<?php if (array_key_exists('cat', $add_cat_errors))?>> <option>Select a Category</option> <?php $q = "SELECT catID, cat FROM category ORDER BY cat ASC"; $r = mysqli_query($dbc, $q); while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) { echo "<option value=\"$row[0]\""; if (isset($_POST['cat']) && ($_POST['cat'] == $row[0])) echo 'selected="selected"'; echo ">$row[1]</option>\n"; } ?> Price: <?php create_form_input('price', 'text', $add_cat_errors);?> Upload an Image: <?php if(array_key_exists('image', $add_cat_errors)) { echo '<input type="file" name="image" />'; } ?> Stock: <?php create_form_input('stock', 'text', $add_cat_errors);?> <input type="submit" name="submit_button" value="ADD RECORD" /> </form> Everything else writes perfectly but I have been trying ways to create a file upload and write successfully to the database. The 'image' field has a data type of 'varchar'. I apologise immensely for the long winded explanation but if anyone could help me please that would be much appreciated. Hi, i want to make an image gallery, this is the first step. uploading files. below is the code I am using , but don't i have to include info about the server? i dont know what to include since it is the server I am working with and not a database, any help greatly appreciated. thanks Code: [Select] <?php // Where the file is going to be placed $target_path = "uploads/"; /* Add the original filename to our target path. Result is "uploads/filename.extension" */ $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } ?> <!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> </head> <body> </body> </html> I developped a cms system to upload images with php to a mysql database and a upload folder on the server. Firefox version 5.0.1 for MAC and earlier have no problems with uploading through the script. But after that version it is impossible to upload images bigger then 250kb. The page where the customer chooses his image for upload stalls and the form is not sent to the actual upload script, which should validate and process the image. This problem only occurs in Firefox, all other browsers work just fine! I tried to run the same script with Firefox on a PC and everything works fine. So it is a Mac related problem. You can try for yourself to see what happens in the following basic script (if you don't get a succes message it means that you are still hanging on the image_upload page and nothing has happened) : http://siteways.net/test_upload/image_upload.php Hi I am creating an e commerce website and I have been using a php dummies book to help me as I am a beginner. I am creating an e commerce website and I have created a page which consists of radio buttons where a user will be able to choose what type of shoe they would like to view. Once they have chosen the radio button and then clicked onto the show me button the type of shoe shown should be the same as the type they have chosen but no shoes are showing on the webpage. I am unsure if i have not entered the format correct in the image section of the database. Here is the code which i have created so far: /* Select shoes the type specified*/ $query = "SELECT * FROM products WHERE prod_type=\"{$_POST['interest']}\""; $result = mysqli_query($cxn,$query) or die ("Couldn't execute query."); /* Display results in a table */ echo "<table cellspacing='10' border='1' cellpadding='87' width='100%'>"; echo "<tr><td colspan='5' style='text-align: right'> Click on any picture to see a larger version. <hr /></td></tr>\n"; while($row = mysqli_fetch_assoc($result)) { $f_price = number_format($row['product_price'],2); /* display row for each shoe */ echo "<tr>\n"; echo " <td>{$row['product_id']}</td>\n"; echo " <td style='font-weight: bold; font-size: 1.1em'>{$row['product_name']}</td>\n"; echo " <td>{$row['product_description']}</td>\n"; echo "<tr><td colspan='5'><hr /></td></tr>\n"; } echo "</table>\n"; echo "<div style='text-align: center'> <a href='shoes_list.php'> <h3>See more shoes</h3></a></div>"; ?> in my database the product_image column the field just contains the file name e.g: heels.jpg. please can anyone help me to get the images displayed.. thank you Hi I am trying to upload images and add the details to a database, the problem I have is the photos are not being uploaded or added to the database but the page is redirecting to the next page in the process I have. The images are selected using this code Code: [Select] <?php include("config.inc.php"); // initialization $photo_upload_fields = ""; $counter = 1; // default number of fields $number_of_fields = 10; // If you want more fields, then the call to this page should be like, // preupload.php?number_of_fields=20 //if( $_GET['number_of_fields'] ) //$number_of_fields = (int)($_GET['number_of_fields']); // Lets build the Photo Uploading fields while( $counter <= $number_of_fields ) { $photo_upload_fields .=<<<__HTML_END <tr> <td> Photo {$counter}: <input name=' photo_filename[]' type='file' /> </td> </tr> <tr> <td> Title: <input name='photo_title[]' type="text" size="30"> </td> </tr> __HTML_END; $counter++; } ?> html code for page look and feel <form enctype='multipart/form-data' action='upload.php' method='post' name='upload_form'> <table width='90%' border='0' align='center' style='width: 90%;'> <!-Insert the photo fields here --> <?php echo $photo_upload_fields;?> <tr> <td> <input name="lot_id" type="text" value="<?php echo $lot_id; ?>" /><input type='submit' name='submit' value='Add Photos' /> </td> </tr> </table> </form> and then uploaded with this Code: [Select] <?php include("config.inc.php"); // 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 and title array $photo_title = $_POST['photo_title']; 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`,`category_id`, `photo_title`) VALUES('0','".addslashes($_POST['lot_id'])."', '".addslashes($photo_title[$counter])."')" ); $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++; } // redirect to Add Vehicle Damage header("Location: vehicle-damage.php"); ?> It is however redirecting to the header indicated at the bottom of the page. I can't see why the photos are not uploading or being added to the database. I have a php website with two parts the client part and an admin part in the client part or the viewers end , i need to show the details of products with description and an image (in the front page). The details are entered though the admin part. My problem is the image uploaded goes to the folder in the admin folder but in the home page the images are taken from the images folder suitated in outside the admin folder . How can i upload images or photos to the folder outside the admin though the admin pages. Pasting my code here Code: [Select] $target = "pics/"; [color=red]//this is created in the admin folder, i need to change here that is keep the folder outside the admin folde[/color]r $target = $target . basename( $_FILES['photo']['name']); $pic=($_FILES['photo']['name']); $image=$pic; $box_num =$_POST['box_num']; $query11 = "update photo_table set page_head='$page_head',image='$image' where id='$box_num'"; $result11 = mysql_query($query11); if(move_uploaded_file($_FILES['photo']['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."; } } } Hi guys, I have a website that I created and it has the ability to upload images to a directory that is located in the same web server, but there are so many images now and it is taking too much space. What I am trying to do now is for the script to upload the images to a different server but don't want to run FTP on that second server if I don't need to. Does anyone know how I can do that? Thank you guys in advanced, Hello: I would like to know how I can add the option to upload JPGs and/or PDFs to the form I have. I believe I will need to allow 3 uploads once the whole form is done, but I'm trying to keep it small as I learn this. Currently, the form saves the data to the database, and emails the results to a contact. This is fine - just what I need to do most of the time. However, what I'm interesting in doing for this form is to allow the end user to upload/attached JPGs and/or PDFs and save then to the database (and I believe I will need to save the files in a folder on the server, I have one called "EmailedImages"), and then email the results to the contact, including links that will allow the contact to click and download the attached JPGs and/or PDFs. I haven't done this before, so can someone point me in the direction of how to do this, or should an example with the code I use: Code: [Select] <?php $error = NULL; $myDate = NULL; $FullName = NULL; $Email = NULL; if(isset($_POST['submit'])) { $myDate = $_POST['myDate']; $FullName = $_POST['FullName']; $Email = $_POST['Email']; if(empty($FullName)) { $error .= '-- Enter your Full Name. <br />'; } if(empty($Email)) { $error .= '-- Enter your Email. <br />'; } if($error == NULL) { $sql = sprintf("INSERT INTO myContactData(myDate,FullName,Email) VALUES ('%s','%s','%s')", mysql_real_escape_string($myDate), mysql_real_escape_string($FullName), mysql_real_escape_string($Email); if(mysql_query($sql)) { $error .= 'Thank you for contacting us.'; mail( "email@mywebsite.com", "Contact Request", "Date Sent: $myDate\n Full Name: $FullName\n Email: $Email\n", "From: $Email" ); } else { $error .= 'There was an error in our Database, please Try again!'; } } } echo '<span class="textError">' . $error . '</span>'; ?> <form name="myform" action="" method="post"> <input type="hidden" name="myDate" size="45" maxlength="50" value="<?php echo date("F j, Y"); ?>" /> Full Name: <input type="text" name="FullName" size="45" maxlength="50" value="<?php echo $FullName; ?>" /> Email: <input type="text" name="Email" size="45" maxlength="50" value="<?php echo $Email; ?>" /> <input type="submit" name="submit" value="Submit" /> </form> Any help would be greatly appreciated! I am trying to add a second image upload to a form I have, but I can't figure out how to get the insert statement and upload statement working properly. The first file uploads and inserts to the database properly, but can anyone tell me how to add a second image to the mix? Here is what I currently have: Code: [Select] //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 "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"], "upload/" . $_FILES["file"]["name"]); //echo "Stored in: " . "http://www.webdesignsbyliz.com/wdbl_wordpress/wp-content/themes/twentyten_2/upload/" . $_FILES["file"]["name"]; $image = $_FILES["file"]["name"]; $query = "INSERT INTO gallery VALUES ('', '$cut', '$color', '$carats', '$clarity', '$size', '$metal', '$other', '$total', '$certificate', '$value', '$image', '$name', '$desc', '$item_no', '$type', '$image2')"; $query_res = mysql_query($query) or die(mysql_error()); } } I thought I could simply add a second move_uploaded_file line and replace "file" with "file2" (the name of my second file upload field from the form), but it's not working. Can anyone tell me the right way to do this, please? Thanks in advance! I'm not experienced with file uploads yet :-( Hi All, This has been driving me crazy for a while now. I was on an older version of PHP and everything was working fine but a few weeks ago my hosting upgraded the PHP to version 5 (I think) and I have started to get problems. I have a form that is completed and also 5 images can be added and then submitted which should save it to the database. But the images are not being saved anymore. I have attached the code that I am using and it did work before. On another note I was having a problems with the other fields on the forms where characters such as ! or , etc would cause problems. I got over this by using '.mysql_real_escape_string'. Should I be doing something like this for the images that I want to upload? I hope I am making sense. Thanks Dear all, I have a problem that I need to be helped with using one form and storing the images in database. I would like to upload multiple images with same title from "title" field. Can somebody help me with this? <?php $db_host = 'localhost'; // don't forget to change $db_user = 'mysql-user'; $db_pwd = 'mysql-password'; $database = 'test'; $table = 'ae_gallery'; // use the same name as SQL table $password = '123'; // simple upload restriction, // to disallow uploading to everyone if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($database)) die("Can't select database"); // This function makes usage of // $_GET, $_POST, etc... variables // completly safe in SQL queries function sql_safe($s) { if (get_magic_quotes_gpc()) $s = stripslashes($s); return mysql_real_escape_string($s); } // If user pressed submit in one of the forms if ($_SERVER['REQUEST_METHOD'] == 'POST') { // cleaning title field $title = trim(sql_safe($_POST['title'])); if ($title == '') // if title is not set $title = '(empty title)';// use (empty title) string if ($_POST['password'] != $password) // cheking passwors $msg = 'Error: wrong upload password'; else { if (isset($_FILES['photo'])) { @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']); // Get image type. // We use @ to omit errors if ($imtype == 3) // cheking image type $ext="png"; // to use it later in HTTP headers elseif ($imtype == 2) $ext="jpeg"; elseif ($imtype == 1) $ext="gif"; else $msg = 'Error: unknown file format'; if (!isset($msg)) // If there was no error { $data = file_get_contents($_FILES['photo']['tmp_name']); $data = mysql_real_escape_string($data); // Preparing data to be used in MySQL query mysql_query("INSERT INTO {$table} SET ext='$ext', title='$title', data='$data'"); $msg = 'Success: image uploaded'; } } elseif (isset($_GET['title'])) // isset(..title) needed $msg = 'Error: file not loaded';// to make sure we've using // upload form, not form // for deletion if (isset($_POST['del'])) // If used selected some photo to delete { // in 'uploaded images form'; $id = intval($_POST['del']); mysql_query("DELETE FROM {$table} WHERE id=$id"); $msg = 'Photo deleted'; } } } elseif (isset($_GET['show'])) { $id = intval($_GET['show']); $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(image_time), data FROM {$table} WHERE id=$id LIMIT 1"); if (mysql_num_rows($result) == 0) die('no image'); list($ext, $image_time, $data) = mysql_fetch_row($result); $send_304 = false; if (php_sapi_name() == 'apache') { // if our web server is apache // we get check HTTP // If-Modified-Since header // and do not send image // if there is a cached version $ar = apache_request_headers(); if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists ($ar['If-Modified-Since'] != '') && // not empty (strtotime($ar['If-Modified-Since']) >= $image_time)) // and grater than $send_304 = true; // image_time } if ($send_304) { // Sending 304 response to browser // "Browser, your cached version of image is OK // we're not sending anything new to you" header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304); exit(); // bye-bye } // outputing Last-Modified header header('Last-Modified: '.gmdate('D, d M Y H:i:s', $image_time).' GMT', true, 200); // Set expiration time +1 year // We do not have any photo re-uploading // so, browser may cache this photo for quite a long time header('Expires: '.gmdate('D, d M Y H:i:s', $image_time + 86400*365).' GMT', true, 200); // outputing HTTP headers header('Content-Length: '.strlen($data)); header("Content-type: image/{$ext}"); // outputing image echo $data; exit(); } ?> <html><head> <title>MySQL Blob Image Gallery Example</title> </head> <body> <?php if (isset($msg)) // this is special section for // outputing message { ?> <p style="font-weight: bold;"><?=$msg?> <br> <a href="<?=$PHP_SELF?>">reload page</a> <!-- I've added reloading link, because refreshing POST queries is not good idea --> </p> <?php } ?> <h1>Blob image gallery</h1> <h2>Uploaded images:</h2> <form action="<?=$PHP_SELF?>" method="post"> <!-- This form is used for image deletion --> <?php $result = mysql_query("SELECT id, image_time, title FROM {$table} ORDER BY id DESC"); if (mysql_num_rows($result) == 0) // table is empty echo '<ul><li>No images loaded</li></ul>'; else { echo '<ul>'; while(list($id, $image_time, $title) = mysql_fetch_row($result)) { // outputing list echo "<li><input type='radio' name='del' value='{$id}'>"; echo "<a href='{$PHP_SELF}?show={$id}'>{$title}</a> – "; echo "<small>{$image_time}</small></li>"; } echo '</ul>'; echo '<label for="password">Password:</label><br>'; echo '<input type="password" name="password" id="password"><br><br>'; echo '<input type="submit" value="Delete selected">'; } ?> </form> <h2>Upload new image:</h2> <form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data"> <label for="title">Title:</label><br> <input type="text" name="title" id="title" size="64"><br><br> <label for="photo">Photo:</label><br> <input type="file" name="photo" id="photo"><br><br> <label for="password">Password:</label><br> <input type="password" name="password" id="password"><br><br> <input type="submit" value="upload"> </form> </body> </html> Hi Im working on a market place style website. the framework im using is called elgg. it uses an algoritm to find the right approximate width and height of an image thats being uploaded. but on my site, all heights and widths must be the same. this is difficult because some pictures have much greater width than height and some have much greater height. so whats the best algoritm to use to make an accurate thumbnail of all images uploaded? Thanks I am trying to upload files to a user profile system. here is the profile page Code: [Select] <?php include('core/init.inc.php'); if (isset($_POST['email'], $_POST['location'], $_POST['about'])) { $errors = array(); if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) { $errors[] = "The email address you entered is not valid"; } if(preg_match('#^[a-z0-9 ]+$#i',$_POST['location'])===0) { $errors[] = 'Your location must only contain A-Z 0-9 and spaces.'; } if (empty($_FILES['avatar']['tmp_name']) === false) { $file_ext = end(explode('.', $_FILES['avatar']['name'])); if(in_array(strtolower($file_ext), array('jpg', 'jpeg', 'gif', 'png')) === false) { $errors[] = 'Your avatar must be an image.'; } } if(empty($errors)) { print_r($_FILES); set_profile_info($_POST['email'],$_POST['location'],$_POST['about'], (empty($_FILES['avatar']['tmp_name'])) ? false : $_FILES['avatar']['tmp_name']); } $userinfo = array( 'email' => htmlentities($_POST['email']), 'location' => htmlentities($_POST['location']), 'about' => htmlentities($_POST['about']) ); } else { $userinfo = fetch_user_info($_SESSION['uid']); } ?> <!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>Edit your Profile</title> </head> <body> <div> <?php if(isset($errors) == false) { echo 'Click update to edit your profile.'; } else if(empty($errors)) { echo 'Your profile has been updated.'; } else { echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>'; } ?> </div> <form action="" method="post" enctype="multipart/form-data"> <div> <label for="email">Email: </label> <input type="text" name="email" id="email" value="<?php echo $userinfo['email']; ?>" /> </div> <div> <label for="location">Location: </label> <input type="text" name="location" id="location" value="<?php echo $userinfo['location']; ?>" /> </div> <div> <label for="about">About Me: </label> <textarea name="about" id="about" rows="14" cols="50"><?php echo strip_tags($userinfo['about']); ?></textarea> </div> <div> <label for="avatar">Avatar: </label> <input type="file" name="avatar" id="avatar"/> </div> <div> <input type="submit" value="Update" /> </div> </form> </body> </html> here is the function taken from an external file Code: [Select] function set_profile_info($email, $location,$about,$avatar) { $email = mysql_escape_string(htmlentities($email)); $about = mysql_escape_string(nl2br(htmlentities($about))); $location = mysql_escape_string($location); if (file_exists($avatar)) { $src_size = getimagesize($avatar); if ($src_size['mime'] === 'image/jpeg') { $src_img = imagecreatefromjpeg($avatar); } else if ($src_size['mime'] === 'image/png') { $src_img = imagecreatefrompng($avatar); } else if ($src_size['mime'] === 'image/gif') { $src_img = imagecreatefromgif($avatar); } else { $src_img = false; } if ($src_img !== false) { $thumb_width= 200; if($src_size[0] <= $thumb_width) { $thumb = $src_img; } else { $new_size[0] = $thumb_width; $new_size[1] = ($src_size[1] / $src_size[0]) * $thumb_width; $thumb = imagecreatetruecolor($new_size[0], $new_size[1]); imagecopyresampled($thumb, $src_img, 0, 0, 0, 0, $new_size[0], $new_size[1], $src_size[0], $src_size[1]); } imagejpeg($thumb, "{$GLOBALS['path']}/user_avatars/{$_SESSION['uid']}.jpg"); } } $sql = "UPDATE `users` SET `user_email` = '{$email}', `user_about` = '{$about}', `user_location` = '{$location}' WHERE `user_id` = {$_SESSION['uid']}"; mysql_query($sql); } Below I have returned the array of files to check if its been uploaded correctly. Array ( [avatar] => Array ( [name] => Sonic.jpg [type] => image/jpeg [tmp_name] => /var/tmp/php.waq8n [error] => 0 [size] => 48477 ) ) But I get this error message. Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: '/var/tmp/php.waq8n' is not a valid JPEG file in /web/stud/u0963643/userprofilesection/finaluserprofile/core/inc/user.inc.php on line 71 If someone could point out where in this code I have made an error I would be very grateful Thanks Jamie Hi guys I am using the code below to upload files, image files seem to upload ok, but for some reason I cnt seem to upload pdf files.. any suggestions? Thank you <?php ini_set('file_uploads','on'); ini_set('upload_max_filesize','1000M'); ini_set('max_execution_time', 0); 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("invoices/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "invoices/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } ?> <form action="" 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="Submit" /> </form> Hi Guys
I run a small roofing company and have been asked by many customers to be able to view / print / save Invoices & Estimates online rather than post etc. I host my own private site using IIS 7, with PHP and MySQL installed and setup properly, I also have a hosted domain from 1and1 What I would like is: Login Area (I can do this using the MySQL for the database) Once the user logs in, I want them to be directed to their "own" page with links to Their Own Invoices, Estimates and PIctures I would like an option somewhere for them to upload pictures into their own folder so if anything happens to their roof, they can simply log onto their account upload the pic of the damage and I can see it. and vice versa Can someone help me out a little? All I have so far is the Login page can anyone tell me why this code doesn't work if it tries to upload like more than 3 files?: Code: [Select] <?php include_once "secure/connect_to_mysql.php"; function genRandomString($length = 20) { $characters = '0123456789'; $string =''; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return $string; } if ($_POST['submit']) { $name = $_POST['name']; $id = $_POST['id']; $image = $_POST['image']; $event = $_POST['event']; $template = 'template.php'; $picture = '$name.png'; $id = genRandomString(); //this could be the uploaded picture $target_path = "images/"; foreach ($_FILES["uploadedfile"]["name"] as $key => $value) { $uploadfile = $target_path . basename($_FILES[uploadedfile][name][$key]); //echo $uploadfile; if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'][$key], $uploadfile)) { echo $value . ' uploaded<br>'; } //we need just the filename - no extension $picture_name = pathinfo($picture, PATHINFO_FILENAME); $sql = "INSERT INTO pictures (name, id, image, event) VALUES('$name', '$id','images/$value','$event')"; $rs = mysql_query($sql) or die ("Problem with the query: $sql<br>" . mysql_error()); echo mysql_error(); } copy($template, "$event.php"); } ?> <form action="new.php" method="post" enctype="multipart/form-data"><input name="id" type="hidden" value=<?php echo $id; ?> /><br /> Event Name:<input name="event" type="text" /><input name="image" id="image" type="hidden" value="images/<?php echo $value; ?>" /><input type="hidden" name="MAX_FILE_SIZE" value="900000000000000000000000000000000000000000000000000000000000000000000000000" /> Choose a file to upload: <div id="dynamicInput"> <br>Pictu <input type="file" id="file" name="uploadedfile[]" onClick="addInput('dynamicInput');" > </div> <input type="button" value="Add another text input" onClick="addInput('dynamicInput');"> <br /><input name="submit" type="submit" value="submit" /></form> is it the code or something else? Hi, I have a system that uses PHP to create a Word Doc as information is extracted from a table using this code: Code: [Select] header("Content-type: applicaton/save"); header("Content-Disposition: attachment; filename="FILE NAME".doc"); header("Pragma: no-cache"); header("Expires: 0"); This part of the system I'm trying to implement is working fine. However, what I would ideally like for it to do (and at this point I understand that it sounds a bit pointless) is to save that downloaded file onto a specified folder location on the server directory i.e. to the uploads folder. This will enable all users of the system to then download / view these files as required. I'm not sure whether this is possible or not but and help would be greatly appreciated. Thanks in advance, Ben |