PHP - Uploading Photo To Mysql
what is the simple way to upload a photo to mysql
or store in a dir, and update the database with the new url? Similar TutorialsI let my members to upload their photos, I m using the script I coded which checks the file extension, if the file extension is "jpg" ( if ($this->url['type'] == "image/jpg")) and less than 600kb it uploads. Otherwise it gives you a warning.. What I wonder is, do I face any unwanted results about this later ? Like someone uploads a virus or script then execute it and do something ? I wonna to upload photo with js and ajax.. i can do inserting something in mysql, but i dont know how to do with files :/ Form: Code: [Select] <form enctype="multipart/form-data" method="get"> <center> <label>Title: <input type="text" name="s_name" value="" style="width:250px" /></label> <label>Image: <input type="file" name="s_image" style="width:250px" /></label> <input class="button" type="submit" name="s_add" value="Add" style="width:100px" OnClick="save();" /> </center> </form> This is js code: Code: [Select] function save() { col = document.getElementById("new"); if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { col.innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET","sources/save.php?i dont know what to insert here,true); xmlhttp.send(); } this is save.php: Code: [Select] <?php $allowed_size = 204800; $name = $_GET['name']; $name = $_GET['image']; $date = time(); if (save_img($up_imgfile, $up_imgname, $allowed_size)) { $query = "INSERT INTO table (name, image, date) VALUES ('{$name}', '{$image}', '$date')"; $result = mysql_query($query, $connection); if ($result) { echo "<p class='warn-green'>$season_name has been successful added</p>"; } else { echo "<p class='warn-red'>Error: $season_name is not added, try again.</p>"; } } } ?>save_img() is php function to upload photo and make thumb.. How can i do this thing to do this function, but i need this: $up_imgname = $_FILES['s_image']['name']; $up_imgfile = $_FILES['s_image']['tmp_name']; Becouse of that i cant do this, how can i get temp name, image name of uploaded file ? adding photo,Array ( [name] => profilepic.jpeg [type] => image/jpeg [tmp_name] => C:\xampp\tmp\phpB923.tmp [error] => 0 [size] => 152127 ) Hi, We have been using this code for ages, but suddenly for some reason we cannot upload an image using the code below. When we try to Print_r the $profilephoto variable, I get this error. The filename is correct, but what is that [error]?? And how do I resolve it? Oddly it does upload it locally, but LIVE, it won't This is the code. if (isset($updatephoto)) { echo "adding photo,"; print_r($profilephoto); define ("MAX_SIZE","5000"); function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } $errors=0; if($_SERVER["REQUEST_METHOD"] == "POST") { $image =$_FILES["profilephoto"]["name"]; $uploadedfile = $_FILES['profilephoto']['tmp_name']; if ($image) { $filename = stripslashes($_FILES['profilephoto']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { echo "Unknown Extension..!"; } else { $size=filesize($_FILES['profilephoto']['tmp_name']); if ($size > MAX_SIZE*1024) { echo "File Size Excedeed..!!"; } if($extension=="jpg" || $extension=="jpeg" ) { $uploadedfile = $_FILES['profilephoto']['tmp_name']; $src = imagecreatefromjpeg($uploadedfile); } else if($extension=="png") { $uploadedfile = $_FILES['profilephoto']['tmp_name']; $src = imagecreatefrompng($uploadedfile); } else { $src = imagecreatefromgif($uploadedfile); echo $scr; } list($width,$height)=getimagesize($uploadedfile); $newwidth=600; $newheight=($height/$width)*$newwidth; $tmp=imagecreatetruecolor($newwidth,$newheight); imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); $pic=($_FILES['profilephoto']['name']); $random = (rand()%99999999); $newname="$random"."$pic"; $filename = "images/profiles/". $newname; imagejpeg($tmp,$filename,100); imagedestroy($src); imagedestroy($tmp); }} } $query = ("UPDATE users SET profilephoto =:newname WHERE id =:userid"); $result = $pdo->prepare($query); $result->execute(array(':userid' => $userid, ':newname' => $newname)); echo "<script> window.location.replace('/profile/') </script>";}
Hello
I want to know to upload the XML file to mysql using php as i am new to xml any help appreciated.
awaiting your valuable reply
here also i am attaching the xml file which i want to upload
Thanks in Advance
Attached Files
xml1.xml 4.89KB
2 downloads Does anyone know of a good tutorial on uploading a picture file to a folder using php and copying the name to the database in mysql? Resizing photos on upload is helpful also...If you know it works...some I have tried do not work. Not asking for someone to write code for me but info or tutorial would be nice. Or maybe a code that has worked for you that is similar that I could learn from and edit... I can upload the actual photo into the database but it slows it way down. I have heard of loading the name only and resizing the photo and sending the actual photo to a file folder on the server. The few codes I have tried were not successful. Thanks for any guidance. I appreciate it. Hi, I need some assistance with coding a form to upload a picture into MySQL DB. This will be part of a form and have a field where the user can upload a picture from where-ever, click submit and the image is uploaded into MySQL. If anyone has done this and can offer assistance with the html coding, PHP and how to set the field in MySQL, I would be greatly appreciative. when i input this code it only uploads a single column into my database
<html> <head> <title>MySQL file upload example</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <form action="try2.php" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"><br> <input type="submit" name="submit"value="Upload file"> </form> <p> <a href="list_files.php">See all files</a> </p> </body> <?php $con=mysqli_connect("localhost","root","","book"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } if(isset($_POST['submit'])) { $fname = $_FILES['uploaded_file']['name']; $chk_ext = explode(".",$fname); if(strtolower($chk_ext[1]) == "csv") { $filename = $_FILES['uploaded_file']['tmp_name']; $handle = fopen($filename, "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $sql = "INSERT into data(name,Groups,phone_number) values('$data[0]','$data[1]','$data[2]')"; $result=mysqli_query($con,$sql) or die(mysql_error()); } fclose($handle); echo "Successfully Imported"; } else { echo "Invalid File"; } } ?> </html> hi i m new to php there is two basic script i m testing on my localhost but it gives me error "( ! ) Notice: Undefined index: video in C:\wamp\www\Boysjoys\video\upload.php on line 4" "( ! ) Notice: Undefined index: video in C:\wamp\www\Boysjoys\video\upload.php on line 16" "( ! ) Notice: Undefined index: video in C:\wamp\www\Boysjoys\video\upload.php on line 27" i cant find where is the real problem is ##########FORM########### <form name="upload" action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="video"> <input type="submit" value="UPLOAD"> </form> #########FORM############ #########PHP############# <?php // This is the directory where images will be saved $path="uploaded/"; $path=$path.basename($_FILES["video"]["name"]); //This gets all the other information from the form $video=$_FILES["video"]["name"]; //connect to database $con=mysql_connect("localhost","root","") or die (mysql_error()); //SELECTING THE DATABASE mysql_select_db("admin_bj",$con) or die(mysql_error()); //write information to the database mysql_query("INSERT INTO 'video'(video) VALUES('$video')"); //write file to server if(move_uploaded_file($_FILES["video"]["tmp_name"],$path)) { // execute if all is ok echo "the file " . basename( $_FILES['uploadedfile']['name']). "has been uploaded and your information has been added to the server"; } else { //GIVES AND ERROR IF ITS NOT OK echo "Sorry,there was a problem in uploading."; } ?> #########PHP############# Hi guys, I have this code that I created. It is suppost to get a file from a form and upload it to a directory that is outside the root folder of my webserver. then the image name is added to the preset location of the directory that contains all of the uploaded images and is placed into a mysql database so I can call it later. the problem I have is that when some one else signs up through this form and the file they upload has the same file name it replaces the one that is already in the images directory that has all the other pictures. I need to add something to this code that adds $username to the end of the original file name and then uploads it to the directory with the new name. Since every username is unique it will make every username unique and will eliminate my problem. I am not sure how to do this. Please, anyone that can help. Thanks. This is my code. // get file attributes!!!!! $photoname = $_FILES['photo']['name']; $tmp_name = $_FILES['photo']['tmp_name']; if ($photoname) { // start upload process $location = "../userpictures/$photoname"; move_uploaded_file($tmp_name,$location); } else { $location = "../userpictures/nophoto.png"; } $queryreg = mysql_query(" INSERT INTO users VALUES ('','$fullname','$username','$password','$date','$location','$email','$phone') "); If there is a better way to upload images to a mysql database and outputting it later then please let me know as well. Thanks. hi everyone im new to php. I have been reading few books. im trying to build a image gallery. the first step is to upload a images. in the process of uploading, i want to resize the image then add watermark last insert into the database which is mysql, (i know about the dont insert image into database thing). here is the form script Code: [Select] <?php require_once('globals.php'); ?> <html> <head> <title>Upload an Image</title> </head> <body> <div> <h1>Upload an Image</h1> <p> <a href="./">View uploaded images</a> </p> <form method="post" action="process.php" enctype="multipart/form-data"> <div> <input type="file" name="image" /> <input type="submit" value="Upload Image" /> </div> </form> </div> <!-- <form action="watermark-image.php" method="post" enctype="multipart/form-data"> Select a file to upload for processing<br> <input type="file" name="File1"><br> <input type="submit" value="Submit File"> </form> --> </body> </html> here is the watermark script Code: [Select] <?php require_once('globals.php'); ?> <html> <head> <title>Upload an Image</title> </head> <body> <div> <h1>Upload an Image</h1> <p> <a href="./">View uploaded images</a> </p> <form method="post" action="process.php" enctype="multipart/form-data"> <div> <input type="file" name="image" /> <input type="submit" value="Upload Image" /> </div> </form> </div> <!-- <form action="watermark-image.php" method="post" enctype="multipart/form-data"> Select a file to upload for processing<br> <input type="file" name="File1"><br> <input type="submit" value="Submit File"> </form> --> </body> </html> here is my resize script Code: [Select] <?php # ========================================================================# # # Author: Jarrod Oberto # Version: 1.0 # Date: 17-Jan-10 # Purpose: Resizes and saves image # Requires : Requires PHP5, GD library. # Usage Example: # include("classes/resize_class.php"); # $resizeObj = new resize('images/cars/large/input.jpg'); # $resizeObj -> resizeImage(150, 100, 0); # $resizeObj -> saveImage('images/cars/large/output.jpg', 100); # # # ========================================================================# Class resize { // *** Class variables private $image; private $width; private $height; private $imageResized; function __construct($fileName) { // *** Open up the file $this->image = $this->openImage($fileName); // *** Get width and height $this->width = imagesx($this->image); $this->height = imagesy($this->image); } ## -------------------------------------------------------- private function openImage($file) { // *** Get extension $extension = strtolower(strrchr($file, '.')); switch($extension) { case '.jpg': case '.jpeg': $img = @imagecreatefromjpeg($file); break; case '.gif': $img = @imagecreatefromgif($file); break; case '.png': $img = @imagecreatefrompng($file); break; default: $img = false; break; } return $img; } ## -------------------------------------------------------- public function resizeImage($newWidth, $newHeight, $option="auto") { // *** Get optimal width and height - based on $option $optionArray = $this->getDimensions($newWidth, $newHeight, $option); $optimalWidth = $optionArray['optimalWidth']; $optimalHeight = $optionArray['optimalHeight']; // *** Resample - create image canvas of x, y size $this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight); imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height); // *** if option is 'crop', then crop too if ($option == 'crop') { $this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight); } } ## -------------------------------------------------------- private function getDimensions($newWidth, $newHeight, $option) { switch ($option) { case 'exact': $optimalWidth = $newWidth; $optimalHeight= $newHeight; break; case 'portrait': $optimalWidth = $this->getSizeByFixedHeight($newHeight); $optimalHeight= $newHeight; break; case 'landscape': $optimalWidth = $newWidth; $optimalHeight= $this->getSizeByFixedWidth($newWidth); break; case 'auto': $optionArray = $this->getSizeByAuto($newWidth, $newHeight); $optimalWidth = $optionArray['optimalWidth']; $optimalHeight = $optionArray['optimalHeight']; break; case 'crop': $optionArray = $this->getOptimalCrop($newWidth, $newHeight); $optimalWidth = $optionArray['optimalWidth']; $optimalHeight = $optionArray['optimalHeight']; break; } return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight); } ## -------------------------------------------------------- private function getSizeByFixedHeight($newHeight) { $ratio = $this->width / $this->height; $newWidth = $newHeight * $ratio; return $newWidth; } private function getSizeByFixedWidth($newWidth) { $ratio = $this->height / $this->width; $newHeight = $newWidth * $ratio; return $newHeight; } private function getSizeByAuto($newWidth, $newHeight) { if ($this->height < $this->width) // *** Image to be resized is wider (landscape) { $optimalWidth = $newWidth; $optimalHeight= $this->getSizeByFixedWidth($newWidth); } elseif ($this->height > $this->width) // *** Image to be resized is taller (portrait) { $optimalWidth = $this->getSizeByFixedHeight($newHeight); $optimalHeight= $newHeight; } else // *** Image to be resizerd is a square { if ($newHeight < $newWidth) { $optimalWidth = $newWidth; $optimalHeight= $this->getSizeByFixedWidth($newWidth); } else if ($newHeight > $newWidth) { $optimalWidth = $this->getSizeByFixedHeight($newHeight); $optimalHeight= $newHeight; } else { // *** Sqaure being resized to a square $optimalWidth = $newWidth; $optimalHeight= $newHeight; } } return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight); } ## -------------------------------------------------------- private function getOptimalCrop($newWidth, $newHeight) { $heightRatio = $this->height / $newHeight; $widthRatio = $this->width / $newWidth; if ($heightRatio < $widthRatio) { $optimalRatio = $heightRatio; } else { $optimalRatio = $widthRatio; } $optimalHeight = $this->height / $optimalRatio; $optimalWidth = $this->width / $optimalRatio; return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight); } ## -------------------------------------------------------- private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight) { // *** Find center - this will be used for the crop $cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 ); $cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 ); $crop = $this->imageResized; //imagedestroy($this->imageResized); // *** Now crop from center to exact requested size $this->imageResized = imagecreatetruecolor($newWidth , $newHeight); imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight); } ## -------------------------------------------------------- public function saveImage($savePath, $imageQuality="100") { // *** Get extension $extension = strrchr($savePath, '.'); $extension = strtolower($extension); switch($extension) { case '.jpg': case '.jpeg': if (imagetypes() & IMG_JPG) { imagejpeg($this->imageResized, $savePath, $imageQuality); } break; case '.gif': if (imagetypes() & IMG_GIF) { imagegif($this->imageResized, $savePath); } break; case '.png': // *** Scale quality from 0-100 to 0-9 $scaleQuality = round(($imageQuality/100) * 9); // *** Invert quality setting as 0 is best, not 9 $invertScaleQuality = 9 - $scaleQuality; if (imagetypes() & IMG_PNG) { imagepng($this->imageResized, $savePath, $invertScaleQuality); } break; // ... etc default: // *** No extension - No save. break; } imagedestroy($this->imageResized); } ## -------------------------------------------------------- } ?> here is the insert database script Code: [Select] <?php require_once('globals.php'); function assertValidUpload($code) { if ($code == UPLOAD_ERR_OK) { return; } switch ($code) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $msg = 'Image is too large'; break; case UPLOAD_ERR_PARTIAL: $msg = 'Image was only partially uploaded'; break; case UPLOAD_ERR_NO_FILE: $msg = 'No image was uploaded'; break; case UPLOAD_ERR_NO_TMP_DIR: $msg = 'Upload folder not found'; break; case UPLOAD_ERR_CANT_WRITE: $msg = 'Unable to write uploaded file'; break; case UPLOAD_ERR_EXTENSION: $msg = 'Upload failed due to extension'; break; default: $msg = 'Unknown error'; } throw new Exception($msg); } $errors = array(); try { if (!array_key_exists('image', $_FILES)) { throw new Exception('Image not found in uploaded data'); } $image = $_FILES['image']; // ensure the file was successfully uploaded assertValidUpload($image['error']); if (!is_uploaded_file($image['tmp_name'])) { throw new Exception('File is not an uploaded file'); } $info = getImageSize($image['tmp_name']); if (!$info) { throw new Exception('File is not an image'); } } catch (Exception $ex) { $errors[] = $ex->getMessage(); } if (count($errors) == 0) { // no errors, so insert the image $query = sprintf( "insert into images (filename, mime_type, file_size, file_data) values ('%s', '%s', %d, '%s')", mysql_real_escape_string($image['name']), mysql_real_escape_string($info['mime']), $image['size'], mysql_real_escape_string( file_get_contents($image['tmp_name']) ) ); mysql_query($query, $db); $id = (int) mysql_insert_id($db); // finally, redirect the user to view the new image header('Location: view.php?id=' . $id); exit; } ?> <html> <head> <title>Error</title> </head> <body> <div> <p> The following errors occurred: </p> <ul> <?php foreach ($errors as $error) { ?> <li> <?php echo htmlSpecialChars($error) ?> </li> <?php } ?> </ul> <p> <a href="upload.php">Try again</a> </p> </div> </body> </html> here is my view script Code: [Select] <?php require_once('globals.php'); try { if (!isset($_GET['id'])) { throw new Exception('ID not specified'); } $id = (int) $_GET['id']; if ($id <= 0) { throw new Exception('Invalid ID specified'); } $query = sprintf('select * from images where image_id = %d', $id); $result = mysql_query($query, $db); if (mysql_num_rows($result) == 0) { throw new Exception('Image with specified ID not found'); } $image = mysql_fetch_array($result); } catch (Exception $ex) { header('HTTP/1.0 404 Not Found'); exit; } header('Content-type: ' . $image['mime_type']); header('Content-length: ' . $image['file_size']); echo $image['file_data']; ?> my main question is how to link them all together. any clues i appreciatte I am very new to php and am trying to create a simple application that uploads a PDF file to a database. I have one field for the Volume Number and on file field for the PDF to be uploaded. My issue is i can't get the PDF to upload or insert the name of the pdf (eg volume1.pdf) into the data base. I would also like to point out that I know i have a low post count, but i only seek help when i truly need it and have exhausted all other resources... Here is what i have, please go easy on me this is my first round at php: Code: [Select] <?php if(isset($_POST['submit'])){ $vol_num = $_POST['vol_num']; $pdf = $_FILES['pdf']['name']; $path = '../pdf/'.$_FILES['pdf']['name']; move_uploaded_file($_FILES["pdf"]["tmp_name"], $path); mysql_query("INSERT INTO volumes set vol_num='$vol_num', vol_link='$pdf'") or die (mysql_error()); echo "<script>location.href='add_volume.php'</script>"; } ?> what am i doing wrong here? Thanks in advance Greetings, What I'm trying to do is have users upload their event information into a database which would include a flyer. I don't want the image file to go into the database (other than the filename) rather I'd like it to be dropped into a directory. In the same script I'd like to dynamically generate a thumbnail. I have the two scripts and separately they work fine, but I can't get them to work together. I'm guessing the conflict because the thumbnail script is using $_POST and the mysql script is using $_SESSION. If so how can I modify them to both use $_SESSION? The thumbnail script is goes from line 1 - 146 and the mysql portion is the rest. The results of processing this look something like this. QUERY TEXT: INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) VALUES ('12', 'spooky times', 'Ironwood Stage & Grill', '2010-12-17 22:36:00', 'DNB', '5000', 'me', '174366-1.jpg') <?php $debug = FALSE; /********************************************************************************************** CREATES THUMBNAIL **********************************************************************************************/ //define a maxim size for the uploaded images define ("MAX_SIZE","1024"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","500"); define ("HEIGHT","650"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext) || !strcmp("JPG",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext) || !strcmp("PNG",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) // and it will be changed to 1 if an error occurs. If the error occurs the file will not be uploaded. $errors=0; // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['eventflyer']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['eventflyer']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message // and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "JPG") && ($extension != "PNG") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which // the uploaded file was stored on the server $size=getimagesize($_FILES['eventflyer']['tmp_name']); $sizekb=filesize($_FILES['eventflyer']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*500) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=$filename; //the new name will be containing the full path where will be stored (images folder) $newname="flyers/".$image_name; $copied = copy($_FILES['eventflyer']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='flyers/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters // the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } /************************************************************ Adjust the headers... ************************************************************/ header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 /***************************************************************************** Check the session details. we will store all the post variables in session variables this will make it easier to work with the verification routines *****************************************************************************/ session_start(); if (!isset($_SESSION['SESSION'])) require_once( "../include/session_init.php"); $arVal = array(); require_once("../include/session_funcs1.php"); reset ($_POST); while (list ($key, $val) = each ($_POST)) { if ($val == "") $val = "NULL"; $arVals[$key] = (get_magic_quotes_gpc()) ? $val : addslashes($val); if ($val == "NULL") $_SESSION[$key] = NULL; else $_SESSION[$key] = $val; if ($debug) echo $key . " : " . $arVals[$key] . "<br>"; } /********************************************************************************************** Make sure session variables have been set and then check for required fields otherwise return to the registration form to fix the errors. **********************************************************************************************/ // check to see if these variables have been set... if ((!isset($_SESSION["eventname"])) || (!isset($_SESSION["eventvenue"])) || (!isset($_SESSION["eventdate"])) || (!isset($_SESSION["eventgenre"])) || (!isset($_SESSION["eventprice"])) || (!isset($_SESSION["eventpromoter"])) || (!isset($_SESSION["eventflyer"]))) { resendToForm("?flg=red"); } // form variables must have something in them... if ($_SESSION['eventname'] == "" || $_SESSION['eventvenue'] == "" || $_SESSION['eventdate'] == "" || $_SESSION['eventgenre'] == "" || $_SESSION['eventprice'] == "" || $_SESSION['eventpromoter'] == "" || $_SESSION['eventflyer'] == "") { resendToForm("?flg=red"); } /********************************************************************************************** Insert into the database... **********************************************************************************************/ $conn = mysql_connect($_SESSION['MYSQL_SERVER1'],$_SESSION['MYSQL_LOGIN1'],$_SESSION['MYSQL_PASS1']) or die ('Error connecting to mysql'); mysql_select_db($_SESSION['MYSQL_DB1']) or die("Unable to select database"); $eventgenre_sel = addslashes($_REQUEST['eventgenre_sel']); $eventname = addslashes($_REQUEST['eventname']); $eventvenue = addslashes($_REQUEST['eventvenue']); $eventdate = addslashes($_REQUEST['eventdate']); $eventgenre = addslashes($_REQUEST['eventgenre']); $eventprice = addslashes($_REQUEST['eventprice']); $eventpromoter = addslashes($_REQUEST['eventpromoter']); $eventflyer = addslashes($_REQUEST['eventflyer']); $sqlquery = "INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) " ."VALUES ('$eventgenre_sel', '$eventname', '$eventvenue', '$eventdate', '$eventgenre', '$eventprice', '$eventpromoter', '$eventflyer')"; echo 'QUERY TEXT:<br />'.$sqlquery; $result = MYSQL_QUERY($sqlquery); $insertid = mysql_insert_id(); /*** This following function will update session variables and resend to the form so the user can fix errors ***/ function resendToForm($flags) { reset ($_POST); // store variables in session... while (list ($key, $val) = each ($_POST)) { $_SESSION[$key] = $val; } // go back to the form... //echo $flags; header("Location: /user_registration.php".$flags); exit; } mysql_close($conn); ?> I'm having a problem understanding how to import more than one photo in a list of up to 20 photos. I can only import 1 photo from a comma delimited csv with a pipe between each photo url. <? function getImg($value,$userid, $stocknum){ $photoStr = ''; if($value !=''){ $photoURLs = explode('|', $value); for($i=0; $i<count($photoURLs);$i++){ $url = $photoURLs[$i]; $j = $i+1; if (@copy($url, "../upload/".$userid."/".$userid."_".$stocknum."_".$j.".jpg")) { $photoStr .= $userid."_".$stocknum."_".$j.".jpg|"; } } } return $photoStr; } ?> And after csv and sql <? if($img){ $img = rtrim($img, '|'); $imgArray = explode('|', $img); $imgIndex = 1; foreach ($imgArray AS $imgItem){ $db->query("UPDATE `stockitem` SET img".$imgIndex."= '$imgItem' where stocknum='$stocknum'","" , __FILE__, __LINE__); $imgIndex++; } } ?> Any help would be appreciated. Hi all, i was wondering if someone could point me in the right direction on how to create the following. After someone uploaded a photo than Cut out only his head in a fixed square say 90x120 pix (of a larger picture). I have seen some on the internet but most of them use flash and i rather use javascript or no javascript at all. Can this be done with GD library for instance where you just give the coordinates and the size of a square. (if this can be done automated i love to hear it) I have seen one where someone should pinpoint the eyes. IF someone has experience with this or a general idea on what techniques to use let me know I bet there are loads of way to do this but the most light weight technique would be great. Something like the attached image i am in the process of creating an auction site. However the images do not show , just the placeholder. Can anyone indicate where I have gone wrong ?
i am using this script to enter the items into the Database
html>
<link rel="stylesheet" type="text/css" href="style.css">
if(isset($_GET["item"]))
if($_GET["item"]=="duplicate")
else if($_GET["item"]=="successful")
}
echo "<label for='item_name' class='label'>Item Name:</label>";
echo "</form>";
</body>
This script displays the items :
<html>
<link rel="stylesheet" type="text/css" href="style.css">
<body> session_start();
if(!isset($_SESSION["username"]))
else
$DBHOST = "localhost";
while($row = $result->fetch_assoc())
$iid = $row["item_id"];
$conn->close();
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 I have used the same method for uploading photos for ages but feel there may be a better way. For both methods, please assume all uploads are large digital camera uploads of a few megabytes and thousands of pixels wide (as you would expect from large digital camera images). CURRENT METHOD (1) receive uploaded file and use ImageMagick to convert to 4 file sizes, then store these file sizes (also set so ImageMagick reduces the quality to something like a setting of 80 out of 100 which will further reduce file size. - file sizes (widths): 800 240 120 60 (mobile phones etc.) (2) Based on the type of size and view required I then use <img src="/photos/240/file.jpg to display (240 being the required image size of course) POSSIBLE BETTER METHOD (1) Use ImageMagick to reduce to 800 wide as will never display bigger than this anyway, reduce quality also. But don't resize further and only need one file. (2) Use PHP commands to display an image, and set height/width/quality then. Eg: <img src="showImage.php?file=file.jpg&width=240&quality=60 So both would do the same thing but the second seems better as you don't need to create 4 images for every photo upload. Why make lots of thumbnails when you can make one and then get PHP to create at the time of display? Although I suppose if you regularly displayed these images in a search result then PHP would need to do that extra processing on every search. Creating all 4 at the time of upload only requires the one bit of processing. Have I just found the answer? Hai i got a site where i take the details of the visitors that enter my office premises. Now what i wanted is to add the photo of the visitor into that. i have a webcam with me through which i can take pictures. I dont have an idea how to do this on the website. I need some one to help me on this.. I dont know really where to start.. Any help would be greately appreciatd.. Hello, can you help me on my news article? I would like to be able to add photo on the article. Below is my codes Quote ======= html ======= <?php include_once ('post_news.php'); ?> <form Action="add_news.php" Method="post"> <input name="postdate" type="text" id="postdate"> <input name="title" type="text" id="title"> <textarea name="newstext" cols="60" rows="15" id="newstext"></textarea> <input type="submit" name="submit" value="Submit"> <input type="reset" name="reset" value="Reset"> </form> ============== php - post_news.php ============== <?php ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); if (isset ($_POST['submit'])) { require_once ('inc/dbConfig.php'); // Define the query. $query = "INSERT INTO news (id, postdate, title, newstext) VALUES (0,'{$_POST['postdate']}', '{$_POST['title']}','{$_POST['newstext']}')"; // Execute the query. if (@mysql_query ($query)) { print "<p>Data has been added.</p>"; } else { print "<p>Could add the entry because: <b>" . mysql_error() . "</b>. The query was $query.</p>"; } mysql_close(); } ?> ===== db structure ====== id int(10) unsigned NOT NULL auto_increment, postdate timestamp(14), title varchar(50) NOT NULL, newstext text NOT NULL, PRIMARY KEY (id), KEY postdate (postdate) Hope you guys can help me. Thanks! |