PHP - Random Image Name On Upload And Insert
Hi all, I have an issue with an image upload script. So far the script will upload the image to the server and rename it with a random 5 digit number on the end. I then INSERT this data into a table for sourcing the image later on. the only problem is that the data in the table is the image's original name not the new one. how do I get it to change that name too? Thanks.
Code: [Select] <?php $idir = "uploads/"; // Path To Images Directory if (isset ($_FILES['fupload'])){ //upload the image to tmp directory $url = $_FILES['fupload']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload']['type'] == "image/jpg" || $_FILES['fupload']['type'] == "image/jpeg" || $_FILES['fupload']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload']['tmp_name'], $idir. basename($_FILES['fupload']['name'], $file_ext).rand(10000 , 99999).$file_ext); // Move Image From Temporary Location To Perm } } error_reporting (E_ALL ^ E_NOTICE); $usr = "user"; $pwd = "pword"; $db = "db"; $host = "host"; # connect to database $cid = mysql_connect($host,$usr,$pwd); if (!$cid) { echo("ERROR: " . mysql_error() . "\n"); } if ($_POST['submit']) { $logo = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); $SQL = " INSERT INTO mhhire "; $SQL .= " (logo) VALUES "; $SQL .= " ('$logo') "; $result = mysql_db_query($db,$SQL,$cid); $last=mysql_insert_id(); if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n"); } header("location:thanks.php"); exit(); } ?> Similar TutorialsCode I'm using if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Successfully uploaded image!"; if (file_exists("img/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "img/" . $_FILES["file"]["name"]); echo "<a href='img/$filename'>Your File</a>; } } } else { echo "Invalid file"; } mysql_query("INSERT INTO $tbl (body, name, subject, ip, timestamp, img) VALUES ('$body', '$name', '$subject', '$ip', '$timestamp', '$imglink')"); mysql_query("INSERT INTO total (ip, subject, name, board) VALUES ('$ip','$subject','$name','$dfg')"); echo "<font color='red'><font size='15'><strong><center>Successfully posted to /$tbl/"; //print("<meta http-equiv='REFRESH' content='0;url=index.php?board=$tbl'>"); If I have the query on the top it runs, and the upload img doesn't && vice versa Okay, so I found this code on-line that uploads images via a form, inserts them in to MySQL and displays the images on the page. It works great! Problem is, I spent a long time hacking this script to make it work with my site just to realize it did not re-size the image after it uploaded (dumb me). I have found other code that do this but I really do not want to start over at this point and my level of expertise with PHP are a step below what I need to figure this out. I am attaching the "original" code. If anyone knows how to add the necessary lines of code to make every image re-size (reduce) itself. I would very much appreciate it. Thanks <?php $con=mysql_connect("localhost", "root", "rootwdp")or die("cannot connect"); mysql_select_db("student",$con)or die("cannot select DB"); if(isset($_POST['upload'])) { $img=$_FILES["image"]["name"]; foreach($img as $key => $value) { $name=$_FILES["image"]["name"][$key] ; $tname=$_FILES["image"]["tmp_name"][$key]; $size=$_FILES["image"]["size"][$key]; $oext=getExtention($name); $ext=strtolower($oext); $base_name=getBaseName($name); if($ext=="jpg" || $ext=="jpeg" || $ext=="bmp" || $ext=="gif"){ if($size< 1024*1024){ if(file_exists("upload/".$name)){ move_uploaded_file($tname,"upload/".$name); $result = 1; list($width,$height)=getimagesize("upload/".$name); $qry="select id from img where `img_base_name`='$base_name' and `img_ext`='$ext'"; $res=mysql_fetch_array(mysql_query($qry)); $id=$res['id']; $qry="UPDATE img SET `img_base_name`='$base_name' ,`img_ext`='$ext' ,`img_height`='$height' ,`img_width`='$width' ,`size`='$size' ,`img_status`='Y' where id=$id"; mysql_query($qry); echo "Image '$name' updated<br />"; } else{ move_uploaded_file($tname,"upload/".$name); $result = 1; list($width,$height)=getimagesize("upload/".$name); $qry="INSERT INTO `img`(`id` ,`img_base_name` ,`img_ext` ,`img_height` ,`img_width`, `size` ,`img_status`)VALUES (NULL , '$base_name', '$ext', '$height', '$width', '$size', 'Y');"; mysql_query($qry); echo "Image '$name' uploaded<br />"; } } else{ echo "Image size excedded.<br />File size should be less than 1Mb<br />"; } } else{ echo "Invalid file extention '.$oext'<br />"; } } } function getExtention($image_name){ return substr($image_name,strrpos($image_name,'.')+1); } function getBaseName($image_name){ return substr($image_name,0,strrpos($image_name,'.')); } ?> <!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> <script type="text/javascript"> function addItems() { var table1 = document.getElementById('tab1'); var newrow = document.createElement("tr"); var newcol = document.createElement("td"); var input = document.createElement("input"); input.type="file"; input.name="image[]"; newcol.appendChild(input); newrow.appendChild(newcol); table1.appendChild(newrow); } function remItems() { var table1 = document.getElementById('tab1'); var lastRow = table1.rows.length; if(lastRow>=2) table1.deleteRow(lastRow-1); } </script> <style type="text/css"> <a class="tooltip" and them url href="/http.www.anyurl.com" </a> a.tooltip:hover span{display:inline; position:absolute; border:2px solid #cccccc; background:#efefef; color:#333399;} a.tooltip span {display:none; padding:2px 3px; margin-left:8px; width:150px;} </style> </head> <body> <form method="post" action="" enctype="multipart/form-data"> <table align="center" border="0" id="tab1"> <tr> <td width="218" align="center"><input type="file" name="image[]" /></td> <td width="54" align="center"><img src="Button-Add-icon.png" alt="Add" style="cursor:pointer" onclick="addItems()" /></td> <td><img src="Button-Delete-icon.png" alt="Remove" style="cursor:pointer" onclick="remItems()" /></td> </tr> </table> <table align="center" border="0" id="tab2"> <tr><td align="center"><input type="submit" value="Upload" name="upload" /></td></tr> </table> </form> <table border="0" style="border:solid 1px #333; width:800px" align="center"><tr><td align="center"> <iframe style="display:none" name="if1" id="if1"></iframe> <? $qry="select * from img where img_status='Y' order by id"; $res=mysql_query($qry); $i=0; if(mysql_num_rows($res)){ ?> <div align="center"><ul style="width:650px; border: 0px"> <? while($fetch=mysql_fetch_array($res)){ $hratio=120/$fetch['img_height']; $wratio=120/$fetch['img_width']; $ratio=($hratio < $wratio) ? $hratio : $wratio; $hth=$fetch['img_height']*$ratio; $wth=$fetch['img_width']*$ratio; ?> <li style="width:120px; height:180px; border:0px solid #333;float:left;list-style:none outside none; padding-right:5px;"><img src="upload/<? echo $fetch['img_base_name'].'.'.$fetch['img_ext']; ?>" width="<? echo $wth; ?>" height="<? echo $hth; ?>" title="<? echo "image : ".$fetch['img_base_name'].".".$fetch['img_ext']; ?>" /><br /> <? if($i==0) $fp=fopen("fileInfo.txt",'w'); else $fp=fopen("fileInfo.txt",'a'); fwrite($fp,"Image : ".++$i ."\r\n"); fwrite($fp,"Name : ".$fetch['img_base_name'].".".$fetch['img_ext']."\r\n"); fwrite($fp,"width X height : ".$fetch['img_width']." X ".$fetch['img_height']."\r\n"); fwrite($fp,"Size : ".round($fetch['size']/1024,1)."Kb\r\n"); fwrite($fp,"____________________________________\r\n"); fclose($fp); echo $fetch['img_base_name'].".".$fetch['img_ext'].'<br />'; echo $fetch['img_width'].' X '; echo $fetch['img_height'].'<br />'; echo round($fetch['size']/1024,1) .'Kb'; ?> </li> <? }?> </ul> </div><? }?> </td></tr></table> </body> </html> files that upload during insert/submit form was gone , only files upload during the update remain , is the way query for update multiple files is wrong ? $targetDir1= "folder/pda-semakan/ic/"; if(isset($_FILES['ic'])){ $fileName1 = $_FILES['ic']['name']; $targetFilePath1 = $targetDir1 . $fileName1; //$main_tmp2 = $_FILES['ic']['tmp_name']; $move2 =move_uploaded_file($_FILES["ic"]["tmp_name"], $targetFilePath1); } $targetDir2= "folder/pda-semakan/sijil_lahir/"; if(isset($_FILES['sijilkelahiran'])){ $fileName2 = $_FILES['sijilkelahiran']['name']; $targetFilePath2 = $targetDir2 . $fileName2; $move3 =move_uploaded_file($_FILES["sijilkelahiran"]["tmp_name"], $targetFilePath2); } $targetDir3= "folder/pda-semakan/sijil_spm/"; if(isset($_FILES['sijilspm'])){ $fileName3 = $_FILES['sijilspm']['name']; $targetFilePath3 = $targetDir3 . $fileName3; $move4 =move_uploaded_file($_FILES["sijilspm"]["tmp_name"], $targetFilePath3); } $query1=("UPDATE semakan_dokumen set student_id='$noMatrik', email= '$stdEmail', surat_tawaran='$fileName', ic='$fileName1',sijil_lahir='$fileName2',sijil_spm= '$fileName3' where email= '$stdEmail'");
i have got this script which displays all folders within a folder but what i want to do now is get it to display a random picture for each of the folders that it is showing in the grid. i know how to display a random image using array_rand() but i don't know how i would implement it. Code: [Select] <form name="Gallery" method="post"> <?php $path = "gallery_files/gallery/"; $dir_handle = @opendir($path) or die("Unable to open folder"); echo "<table cellspacing='15'>"; echo "<tr>"; while (false !== ($folder = readdir($dir_handle))) { if($folder == "pictures.php") continue; if($folder == ".") continue; if($folder == "..") continue; echo ($x % 6 == 0) ? "</tr><tr>" : ""; echo "<td><a href='pictures/?folder=$folder'><img src='path/to/random/image' style='height:auto;width:110px;' alt='$folder'></a><br /><a href='pictures/?folder=$folder'>$folder</a></td>"; $x++; } echo "</tr>"; echo "</table>"; closedir($dir_handle); ?> </form> Hi, I'm a researcher (and complete coding noob), and am planning a longitudinal study that requires e-mail follow-up with subjects taking an initial survey. For purposes of ethics/anonymity due to sensitive survey data, I'd like the acquired e-mails to be saved uncoupled from the survey responses; this is simple to deal with, and I use a basic PHP e-mail form, which injects the email address in a table in MySQL in a different server than the one used for the survey. The issue is that the e-mails are saved in the MySQL database in order of injection, thus it is still theoretically possible for me to link the e-mails back to the survey responses (which have a time stamp that I cannot remove). Ideally I would like not to be able (at all) to link the e-mails to the survey responses, and one way to do that (since I don't save the e-mail injection timestamps in MySQL) might be to have the e-mails saved in MySQL in a random order. Not sure if this is possible, and not even sure if this would be via PHP or MySQL side of things. The server is on godaddy and uses Starfield interface for MySQL but I cannot find an option for random insert/saving of table items (emails). They are saved in order of injection. Any solution for this? Thanks, im doing smting basically wrong Code: [Select] <form action="" method="post"> <?php $x=1; $images = $_GET['images']; for( $i=0; $i<$images; $i++ ) { echo '<input name="ID" type="hidden" value="1234" /> <br> <input name="ImageURL['.$i.']" type="file" value=""/><br><br>'; } ?> <input name="submit" type="submit" /> <?php $con = mysql_connect("localhost","root","root"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_query("SET NAMES 'utf8'"); mysql_select_db("international", $con); if (isset($_POST['submit'])) for( $i=0; $i<$images; $i++ ) { $query=mysql_query("INSERT INTO images (ID,ImageURL) VALUES ('$_POST[ID]','$_POST[ImageURL]')"); exit; mysql_close($con); } ?></form> I want to use the following code to upload images to my server (below code works great) Code: [Select] <?php $rand = rand(1,99999999999999); $member_id = $_SESSION['SESS_MEMBER_ID']; if(isset($_FILES['uploaded']['name'])) { $target = "gallery/"; $allowed_filetypes = array('.jpg','.gif','.bmp','.png'); $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB) $fileName = basename($_FILES['uploaded']['name']); $target = $target . $fileName; $errors = array(); // Get the extension from the filename. $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Check if the filetype is allowed. if(in_array($ext,$allowed_filetypes)) { $errors[] = "The file you attempted to upload is not allowed."; } // Now check the filesize. if(filesize($_FILES['uploaded']['tmp_name']) > $max_filesize) { $errors[] = "The file you attempted to upload is too large."; } // Check if we can upload to the specified path. if(is_writable($target)) { $errors[] = "You cannot upload to the specified directory, please CHMOD it to 777."; } //Here we check that no validation errors have occured. if(count($errors)==0) { //Try to upload it. if(!move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { $errors[] = "Sorry, there was a problem uploading your file."; } } //If no errors show confirmation message if(count($errors)==0) { echo "<div class='notification success png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> The file {$fileName} has been uploaded<br>\n </div> </div>"; //echo "The file {$fileName} has been uploaded"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } else { //show error message echo "<div class='notification attention png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Sorry your file was not uploaded due to the following errors:<br>\n </div> </div>"; //echo "Sorry your file was not uploaded due to the following errors:<br>\n"; echo "<ul>\n"; foreach($errors as $error) { echo "<li>{$error}</li>\n"; } echo "</ul>\n"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } } else { //Show the form echo "Use the following form below to add a new image to your gallery;<br />\n"; echo "<form enctype='multipart/form-data' action='' method='POST'>\n"; echo "Please choose a file: <input name='uploaded' type='file' /><br />\n"; echo "<input type='submit' value='Upload' />\n"; echo "</form>\n"; //Echo Tests! echo "<br /><br />Random FileName: "; echo $rand; echo "<br />"; echo "member ID: #"; echo $member_id; } ?> i then want it to rename the files for example: "test.png" is uploaded and name changed to "92997863_321.png" (where first number is using my $rand then the "_" then second number is my $member_id) the script already got these pieces of information and also gets the file extension using the $ext code. can this be done, and can i also upload the new filename to my sql table? i need to upload files to a different folder dependint on option in form, make thumbnails, and store title and src for image and thumb in database table dependant on category. i think i'm pretty close, but there's still something wrong. Here is my upload form : Code: [Select] <form enctype="multipart/form-data" action="upload.php" method="POST"> Photo: <input type="file" name="photo"><br> Category: <select name="cat"> <option value="weddings">Weddings</option> <option value="music">Music</option> <option value="portraits">Portraits</option></select> Title: <input type="text" name="title"><br> <input type="submit" value="Upload photo"> </form> form processed by upload.php : Code: [Select] <?php require "db.php"; //Get form info $name=$_POST['name']; $title=$_POST['title']; $category=$_POST['cat']; $pic=($_FILES['photo']['name']); //set target dir source file width height $target = $cat."/"; $src = $target . basename( $_FILES['photo']['name']); $destination = $cat."/thumbs"; $thumbsrc = $destination . basename( $_FILES['photo']['name']); $width = 200; $height = 200; header("content-type: image/jpeg"); $src_img = imagecreatefromjpeg("$src"); $srcsize = getimagesize("$dest"); $dst_img = imagecreatetruecolor($width, $height); imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $width, $height, $srcsize[0], $srcsize[1]); imagejpeg($dst_img); //Unstert into db mysql_query("INSERT INTO `$category` VALUES ('$name', 'Stitle', '$src, $thumbsrc')") ; //move photo if(move_uploaded_file($_FILES['photo']['tmp_name'], $fulltarget)) { //Ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { //not ok echo "Sorry, there was a problem uploading your file."; } ?> call a script from main page Code: [Select] <div class="gallery"> <?php include "weddings/get.php" ?> </div> <div class="gallery"> <?php include "music/get.php" ?> </div> get.php displays links Code: [Select] <?php include "db.php"; $cat = weddings; $q = "SELECT id, title, src, thumbsrc FROM $cat"; $result = $mysqli->query($q) or die(mysqli_error($mysqli)); if ($result) { echo "<ul id='photos'> \n"; while ($row = $result->fetch_object()) { $title = $row->title; $src = $row->src; $thsrc = $row->thumbsrc; $id = $row->id; echo "<a href='$src' class="lightbox" rel="$cat" title="$name - $title"><img src='$thsrc' id='$id' alt='$name' /></a>": } echo "</ul>"; } ?> I think i'm going along the right sort of path, but i'm not sure. How can i edit just one image at on time with a multiple image upload form? I have the images being stored in a folder and the path being stored in MySQL. I also have the files being uploaded with a unique id. My issue is that I want to be able to pass the values of what is already in $name2 $name3 $name4 if I only want to edit $name1. I don't want to have to manually update the 4 images. Here is the PHP: Code: [Select] <?php require_once('storescripts/connect.php'); mysql_select_db($database_phpimage,$phpimage); $uploadDir = 'upload/'; if(isset($_POST['upload'])) { foreach ($_FILES as $file) { $fileName = $file['name']; $tmpName = $file['tmp_name']; $fileSize = $file['size']; $fileType = $file['type']; if ($fileName != ""){ $filePath = $uploadDir; $fileName = str_replace(" ", "_", $fileName); //Split the name into the base name and extension $pathInfo = pathinfo($fileName); $fileName_base = $pathInfo['fileName']; $fileName_ext = $pathInfo['extension']; //now we re-assemble the file name, sticking the output of uniqid into it //and keep doing this in a loop until we generate a name that //does not already exist (most likely we will get that first try) do { $fileName = $fileName_base . uniqid() . '.' . $fileName_ext; } while (file_exists($filePath.$fileName)); $file_names [] = $fileName; $result = move_uploaded_file($tmpName, $filePath.$fileName); } if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); } $fileinsert[] = $filePath; } } $mid = mysql_real_escape_string(trim($_POST['mid'])); $cat = mysql_real_escape_string(trim($_POST['cat'])); $item = mysql_real_escape_string(trim($_POST['item'])); $price = mysql_real_escape_string(trim($_POST['price'])); $about = mysql_real_escape_string(trim($_POST['about'])); $fields = array(); $values = array(); $updateVals = array(); for($i = 0; $i < 4; $i++) { $values[$i] = isset($file_names[$i]) ? mysql_real_escape_string($file_names[$i]) : ''; if($values[$i] != '') { $updateVals[] = 'name' . ($i + 1) . " = '{$values[$i]}'"; } } $updateNames = ''; if(count($updateVals)) { $updateNames = ", " . implode(', ', $updateVals); } $update = "INSERT INTO image (mid, cid, item, price, about, name1, name2, name3, name4) VALUES ('$mid', '$cat', '$item', '$price', '$about', '$values[0]', '$values[1]', '$values[2]', '$values[3]') ON DUPLICATE KEY UPDATE cid = '$cat', item = '$item', price = '$price', about = '$about' $updateNames"; $result = mysql_query($update) or die (mysql_error()); Hello I am having problems uploading an image through a HTML form. I want the image to be uploaded to the server and the image name to be written to the mysql database. Below is the code I am using: Code: [Select] <?php if (isset($_POST['add'])){ echo "<br /> add value is true"; $name = $_POST['name']; $description = $_POST['description']; $price = $_POST['price']; $category_id = $_POST['category_name']; $image = $_FILES['image']['name']; //file path of the image upload $filepath = "../images/"; //mew name for the image upload $newimagename = $name; //new width for the image $newwidth = 100; //new height for the image $newheight = 100; include('../includes/image-upload.php'); mysql_query("INSERT INTO item (item_name, item_description, item_price, item_image) VALUES ('$name','$description','$price','$image')"); ?> Here is the image-upload.php file code: Code: [Select] <?php //assigns the file to the image $image =$_FILES["image"]["name"]; $uploadedfile =$_FILES["image"]["tmp_name"]; if ($image) { //retrieves the extension type from image upload $extension = getextension($image); //converts extension to lowercase $extension = strtolower($extension); //create image from uploaded file type if($extension=="jpg" || $extension=="jpeg") { $uploadedfile = $_FILES['image']['tmp_name']; $src = imagecreatefromjpeg($uploadedfile); }else if($extension=="png") { $uploadedfile = $_FILES['image']['tmp_name']; $src = imagecreatefrompng($uploadedfile); }else{ $src = imagecreatefromgif($uploadedfile); } //creates a list of the width and height of the image list($width,$height)=getimagesize($uploadedfile); //adds color to the image $tmp = imagecreatetruecolor($newwidth,$newheight); //create image imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); //set file name $filename = $filepath.$newimagename.".".$extension; $imagename = $newimagename.".".$extension; //uploads new file with name to the chosen directory imagejpeg($tmp,$filename,100); //empty variables imagedestroy($src); imagedestroy($tmp); } ?> Any help would be appreciated, fairly new to all this! Thanks!!! I have a working image upload script that uploads, renames the file and adds filename to the database. is it possible to include some sort of image resize code? if so can anyone point me in the right direction or better still show some example code and explain how it works etc. below is my working code: Code: [Select] <?php $rand = mt_rand(1,9999999); $member_id = $_SESSION['SESS_MEMBER_ID']; $caption = $_POST["caption"]; if(isset($_FILES['uploaded']['name'])) { $allowed_filetypes = array('.jpg','.gif','.bmp','.png','.jpeg'); $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB) $fileName = basename($_FILES['uploaded']['name']); $errors = array(); $target = "gallery/"; $fileBaseName = substr($fileName, 0, strripos($fileName, '.')); // Get the extension from the filename. $ext = substr($fileName, strpos($fileName,'.'), strlen($fileName)-1); //$newFileName = md5($fileBaseName) . $ext; $newFileName = $target . $rand . "_" . $member_id.$ext; // Check if filename already exists if(file_exists("gallery/" . $newFileName)) { $errors[] = "The file you attempted to upload already exists, please try again."; } // Check if the filetype is allowed. if(!in_array($ext,$allowed_filetypes)) { $errors[] = "The file you attempted to upload is not allowed."; } // Now check the filesize. if(!filesize($_FILES['uploaded']['tmp_name']) > $max_filesize) { $errors[] = "The file you attempted to upload is too large."; } // Check if we can upload to the specified path. if(!is_writable($target)) { $errors[] = "You cannot upload to the specified directory, please CHMOD it to 777."; } //Here we check that no validation errors have occured. if(count($errors)==0) { //Try to upload it. if(!move_uploaded_file($_FILES['uploaded']['tmp_name'], $newFileName)) { $errors[] = "Sorry, there was a problem uploading your file."; } } //Lets INSERT database information here if(count($errors)==0) { $result = mysql_query("INSERT INTO `gallery` (`image`, `memberid`, `caption`) VALUES ('$newFileName', '$member_id', '$caption')") or die (mysql_error()); } //If no errors show confirmation message if(count($errors)==0) { echo "<div class='notification success png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Image has been uploaded.<br>\n </div> </div>"; //echo "The file {$fileName} has been uploaded"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } else { //show error message echo "<div class='notification attention png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Sorry your file was not uploaded due to the following errors:<br>\n </div> </div>"; //echo "Sorry your file was not uploaded due to the following errors:<br>\n"; echo "<ul>\n"; foreach($errors as $error) { echo "<li>{$error}</li>\n"; } echo "</ul>\n"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } } else { //Show the form echo "Use the following form below to add a new image to your gallery;<br /><br />\n"; echo "<form enctype='multipart/form-data' action='' method='POST'>\n"; echo "Please choose a file:<br /><input class='text' name='uploaded' type='file' /><br />\n"; echo "Image Caption:<br /><input class='text' name='caption' type='text' value='' /><br /><br />\n"; echo "<input class='Button' type='submit' value='Upload' />\n"; echo "</form>\n"; } ?> Many thanks to phpfreaks again. hello friends, while clicking the form all the information goes to database, I have one image upload field, when cliking the submit button, i would like 'image name' to go in database and file to go in /upload folder, i have tried this for hours and gave up, if anyone help me in this, i would be very greatful Hi Everyone, I was wondering if anyone could help me make this code I wrote better and a bit more readable and shorter. I have 8 images on the home page so the php code is like this: Code: [Select] <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage1 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage2 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage3 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage4 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage5 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage6 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage7 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage8 = "_images/showreel/{$images[$i]}.jpg"; ?> And the HTML is like this: Code: [Select] <div id="slider1" class="nivoSlider"> <img src="<?php echo $selectedImage1; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage2; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage3; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage4; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage5; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage6; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage7; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage8; ?>" alt="John Richard Cleckheaton West Yorkshire" /> </div> I no this code is terrible but I am still learning. Just a few months ago I had never touched PHP. Any help would be greatly appreciated. Regards Barry The purpose of this function is to go to the characters table and grab all of the characters that have a statusID of one however I want it to limit it to any ONE of those characters as this is a random image it's going to show and then I want it to have that charactes shortName and then use it to find their spotlight image from inside of the images/spotlight folder. All its showing right now in its spot is the the filename of the image when I call this function. function spotlight(){ $query = "SELECT * FROM characters WHERE characters.statusID = 1 LIMIT 1"; $result = mysql_query($query); $row = mysql_fetch_assoc($result); $labels = array('shortName'); $img = array(); if($handle = opendir('images/spotlight/')) { $count = 0; while (false !== ($file = readdir($handle))) { if(strlen($file) > 2){ $img[$count] = $file; $count++; } } } echo $img[rand(0, (count($img)-1))]; } Im Am Trying To Display A Random Image Every Time The Page Refreshs i dont know if this will help??? <?php /* User Pets (user_pets.php) */ $rank_check = 1; $page_title = "User Pets"; include "header.inc.php"; print $openHTML; $array = fetch("SELECT * FROM user_pets2 WHERE id = '$id' AND game = '$game'"); if (!$array[id]) { die("<p align=center class=error>That is not a real pet</p>$closeHTML"); } if ($array[pet_desc]) { $petNote = "<tr><td colspan=2><p align=center><font size=-1><i>$array[pet_desc]</i></font></p></td></tr>"; } print "<center><table>$petNote<tr> <td width=200> "; $id = $array[id]; $getPet = fetch("SELECT * FROM pets2 WHERE id = '$array[species]' AND game = '$game'"); $getOwner = fetch("SELECT display_name,username FROM members2 WHERE id = '$array[owner]' AND game = '$game'"); $image = "pet_$getPet[id]"; if ($array[wearing] != 0) { $findLook = fetch("SELECT * FROM pet_looks WHERE change_from = '$array[species]' AND item_name = '$array[wearing]'"); if ($findLook[id]) { $image = "pet2_$findLook[id]"; } } $hunger = $array[$hunger]; $hungerLevel = $hungerArray[$hunger]; if (($array[hunger] > 10) OR ($array[hunger] < 0)) { $hungerLevel = "Unknown ($array[hunger])"; } $percentHealth = ($array[current_hp] / $array[max_hp]) * 100; if ($percentHealth > 0) { $healthLine = "<font color=red>$array[current_hp]/$array[max_hp]</font>"; } if ($percentHealth > 35) { $healthLine = "<font color=orange>$array[current_hp]/$array[max_hp]</font>"; } if ($percentHealth > 75) { $healthLine = "<font color=green>$array[current_hp]/$array[max_hp]</font>"; } ECHO <<<END <br> <CENTER><TABLE BGCOLOR="#$tableOutline" CELLSPACING=1 CELLPADDING=0 WIDTH=400> <tr> <td colspan=2 bgcolor=#$topAndBottomBG><font color=#$topAndBottomText><b>View Pet:</b></font></td></tr> <TR> <TD BGCOLOR=#$middleBG> <p> <font size=-1> Name: $array[name]<br> Level: $array[level]<br> Experience: $array[experience]<br> Next Level: $nextLevel[$id]<br> Health: <b>$healthLine</b><br> Strength: $array[strength]<br> Intelligence: $array[intelligence]<br> Speed: $array[speed]<br> Defense: $array[defense]<br> Hunger: $hungerLevel<Br> </font> </p> <p> <font size=-1> 1-Player Wins: $array[one_p_wins]<br> 1-Player Loses: $array[one_p_loses] </font> </p> </TD> <TD WIDTH=175 BGCOLOR=#FFFFFF> <p align=center> <img src=$base_url/images/user_images/opg_$game/pets/$image.gif border=1> <br><a href=view_pet.php?id=$array[id]&game=$game><b>$array[name]</b> the $getPet[name]!$petNote[$id]</a></P> <p align=center>$attitude[$id]</p> </TD> </TR> </TABLE> </CENTER> <p align=center><a href=user_profile.php?game=$game&user=$getOwner[username]>Back to $getOwner[display_name]'s Profile!</a></p> END; print "$closeHTML"; ?> Please Help Me Jackthumper This is going to be tricky for everyone but here is goes. I have a random image function however I want the image attatched to a link that will go to the person's bio page. Even if I query anything how can I make sure that it matches up with what the right link person. <a href="bio/".$shortname.""><img src="images/spotlight/<?php randlogo(); ?>" alt=".::Spotlight A KOW Superstar::." /></a> <?php function randlogo(){ $img = array(); if($handle = opendir('images/spotlight/')) { $count = 0; while (false !== ($file = readdir($handle))) { if(strlen($file) > 2){ $img[$count] = $file; $count++; } } } echo $img[rand(0, (count($img)-1))]; } ?> Hey guys, i've made a script to display a random image. Works perfect on firefox, ie but not chrome =/. Rotate.php <?php // rotate images randomly but w/o dups on same page - format: // <img src='rotate.php?i=0'> - rotate image #0 - use 'i=1' // for second, etc // (c) 2004 David Pankhurst - use freely, but please leave in my credit $images=array( // list of files to rotate - add as needed "images/1.jpg", "images/2.jpg", "images/3.jpg", "images/4.jpg", "images/5.jpg", "images/6.jpg", "images/7.jpg", "images/8.jpg", "images/9.jpg" ); $total=count($images); $secondsFixed=2; // seconds to keep list the same $seedValue=(int)(time()/$secondsFixed); srand($seedValue); for ($i=0;$i<$total;++$i) // shuffle list 'randomly' { $r=rand(0,$total-1); $temp =$images[$i]; $images[$i]=$images[$r]; $images[$r]=$temp; } $index=(int)($_GET['i']); // image index passed in $i=$index%$total; // make sure index always in bounds $file=$images[$i]; header ("Location: $file"); header ("Content-Length: 0"); exit; ?> and then to call it, script.php <img src='rotate.php?i=0' width="90%" height="90%" alt="" /> How would i do a random file name for my upload script Code: [Select] $type = $_FILES['uploadedfile']['type']; // Where the file is going to be placed $target_path ="/***/***/public_html/****/lofslidernews/images/"; /* Add the original filename to our target path. Result is "/images/uploads/filename.extension" */ $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); $uploadedfile2 = $_FILES['uploadedfile']['name']; if (empty($quicktitle) || empty($maintitle ) || empty($description ) || empty($uploadedfile)) { $_SESSION["promoerror"] = "Please Select an image and enter a Quick Title, Main Title and Description!" ; header("Location: promo.php"); //This sets the redirection information //echo "Going to login.php, username or password is empty"; exit(); //Ends the script and redirects to above } $query = "INSERT INTO promotion (title, maintitle, description, image) VALUES ('$quicktitle','$maintitle','$description', '$uploadedfile2')"; $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); if ( ( $type != "image/jpeg") && ($type != "image/gif") ) { die ("That format is not allowed"); } else { move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path); header("Location: promo.php"); $_SESSION["promoerror"] = "Added Successfully!"; } I need code for upload images for php as well as to edit that image
Hi, Im rather new to php and really unable to get the above to work. Everything works apart from the image being resized. File is uploaded, and the image name is printed into the SQL database. But i cant for the life of me get the image to go to 300x200? If you could help me i would be very grateful My code for the form processing page is attached. Ive put a few line breaks into the code as to where i think is the issue. I just cant seem to resize the image. Does the image resize need to come before the part it writes the image to the server or can this be done afterwards? Please help. P.S - Thanks in advance |