PHP - Simple Browse For Image And Save To Db
Hi Guys,
Please can someone here help me with a simple browse for an image from the computer and then when the form is submitted it uploads the image and then saves the image url in my DB. my form page is here http://bit.ly/gntCvD Any help will be appreciated. thanks Craig Similar TutorialsThis topic has been moved to PHP Installation & Configuration. http://www.phpfreaks.com/forums/index.php?topic=307015.0 This resizer works fine except I would like it to save the original image AND the thumbnail. Right now its only saving the cropped thumbnail. It's seems simple enough but I've tried several different ways but can't get it to work. :( I would appreciate your help. :) define( 'DESIRED_IMAGE_WIDTH', 150 ); define( 'DESIRED_IMAGE_HEIGHT', 150 ); $source_path = $_FILES[ 'thumb' ][ 'tmp_name' ]; $timestamp = time(); $target = "image_files/".$imagename; move_uploaded_file($source, $target); // // Add file validation code here // list( $source_width, $source_height, $source_type ) = getimagesize( $source_path ); switch ( $source_type ) { case IMAGETYPE_GIF: $source_gdim = imagecreatefromgif( $source_path ); break; case IMAGETYPE_JPEG: $source_gdim = imagecreatefromjpeg( $source_path ); break; case IMAGETYPE_PNG: $source_gdim = imagecreatefrompng( $source_path ); break; } $source_aspect_ratio = $source_width / $source_height; $desired_aspect_ratio = DESIRED_IMAGE_WIDTH / DESIRED_IMAGE_HEIGHT; if ( $source_aspect_ratio > $desired_aspect_ratio ) { // // Triggered when source image is wider // $temp_height = DESIRED_IMAGE_HEIGHT; $temp_width = ( int ) ( DESIRED_IMAGE_HEIGHT * $source_aspect_ratio ); } else { // // Triggered otherwise (i.e. source image is similar or taller) // $temp_width = DESIRED_IMAGE_WIDTH; $temp_height = ( int ) ( DESIRED_IMAGE_WIDTH / $source_aspect_ratio ); } // // Resize the image into a temporary GD image // $temp_gdim = imagecreatetruecolor( $temp_width, $temp_height ); imagecopyresampled( $temp_gdim, $source_gdim, 0, 0, 0, 0, $temp_width, $temp_height, $source_width, $source_height ); // // Copy cropped region from temporary image into the desired GD image // $x0 = ( $temp_width - DESIRED_IMAGE_WIDTH ) / 2; $y0 = ( $temp_height - DESIRED_IMAGE_HEIGHT ) / 2; $desired_gdim = imagecreatetruecolor( DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT ); imagecopy( $desired_gdim, $temp_gdim, 0, 0, $x0, $y0, DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT ); // // Render the image // Alternatively, you can save the image in file-system or database // header( 'Content-type: image/jpeg' ); imagejpeg( $desired_gdim, "image_files/" . $timestamp . $_FILES["thumb"]["name"] ); hi all, i'm trying to save an image after cropping it using jcrop (jquery plugin). i'm currently using a script i found on the internet called ImageManipulation.php (attached). its working fine, but i get a black image if i crop a gif, or png images (works great for jpg images). Code: [Select] $objImage = new ImageManipulation("../products/" . $_SESSION['image']); if ($objImage->imageok) { // get x, y, w, h from hidden inputs that are update by jcrop $objImage->setCrop($_POST['x'], $_POST['y'], $_POST['w'], $_POST['h']); $objImage->resize(150); $objImage->save("../products/" . $_SESSION['image']); } how can i fix this?? if you have a better way of using php with jcrop to save cropped images please share it thanks for the help Hi I have a javascript image cropping script which is working well, I then have some php to save the new cropped image. But I can't seem to get it working 100%. When the form is posted the cropped image is not created and I get a "The connection was reset" error. If I comment out the line Code: [Select] $source=imagecreatefromjpeg($image); then I dont get the The connection was reset" error but the image is obviously still not created. Can anyone help? Code: [Select] <?php function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){ list($imagewidth, $imageheight, $imageType) = getimagesize($image); $imageType = 'image/jpeg'; $newImageWidth = ceil($width * $scale); $newImageHeight = ceil($height * $scale); $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight); switch($imageType) { case "image/jpeg": case "image/jpg": $source=imagecreatefromjpeg($image); break; } imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height); switch($imageType) { case "image/jpeg": case "image/jpg": imagejpeg($newImage,$thumb_image_name,90); break; } chmod($thumb_image_name, 0777); return $thumb_image_name; } function getHeight($image) { $size = getimagesize($image); $height = $size[1]; return $height; } function getWidth($image) { $size = getimagesize($image); $width = $size[0]; return $width; } $large_image_location = $upload_path.$large_image_name.'.jpg'; $thumb_image_location = $upload_path.$thumb_image_name.'.jpg'; if (isset($_POST["upload_thumbnail"])) { $x1 = $_POST["x1"]; $y1 = $_POST["y1"]; $x2 = $_POST["x2"]; $y2 = $_POST["y2"]; $w = $_POST["w"]; $h = $_POST["h"]; $scale = $thumb_width/$w; $cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale); header("location:index.php"); exit(); } ?> Hi all, i need little help in saving and download gif image created by using GD library. code works fine in mozilla and crome but in IE a new new page where the image is created,saved as well as dowloaded remains open and shows this"Action canceled". but the image is stored and downloaded on my system. i just want to close this page automatically when download is complete Code: [Select] <?php ob_start(); ini_set("memory_limit","180M"); $data = explode(",", $_POST['img']); $width = $_POST['wp']; $height = $_POST['ht']; $image=imagecreatetruecolor( $width ,$height ); $background = imagecolorallocate( $image ,0 , 0 , 0 ); //Copy pixels $i = 0; for($x=0; $x<=$width; $x++){ for($y=0; $y<=$height; $y++){ $int = hexdec($data[$i++]); $color = ImageColorAllocate ($image, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int); imagesetpixel ( $image , $x , $y , $color ); } } //Output image and clean header( "Content-type: image/gif" ); $name = rand(0,9999); $n = $name; $name = "img/".$name.".gif"; ImageGIF($image,$name,100); imagedestroy($image); $path = "http://localhost/madeup/img/"; $fullPath = $path.$n.'.gif'; if ($fd = fopen ($fullPath, "r")) { header( "Content-type: image/gif" ); header("Content-Disposition: attachment; filename=".$n); header("Cache-control: private"); while(!feof($fd)) { $buffer = fread($fd, 2048); echo $buffer; } } fclose ($fd); ob_end_flush(); exit; ?> I'm trying to save images from a directory into mine. To get the image I am having to take the email from a database, split it and take whatever it is before the '@' sign and add it to "-S.jpg". I wrote the script and when I echo the variable it shows the correct thing, but when it tries to save it , it is trying to find the image as "script>-S.jpg". It looks like it is taking whatever is after the last '/' which in the variable since I am running javascript it is going to be </script> if you look at my variable $url. Here is the code below. Any help is appreciated. while($rows=mysql_fetch_array($result)){ $email=$rows['email']; $url= "<SCRIPT LANGUAGE=\"javascript\"> var url; var email = \"$email\"; function emailsplit () { var userid = email.split(\"@\"); var url = userid[0]; var imgid = \"http://my.snu.edu/images/idpictures/\" + url + \"-S.jpg\"; return url; } document.write(emailsplit()); </script> "; $img[]= 'http://my.snu.edu/images/idpictures/'.$url.'-S.jpg'; } function save_image($img,$fullpath='basename'){ if($fullpath=='basename'){ $fullpath = basename($img); } $ch = curl_init ($img); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec($ch); curl_close ($ch); if(file_exists($fullpath)){ unlink($fullpath); } $fp = fopen($fullpath,'x'); fwrite($fp, $rawdata); fclose($fp); } foreach($img as $i){ save_image($i); if(getimagesize(basename($i))){ echo '<h3 style="color: green;">Image ' . basename($i) . ' Downloaded OK</h3>'; }else{ echo '<h3 style="color: red;">Image ' . basename($i) . ' Download Failed</h3>'; } } Hi, I am tryng to use the gd functions in php to output an image of a lower quality and save it as another image: Code: [Select] header('Content-Type: image/jpeg'); $im = @imagecreatefromjpeg('SDC10424.JPG'); imagejpeg($im, null, 50);// this line lowers the image quality imagedestroy($im); but the problem is how to save it? I tried file_put_contents, but it didnt work, like fileputcontents("test.jpg", $im); How can i save image just assume that i have "test.jpg" and wish to store the image to directory "directory A" using Curl..how can i do that? thanks in adv My current project requires me to save the number of views an image (banner ad) has appeared on users website. The problem here is that the image will be appearing on several users website and i want to be able to save the number of times it has appeared on my database. I know how to do this if the image was on the same server as the database, but not when the image and database are on completely different servers. This is somewhat like analytic where it tracks the visitors to a page. Does anyone how i can accomplish this? i figured i would need to create a JavaScript code to provide to the user so they can place it on the site but how do i get that code to connect to my database? Hey guys! I have the following script to create an excel file, the thing is that I dont want to be asked if I want to open or save the file when accessing the php file...I just want the php file directly to save the excel file. Heres the code: $filename = "test.xls"; $contents = "testdata1 \ntestdata2 \ntestdata3 \n"; header('Content-type: application/vnd.ms-excel'); header('Content-Disposition: attachment; filename='.$filename); echo $contents; Is there a way instead of using the header function, use something like: fopen, fwrite, fclose ? Thanks in advance! Cheers, This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=321638.0 I have a script that will allow me to mkdir by inputing a folder name and so forth. Is there a way that I can browse for a directory or create one if needed? Is there a browse script so that I can make the dir? What I am trying to accomplish is an image upload script where I can either create a new directory or choose from an existing one. Is this even possible? Thanks in advance! Hi guys, I've created some coding and a button allowing the user to browse their local machine and upload a file, with certain details then displayed on a new web page. Is there a way I can get the ouput to display on a popup window rather than navigate to a new browser page? The code I have used to create this is: 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" /> <input type="submit" name="submit" value="Start" style="height:50px" /> </form> When the user clicks the 'start' button, the php script runs and retrieves the information required but I want this to be output on a popup window. Cheers for your time Hi All, sure this is simple but I'm still new to php/mySQL so errors are abundant! I have a simple form with one input: a browse button so the user can find a .csv file on their computer. User then clicks button, upon which I would like the file to be read and the contents put into an array, and the values to be added to the database. I do not need the file to be stored (uploaded). So far my code is not erroring, it just doesn't add the values to the db. I'm wondering if it's just that I HAVE to upload and save the file to the webserver else I can't read it? if(isset($_FILES['file_path']['tmp_name'])&& $_FILES['file_path']['tmp_name'] !=''){ $file_to_import = $_FILES['file_path']['tmp_name']; $import_data = file($file_to_import); print_r($import_data); if ($import_data !=''){ for($index = 1; $index < sizeof($import_data); $index++){ $order_data = explode(",",$import_data[$index]); tep_db_query("UPDATE orders SET act_shipping_cost = '" . $order_data[8]. "' WHERE orders_id = '". $order_data[0]."'"); echo "done it"; } }else{ echo 'error cant read file!'; } } else{ ?> <!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN"> etc etc etc <form id="shipping_costs_upload" name="csv_file_reader" method="post" action="shipping_cost_upload.php"> <div class="main" id="info_text"><h2>Upload Actual Shipping Costs CSV</h2><p>To upload actual shipping cost data, browse to your csv and click the Upload Data button.<br /><br /></p> <div class="date" id="file"> <strong>CSV File: </strong><input type="file" name="file_path" id="file_url" /> </div> <div class="date"><input type="submit" value="Upload Data"> </div> </form> etc etc etc Apologies if I'm being a complete dunce! Ok, I have this code that is supposed to upload a csv file and save the contents into a specific sql table. I am getting an error when i hit submit that states the file is empty, meaning the csv file. I am thinking that the file isn't really being targeted i just don't know how to fix it. To start i have a php page with a the form and then i have another php page that is included in the form php page. The functions for submitting the csv info in the text file is located in the include file. here is the code: Code: [Select] $csv = new Quick_CSV_import(); $arr_encodings = $csv->get_encodings(); //take possible encodings list $arr_encodings["default"] = "[default database encoding]"; //set a default (when the default database encoding should be used) if(!isset($_POST["encoding"])) $_POST["encoding"] = "default"; //set default encoding for the first page show (no POST vars) if(isset($_POST["Go"]) && ""!=$_POST["Go"]) //form was submitted { $csv->file_name = $HTTP_POST_FILES['file_source']['tmp_name']; //optional parameters $csv->use_csv_header = isset($_POST["use_csv_header"]); $csv->field_separate_char = $_POST["field_separate_char"][0]; $csv->field_enclose_char = $_POST["field_enclose_char"][0]; $csv->field_escape_char = $_POST["field_escape_char"][0]; $csv->encoding = $_POST["encoding"]; //start import now $csv->import(); } else $_POST["use_csv_header"] = 1; ?> <tr> <td>Source CSV file to import:</td> <td rowspan="30" width="10px"> </td> <td><input type="file" name="file_source" id="file_source" class="edt" value="<?=$file_source?>"></td> </tr> and Code: [Select] class Quick_CSV_import { var $table_name = "tbl_product"; //where to import to var $file_name; //where to import from var $use_csv_header; //use first line of file OR generated columns names var $field_separate_char; //character to separate fields var $field_enclose_char; //character to enclose fields, which contain separator char into content var $field_escape_char; //char to escape special symbols var $error; //error message var $arr_csv_columns; //array of columns var $table_exists; //flag: does table for import exist var $encoding; //encoding table, used to parse the incoming file. Added in 1.5 version function Quick_CSV_import() { $this->file_name = $file_name; $this->arr_csv_columns = array(); $this->use_csv_header = true; $this->field_separate_char = ","; $this->field_enclose_char = "\""; $this->field_escape_char = "\\"; $this->table_exists = false; } function import() { if($this->table_name=="") $this->table_name = "temp_".date("d_m_Y_H_i_s"); $this->table_exists = false; $this->create_import_table(); if(empty($this->arr_csv_columns)) $this->get_csv_header_fields(); /* change start. Added in 1.5 version */ if("" != $this->encoding && "default" != $this->encoding) $this->set_encoding(); /* change end */ if($this->table_exists) { $sql = "LOAD DATA INFILE '".@mysql_escape_string($this->file_source). "' INTO TABLE `".$this-> table_name. "` FIELDS TERMINATED BY '".@mysql_escape_string($this->field_separate_char). "' OPTIONALLY ENCLOSED BY '".@mysql_escape_string($this->field_enclose_char). "' ESCAPED BY '".@mysql_escape_string($this->field_escape_char). "' ". ($this->use_csv_header ? " IGNORE 1 LINES " : "") ."(`".implode("`,`", $this->arr_csv_columns)."`)"; $res = @mysql_query($sql); $this->error = mysql_error(); } } //returns array of CSV file columns function get_csv_header_fields() { $this->arr_csv_columns = array(); $fpointer = fopen($file_name, "r"); if ($fpointer) { $arr = fgetcsv($fpointer, 10*1024, $this->field_separate_char); if(is_array($arr) && !empty($arr)) { if($this->use_csv_header) { foreach($arr as $val) if(trim($val)!="") $this->arr_csv_columns[] = $val; } else { $i = 1; foreach($arr as $val) if(trim($val)!="") $this->arr_csv_columns[] = "column".$i++; } } unset($arr); fclose($fpointer); } else $this->error = "file cannot be opened: ".(""==$this->file_name ? "[empty]" : @mysql_escape_string($this->file_name)); return $this->arr_csv_columns; } i just can't figure it out. could anyone help me out? the error i get says this: Warning: fopen() [function.fopen]: Filename cannot be empty in /Quick_CSV_import.php on line 83 hi- i'm trying to browse for a CSV file and then upload it to my mysql database. i found the code below and not working. i don't get any errors. the connection to the database is ok bcz i get the existing results but not the ones from the CSV file added to the db.. any ideas? Code: [Select] <?php ob_start(); require_once('../../connections/congif.php'); mysql_select_db($dbname, $db); $sql_get_project="SELECT * FROM gifts_tbl ORDER BY autoID DESC LIMIT 25"; $get_project = mysql_query($sql_get_project, $db) or die(mysql_error()); $row_get_project = mysql_fetch_assoc($get_project); //database connect info here //check for file upload if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){ //upload directory $upload_dir = "csv_dir/"; //create file name $file_path = $upload_dir . $_FILES['csv_file']['name']; //move uploaded file to upload dir if (!move_uploaded_file($_FILES['csv_file']['tmp_name'], $file_path)) { //error moving upload file echo "Error moving file upload"; } //open the csv file for reading $handle = fopen($file_path, 'r'); //turn off autocommit and delete the product table mysql_query("BEGIN"); while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) { //Access field data in $data array ex. $name = $data[0]; //Use data to insert into db $sql = sprintf("INSERT INTO gifts_tbl (player_id) VALUES ('%s)", mysql_real_escape_string($name) ); mysql_query($sql) or (mysql_query("ROLLBACK") and die(mysql_error() . " - $sql")); } unlink($file_path); } ob_flush(); ?> <!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>Gifts</title> </head> <body> <h1>Testing for CSV upload</h1> <form action="" method="post"> <input type="file" name="csv_file"> <input type="submit" name="csv_submit" value="Upload CSV File"> </form> <h2>Results</h2> <?php do { ?> <ul> <li><?php echo $row_get_project['player_id']; ?></li> </ul> <?php } while ($row_get_project = mysql_fetch_assoc($get_project)); ?> </body> </html> ok so ive found what looks to be a decent image uploader. which if anyone is interested can be found here; http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/ I have followed the instruction and added the few bits needed to make it work properly. However hence me beening here, it doesnt work. Im not overly familiar with the syntax of -> so maybe I am outputting the wrong name in the move_upload_file but the error I get on the server is Unable to move '/tmp/phpJnOkXP' to bla bla bla upload-new.php on line 126 Upload fail which is the move_upload line Here is my code <?php if( isset($_POST['uploadbtn']) ) { $folder = "{$_SERVER['DOCUMENT_ROOT']}/images/test/"; $fileName = $_FILES['newImage']['name']; $tmpName = $_FILES['image']['tmp_name']; include('../simple-image.php'); $image = new SimpleImage(); $image->load($tmpName); $image->resizeToWidth(600); $image->output(); $uploaded = move_uploaded_file($tmpName , $folder.$fileName); if($uploaded){ echo "Upload success"; } else { echo "Upload fail"; } } ?> <form action="" method="post" enctype="multipart/form-data" name="uploadfrm"> <input name="image" type="file" /> <input name="uploadbtn" value="Upload" type="submit" /> </form> I am trying to show images in a directory by date last modified. The code below is showing the oldest ones first then by file type. How do I modify it to show all files by last uploaded to the directory? I want the newest ones showing first. I am very new to PHP. Code: [Select] <?php //Your folder $files = glob("images/*.*"); $colCnt=0; echo '<table border="0" style="width:1000px;">'; for ($i=1; $i<count($files); $i++) { $colCnt++; if ($colCnt==1) echo '<tr>'; echo '<td width="20%" style="font-size:8.5px; font-family:arial">'; $num = $files[$i]; echo ' <a href="' . $num . '"><img class="thumb ImgBorder" src="'.$num.'" rel="lightbox" alt="random image"></a>'." "; echo '</td>'; if ($colCnt==6) { echo '</tr>'; $colCnt=0; } } echo '</table>'; ?> hey guys im trying to impliment a overlay to images uploaded by the user to allow to delete and crop...now im not sure if im going aroung this the right way (but it works sort of)...the problem im having is that the overlay.gif which is a transparent image which has 2 small images at the top of each corner...but when the original image is hovered over the overlay is out of position showing the 2 small images at the bottom of the div and not at the top where it should be.
im guessing it is a css issue...any advise would be greatly appreciated...thank you
#overlay { width: 110px; height: 110px; } .selected-image{ width: 110px; height: 110px; } #overlay:hover .selected-image { opacity: 0.4; filter: alpha(opacity=40); } #overlay:hover { background-image: url('overlay.gif'); width: 110px; height: 110px; } <div id="overlay"><img class="selected-image" src="logo.png" /></div> The code below works well and shows all the images in a folder in reverse chronological order. But I want to limit it to a certain number of images . This would enable me to have several pages of images. So the first page would display the latest 50 images, the second page would show 50-100, and the third, 100-150. Any helps on how to modify? I can create the pages manually. I just want to know how to limit the current page to a certain range. Code: [Select] <?php //Your folder $files = glob("images/*.*"); function sortnewestfilesfirst($a, $b) { return filemtime($b) - filemtime($a); } usort($files, "sortnewestfilesfirst"); $colCnt=0; echo '<table border="0" style="width:1000px;">'; for ($i=0; $i<count($files); $i++) { $colCnt++; if ($colCnt==1) echo '<tr>'; echo '<td width="20%" style="font-size:8.5px; font-family:arial">'; $num = $files[$i]; echo ' <div class="ImgBorder"> <div class="clipout"> <div class="clipin"> <a href="' . $num . '" rel="lightbox[all]"><img class="thumb ImgBorder" src="'.$num.'"> </a> </div> </div></div>'." "; echo '</td>'; if ($colCnt==6) { echo '</tr>'; $colCnt=0; } } echo '</table>'; ?> |