PHP - Need A Display Image Script That Works For This Insert Image Script
Well the subject line is pretty explicit. I found this script that uploads a picture onto a folder on the server called images, then inserts the the path of the image on the images folder onto a VACHAR field in a database table.
Code: [Select] <?php //This file inserts the main image into the images table. //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //Check whether the session variable id is present or not. If not, deny access. if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) { header("location: access_denied.php"); exit(); } else{ // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that's easy to read // I used this function during debugging but it serves no purpose at run time for this example function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } // Set some constants // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "images/"; // Get our POSTed variable $image = $_FILES['image']; // Sanitize our input $image['name'] = mysql_real_escape_string($image['name']); // Build our target path full string. This is where the file will be moved to // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Make sure all the fields from the form have inputs if ( $image['name'] == "" ) { $_SESSION['error'] = "All fields are required"; header("Location: member.php"); exit; } // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header("Location: member.php"); exit; } // Here we check to see if a file with that name already exists // You could get past filename problems by appending a timestamp to the filename and then continuing if (file_exists($TARGET_PATH)) { $_SESSION['error'] = "A file with that name already exists"; header("Location: member.php"); exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into images (member_id, image_cartegory, image_date, image) values ('{$_SESSION['id']}', 'main', NOW(), '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: images.php"); echo "File uploaded"; exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: member.php"); exit; } } //End of if session variable id is not present. ?> The script seems to work fine because I managed to upload a picture which was successfully inserted into my images folder and into the database. Now the problem is, I can't figure out exactly how to write the script that displays the image on an html page. I used the following script which didn't work. Code: [Select] //authenticate user //Start session session_start(); //Connect to database require ('config.php'); $sql = mysql_query("SELECT* FROM images WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main' "); $row = mysql_fetch_assoc($sql); $imagebytes = $row['image']; header("Content-type: image/jpeg"); print $imagebytes; Seems to me like I need to alter some variables to match the variables used in the insert script, just can't figure out which. Can anyone help?? Similar TutorialsSo this script did work in previous versions oh php but in php5 I get the error, "Sorry, uploaded images must be of type jpg or jpeg, (not )." So it looks like it's not recognizing my file as a jpeg?? Any contributions towards a fix are GREATLY appreciated!!! If there are clean, nice (EASY) php5 scripts available for this simple image uploading and thumbnail creation I would consider starting this over. //Listing page code: echo "<form name=\"addCat\" enctype=\"multipart/form-data\" action=\"preview.php\" method=\"post\">"; <INPUT type="file" name="pic1" size="50" value=""> <INPUT type="file" name="pic2" size="50" value=""> <INPUT type="file" name="pic3" size="50" value=""> <INPUT type="file" name="pic4" size="50" value=""> <input type="submit" value="Upload Images"> //preview.php page code: $pic1 = $_FILES['pic1']; $pic2 = $_FILES['pic2']; $pic3 = $_FILES['pic3']; $pic4 = $_FILES['pic4']; function ResizeImage($im,$maxwidth,$maxheight,$name){ $width = imagesx($im); $height = imagesy($im); if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){ if($maxwidth && $width > $maxwidth){ $widthratio = $maxwidth/$width; $RESIZEWIDTH=true; } if($maxheight && $height > $maxheight){ $heightratio = $maxheight/$height; $RESIZEHEIGHT=true; } if($RESIZEWIDTH && $RESIZEHEIGHT){ if($widthratio < $heightratio){ $ratio = $widthratio; }else{ $ratio = $heightratio; } }elseif($RESIZEWIDTH){ $ratio = $widthratio; }elseif($RESIZEHEIGHT){ $ratio = $heightratio; } $newwidth = $width * $ratio; $newheight = $height * $ratio; if(function_exists("imagecopyresampled")){ $newim = imagecreatetruecolor($newwidth, $newheight); imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); }else{ $newim = imagecreate($newwidth, $newheight); imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); } ImageJpeg (($newim),$name . ".jpg"); ImageDestroy ($newim); }else{ ImageJpeg ($im,$name . ".jpg"); } } // Set up some variables flush(); set_time_limit(210); // set process page limit to 3.5 minutes $maxfilesize = "102400"; //# individual file size limit - in bytes (102400 bytes = 100KB) $path="2012images"; $thumbpath="thumbs"; // two data pulls to rename images - would be easier to have a permanent counter...fix later $mysql[getpicname] = mysql_query("select pic from picname"); $z = mysql_fetch_array($mysql[getpicname]); $new_filename=$z[pic]; $new_z[pic]=$z[pic]+$total_pics; if(@mysql_query("UPDATE picname SET pic = '$new_z[pic]' ")) echo ""; // Create thumbnail from imgurl and store in thumbs // Height to reszie image to (in pixels) $RESIZEHEIGHT=200; // Width to reszie image to (in pixels) $RESIZEWIDTH=200; //thumbnail to thumbs folder, named same as 1st image $FILENAME=$thumbpath."/".$new_filename; $thumb_name=$thumbpath."/".$new_filename.".jpg"; // create a thumbnail from the first image only $im = imagecreatefromjpeg($_FILES['pic1']['tmp_name']); if($im) { if(file_exists("$pic_1.jpg")) { unlink("$pic_1.jpg"); } if (ResizeImage($im,$RESIZEWIDTH,$RESIZEHEIGHT,$FILENAME)) ImageDestroy ($im); } //now upload the images..... for ($i=1;$i<5;$i++) { //check if blank or image $xpic="pic".$i; if (($$xpic<>"none") and ($$xpic<>"")) { // check if jpg $cert1 = "image/pjpeg"; //jpg $cert2 = "image/jpeg"; //jpg (for MAC) $xtype =$HTTP_POST_FILES[$xpic]['type']; $xsize =$HTTP_POST_FILES[$xpic]['size']; if (($xtype <> $cert1) AND ($xtype <> $cert2)) { echo "<DIV class=\"errorsubheading\"><br><br>Alert - Missing or Invalid Information</DIV><br>"; echo "<DIV class=\"requiredtext\">Sorry, uploaded images must be of type jpg or jpeg, (not $xtype).</DIV><BR>"; echo "<BR><br><br>"; include ("footer.php"); exit(); } if ($xsize > $maxfilesize) { echo "<DIV class=\"errorsubheading\"><br><br>Alert - Missing or Invalid Information</DIV><br>"; echo "<DIV class=\"requiredtext\">Sorry, uploaded images must be under the maximum size requirements.</DIV><BR>"; echo "<BR><br><br>"; include ("footer.php"); exit(); } else { // upload to server $dest=$path."/".$new_filename.".jpg"; If (move_uploaded_file($$xpic, $dest)) { $photo[$i]=$dest; $new_filename+=1; } else { echo "<DIV class=\"errorsubheading\"><br><br>Alert - Upload Failed!</DIV><br>"; echo "<BR><br><br>"; include ("footer.php"); exit(); } // upload sucessful } // end type check } // end check if blank } I had posted a similar post a few days back, about an display script which is supposed to retrieve a stored image from my database and displays it on an html page, but fails to do so. Someone suggested that I upload my image onto a folder on the server and then save the image path name in my database. I found this script(below) which does just that. It uploads the image into a folder on the server called images and stores the image path into a table in my database called images and I know this script works because i saw the file saved in the images folder and the path name inserted into the images table. Code: [Select] <?php //This file inserts the main image into the images table. //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //Check whether the session variable id is present or not. If not, deny access. if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) { header("location: access_denied.php"); exit(); } else{ // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that's easy to read // I used this function during debugging but it serves no purpose at run time for this example function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } // Set some constants // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "images/"; // Get our POSTed variable $image = $_FILES['image']; // Sanitize our input $image['name'] = mysql_real_escape_string($image['name']); // Build our target path full string. This is where the file will be moved to // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Make sure all the fields from the form have inputs if ( $image['name'] == "" ) { $_SESSION['error'] = "All fields are required"; header("Location: member.php"); exit; } // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header("Location: member.php"); exit; } // Here we check to see if a file with that name already exists // You could get past filename problems by appending a timestamp to the filename and then continuing if (file_exists($TARGET_PATH)) { $_SESSION['error'] = "A file with that name already exists"; header("Location: member.php"); exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into images (member_id, image_cartegory, image_date, image) values ('{$_SESSION['id']}', 'main', NOW(), '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: images.php"); echo "File uploaded"; exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: member.php"); exit; } } //End of if session variable id is not present. ?> Now the display image script accompanying this insert image script is shown below. Code: [Select] <?php // Get our database connector require("config.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Dream in code tutorial - List of Images</title> </head> <body> <div> <?php // Grab the data from our people table $sql = "SELECT * from images WHERE image_cartegory = 'main'"; $result = mysql_query($sql) or die ("Could not access DB: " . mysql_error()); while ($row = mysql_fetch_assoc($result)) { echo "<div class=\"picture\">"; echo "<p>"; // Note that we are building our src string using the filename from the database echo "<img src=\"images/ " . $row['filename'] . " \" alt=\"\" />"; echo "</p>"; echo "</div>"; } ?> </div> </body> </html> Well, needless mentioning, the picture isn't displayed. Just a tiny jpeg icon is displayed at the top left hand corner of the page. Figuring out that the problem might be the lack of a header that declares the image type, I add this line header("Content-type: image/jpeg"); but all it does is display a blank white page, without the tiny icon this time. What am I missing? Any clues?? I came up with the following script for displaying an uploaded picture on a webpage but for some reason I can't pinpoint, the picture won't be displayed. I checked my database from php myadmin and sure enough, the picture was successfully uploaded but somehow, the picture won't be displayed. So here is the display script. I named it display_pic.php Code: [Select] <?php //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //include the config file require('config.php'); $image = stripslashes($_REQUEST[imname]); $rs = mysql_query("SELECT* FROM images WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main' "); $row = mysql_fetch_assoc($rs); $imagebytes = $row[image]; header("Content-type: image/jpeg"); print $imagebytes; ?> The tag on the html page that's supposed to display the picture reads something like this <img src="display_pic.php" width="140" height="140"> And just in case this might help, I will include the image upload script below, which I think worked just fine because my values were successfully inserted into the database. Code: [Select] <?php //This file inserts the main image into the images table. //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //Check whether the session variable id is present or not. If not, deny access. if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) { header("location: access_denied.php"); exit(); } else{ // Make sure the user actually // selected and uploaded a file if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { // Temporary file name stored on the server $tmpName = $_FILES['image']['tmp_name']; // Read the file $fp = fopen($tmpName, 'r'); $data = fread($fp, filesize($tmpName)); $data = addslashes($data); fclose($fp); // Create the query and insert // into our database. $query = "INSERT INTO images (member_id, image_cartegory, image_date, image) VALUES ('{$_SESSION['id']}', 'main', NOW(), '$data')"; $results = mysql_query($query); // Print results print "Thank you, your file has been uploaded."; } else { print "No image selected/uploaded"; } // Close our MySQL Link mysql_close(); } //End of if statmemnt. ?> So any insights as to why the script fails to display the image? Any help is appreciated. Hi, I am planning to display remote images with the following code but it seems to return errors. <?php $image_dir = 'http://www.domain.com/images/' ; $dir_handle = opendir( $image_dir ); $count = 0 ; $display = '' ; while( $filename = readdir($dir_handle)){ if( preg_match( '/$[a-z0-9]{4}_th\.jpg$/' , $filename ) ){ $display .= " <img src='$image_dir$filename' /> " ; $count++ ; if( $count % 10 == 0 ){ $count=0; $display .= "<br />"; } } } closedir( $dir_handle ); echo $display ; ?> I am thinking might be the $image_dir cannot use address format.... Errors is as follow Quote Warning: opendir(http://www.foo.com/images/) [function.opendir]: failed to open dir: not implemented in /home/jch02140/public_html/test.php on line 3 Warning: readdir(): supplied argument is not a valid Directory resource in /home/jch02140/public_html/test.php on line 6 Warning: closedir(): supplied argument is not a valid Directory resource in /home/jch02140/public_html/test.php on line 16 Hi i have this upload script which works fine it uploads image to a specified folder and sends the the details to the database. but now i am trying to instead make a modify script which is Update set so i tried to change insert to update but didnt work can someone help me out please this my insert image script which works fine but want to change to modify instead Code: [Select] <?php mysql_connect("localhost", "root", "") or die(mysql_error()) ; mysql_select_db("upload") or die(mysql_error()) ; // my file the name of the input area on the form type is the extension of the file //echo $_FILES["myfile"]["type"]; //myfile is the name of the input area on the form $name = $_FILES["image"] ["name"]; // name of the file $type = $_FILES["image"]["type"]; //type of the file $size = $_FILES["image"]["size"]; //the size of the file $temp = $_FILES["image"]["tmp_name"];//temporary file location when click upload it temporary stores on the computer and gives it a temporary name $error =array(); // this an empty array where you can then call on all of the error messages $allowed_exts = array('jpg', 'jpeg', 'png', 'gif'); // array with the following extension name values $image_type = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif'); // array with the following image type values $location = 'images/'; //location of the file or directory where the file will be stored $appendic_name = "news".$name;//this append the word [news] before the name so the image would be news[nameofimage].gif // substr counts the number of carachters and then you the specify how how many you letters you want to cut off from the beginning of the word example drivers.jpg it would cut off dri, and would display vers.jpg //echo $extension = substr($name, 3); //using both substr and strpos, strpos it will delete anything before the dot in this case it finds the dot on the $name file deletes and + 1 says read after the last letter you delete because you want to display the letters after the dot. if remove the +1 it will display .gif which what we want is just gif $extension = strtolower(substr($name, strpos ($name, '.') +1));//strlower turn the extension non capital in case extension is capital example JPG will strtolower will make jpg // another way of doing is with explode // $image_ext strtolower(end(explode('.',$name))); will explode from where you want in this case from the dot adn end will display from the end after the explode $myfile = $_POST["myfile"]; if (isset($image)) // if you choose a file name do the if bellow { // if extension is not equal to any of the variables in the array $allowed_exts error appears if(in_array($extension, $allowed_exts) === false ) { $error[] = 'Extension not allowed! gif, jpg, jpeg, png only<br />'; // if no errror read next if line } // if file type is not equal to any of the variables in array $image_type error appears if(in_array($type, $image_type) === false) { $error[] = 'Type of file not allowed! only images allowed<br />'; } // if file bigger than the number bellow error message if($size > 2097152) { $error[] = 'File size must be under 2MB!'; } // check if folder exist in the server if(!file_exists ($location)) { $error[] = 'No directory ' . $location. ' on the server Please create a folder ' .$location; } } // if no error found do the move upload function if (empty($error)){ if (move_uploaded_file($temp, $location .$appendic_name)) { // insert data into database first are the field name teh values are the variables you want to insert into those fields appendic is the new name of the image mysql_query("INSERT INTO image (myfile ,image) VALUES ('$myfile', '$appendic_name')") ; exit(); } } else { foreach ($error as $error) { echo $error; } } //echo $type; ?> hello i have this php code to show the last image upload in a folder and the result is this http://theplattan.com/screenlive2/Screenshooter2.php this code must be in the same image folder to work. I need add a php code from my joomla website but i dont know where i can change the path image folder on this script. i have tried by my self to change rad 33 $files = dirList('.'); to $files = dirList('screenlive2'); but this show only the list and not the image, somebody have any idea? Code: [Select] 1: <html> 2: <head> 3: <style type="text/css"> 4: #files { float: left; font-size: small; } 5: #image { float: right; } 6: .links { float: right; left: -40px; position: relative; } 7: .selected { font-weight: bold; } 8: </style> 9: </head> 10: <body> 11: 12: <?php 13: 14: function dirList ($directory) 15: { 16: $results = array(); 17: $handler = opendir($directory); 18: while ($file = readdir($handler)) { 19: if ($file != '.' && $file != '..') 20: { 21: $suffix = "gif"; 22: 23: if( substr($file, -3) == $suffix ) 24: { 25: $results[] = $file; 26: } 27: } 28: } 29: closedir($handler); 30: return $results; 31: } 32: 33: $files = dirList('.'); 34: 35: arsort($files); 36: 37: //$files = array_reverse( $files ); 38: 39: echo "<div id='files'><ul>"; 40: 41: $prev = ""; 42: $next = ""; 43: $last = ""; 44: 45: foreach( $files as $entry ) 46: { 47: if( isset($_GET['sel']) == false ) 48: { 49: $_GET['sel'] = $entry; 50: } 51: 52: $style = ""; 53: 54: if( $_GET['sel'] == $entry ) 55: { 56: $style="selected"; 57: $selected = $entry; 58: $prev = $last; 59: } 60: 61: echo "<li class='".$style."'><a href='i.php?sel=".$entry."'>"; 62: print_r( $entry ); 63: echo "</a></li>"; 64: 65: if( ($last == $selected) && ($last != "") ) 66: { 67: $next = $entry; 68: } 69: 70: $last = $entry; 71: } 72: 73: echo "</ul></div>"; 74: 75: echo "<div id='image'><img src='".$selected."' alt=''/></div>"; 76: 77: echo "<p class='links'>"; 78: 79: if( $prev != "" ) echo "<a href='i.php?sel=".$prev."'>Up</a>"; 80: echo "<br/>"; 81: if( $next != "" ) echo "<a href='i.php?sel=".$next."'>Down</a>"; 82: 83: echo "</p>"; 84: 85: ?> 86: 87: </body> 88: </html> Hi Guys, I am trying to disguise my php script as a .gif file for the purposes of a shopping cart. Basically, you click on the .gif which is placed on the page and it takes you to an image unless it has variables attached to it. Google use this for their checkout so I know this is possible. Does anyone have any ideas how I would go about doing this? Thanks in advance, Jacob. I have 23 products in a db, all with a unique ID that Im creating a user site for. Some of the items have 1 or 2 images and others have as many as 30 images. In my db I have a field called "pics". All the images are saved as a .jpg, according to their id on the server. So if item 1 has 10 images the files a "1_001.jpg," "1_002.jpg," ect. How do I create a script that will display the correct amount of images based on the number in the db. I was going to do something like this: Code: [Select] if ($row['pics'] =="1") { $pictures = '<img src="pictures/'.$id.'_001.jpg" width="200" alt="" />'; } elseif ($row['pics'] =="2") { $pictures = '<img src="pictures/'.$id.'_001.jpg" width="200" alt="" /><img src="pictures/'.$id.'_002.jpg" width="200" alt="" />'; } elseif ($row['pics'] =="3") { $pictures = '<img src="pictures/'.$id.'_001.jpg" width="200" alt="" /><img src="pictures/'.$id.'_002.jpg" width="200" alt="" /><img src="pictures/'.$id.'_003.jpg" width="200" alt="" />'; } but that would just be retarded... Thank you! If I upload this script in /www/ads/insert/image/ it works fine If I upload it in /www/ads/insert/ it does not work It says PHP could not open /new/ to upload image Code: [Select] <? $target_path = 'images/new/'; $image_name = 'myself.gif'; if( imagejpeg( $tmp_img, "{$target_path}{$image_name}" ) ){ print"image uploaded!"; } ?> I think because PHP only allows to upload images 1 folder deep!!! Why? How do I solve this? I want to create different folders for each group of images ok i have a image uploading script here, it works fine but theres one thing im unhappy with when i first downloaded it it had 1 working one, and the rest examples which you basically have to put together yourself with the sample code (doesen't work without adding missing coding), i have done all that then i took the time to add a random string prefix, im new at php so it took me awhile to work out which strings would work in the right area. now this is what i need help with, when it uploads it has two options, download and remove, these both work fine, but on the file uploader that does work it has "file uploaded to "http://site.com/image.png" the example of course did not work (had loading bar working, and etc but didn't upload or have the feature i just mentioned) and the coder of the script used javascript and inner html for the file uploaded.... etc, because it uploads without refreshing, only thing is i cant seem to get it to work with the new random string i put in, i tried to recreate one with the same type of thing they used for the filename but it didn't work well here is the code, hope you can help. image upload handler Code: [Select] <?php require_once "phpuploader/include_phpuploader.php" ?> <?php $uploader=new PhpUploader(); if(@$_GET["download"]) { $fileguid=$_GET["download"]; $mvcfile=$uploader->GetUploadedFile($fileguid); header("Content-Type: application/oct-stream"); header("Content-Disposition: attachment; filename=\"" . $mvcfile->FileName . "\""); readfile($mvcfile->FilePath); } if(@$_POST["delete"]) { $fileguid=$_POST["delete"]; $mvcfile=$uploader->GetUploadedFile($fileguid); unlink($mvcfile->FilePath); echo("OK"); } if(@$_POST["guidlist"]) { $guidarray=explode("/",$_POST["guidlist"]); //OUTPUT JSON echo("["); $count=0; foreach($guidarray as $fileguid) { $mvcfile=$uploader->GetUploadedFile($fileguid); if(!$mvcfile) continue; //process the file here , move to some where //rename(...) if($count>0) echo(","); echo("{"); echo("FileGuid:'");echo($mvcfile->FileGuid);echo("'"); echo(","); echo("FileSize:'");echo($mvcfile->FileSize);echo("'"); echo(","); echo("FileName:'");echo($mvcfile->FileName);echo("'"); echo("}"); $count++; } echo("]"); } //USER CODE: $rand = substr(md5(microtime()),rand(0,26),10); $targetfilepath= 'savefiles/' . $rand->rand . $mvcfile->FileName; if( is_file ($targetfilepath) ) unlink($targetfilepath); $mvcfile->MoveTo( $targetfilepath ); exit(200); ?> image upload(with form to choose file) Code: [Select] <?php require_once "phpuploader/include_phpuploader.php" ?> <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> Ajax - Build attachments table </title> <link href="demo.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> var handlerurl='ajax-attachments-handler.php' function CreateAjaxRequest() { var xh; if (window.XMLHttpRequest) xh = new window.XMLHttpRequest(); else xh = new ActiveXObject("Microsoft.XMLHTTP"); xh.open("POST", handlerurl, false, null, null); xh.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); return xh; } </script> <script type="text/javascript"> var fileArray=[]; function ShowAttachmentsTable() { var table = document.getElementById("filelist"); while(table.firstChild)table.removeChild(table.firstChild); AppendToFileList(fileArray); } function AppendToFileList(list) { var table = document.getElementById("filelist"); for (var i = 0; i < list.length; i++) { var item = list[i]; var row=table.insertRow(-1); row.setAttribute("fileguid",item.FileGuid); row.setAttribute("filename",item.FileName); var td1=row.insertCell(-1); td1.innerHTML="<img src='phpuploader/resources/circle.png' border='0'/>"; var td2=row.insertCell(-1); td2.innerHTML=item.FileName; var td4=row.insertCell(-1); td4.innerHTML="[<a href='"+handlerurl+"?download="+item.FileGuid+"'>download</a>]"; var td4=row.insertCell(-1); td4.innerHTML="[<a href='javascript:void(0)' onclick='Attachment_Remove(this)'>remove</a>]"; } } function Attachment_FindRow(element) { while(true) { if(element.nodeName=="TR") return element; element=element.parentNode; } } function Attachment_Remove(link) { var row=Attachment_FindRow(link); if(!confirm("Are you sure you want to delete '"+row.getAttribute("filename")+"'?")) return; var guid=row.getAttribute("fileguid"); var xh=CreateAjaxRequest(); xh.send("delete=" + guid); var table = document.getElementById("filelist"); table.deleteRow(row.rowIndex); for(var i=0;i<fileArray.length;i++) { if(fileArray[i].FileGuid==guid) { fileArray.splice(i,1); break; } } } function CuteWebUI_AjaxUploader_OnPostback() { var uploader = document.getElementById("myuploader"); var guidlist = uploader.value; var xh=CreateAjaxRequest(); xh.send("guidlist=" + guidlist); //call uploader to clear the client state uploader.reset(); if (xh.status != 200) { alert("http error " + xh.status); setTimeout(function() { document.write(xh.responseText); }, 10); return; } var list = eval(xh.responseText); //get JSON objects fileArray=fileArray.concat(list); AppendToFileList(list); } function ShowFiles() { var msgs=[]; for(var i=0;i<fileArray.length;i++) { msgs.push(fileArray[i].FileName); } alert(msgs.join("\r\n")); } </script> </head> <body> <div class="demo"> <h2>Building attachment table (AJAX)</h2> <p>This sample demonstrates how to build your own attachment table.</p> <?php $uploader=new PhpUploader(); $uploader->MaxSizeKB=10240; $uploader->Name="myuploader"; $uploader->MultipleFilesUpload=true; $uploader->InsertText="Select multiple files (Max 10M)"; $uploader->AllowedFileExtensions="*.jpg,*.png,*.gif,*.bmp,*.txt,*.zip,*.rar"; $uploader->Render(); ?> <br/><br/> <table id="filelist" style='border-collapse: collapse' class='Grid' border='0' cellspacing='0' cellpadding='2'> </table> <br/><br/> <button onclick="ShowFiles()">Show files</button> </div> <script type='text/javascript'> //this is to show the header.. ShowAttachmentsTable(); </script> <script type='text/javascript'> function CuteWebUI_AjaxUploader_OnTaskComplete(task) { var div=document.createElement("DIV"); var link=document.createElement("A"); link.setAttribute("href","savefiles/"+task.rand); link.innerHTML="You have uploaded file : savefiles/"+task.rand; link.target="_blank"; div.appendChild(link); document.body.appendChild(div); } </script> </body> </html> and here is the phpuploader.php file just in case Hey guys!! i'm after a bit of help with a script i am using for simple image upload to server. At the moment the script works fine and will allow upload of JPG files, i want to extend on this to allow GIF and PNG files to be uploaded aswell. This is the script i am using... <?php //?heck that we have a file if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 600Kb $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 600000)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/uploads/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { echo "Upload Complete! You can use the following link in the IMS:" .$newname; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } } else { echo "Error: Only .jpg images under 600Kb are accepted for upload"; } } else { echo "Error: No file uploaded"; } // $sessionid=session_id() //$newname=$_SESSION['session_name'] header( 'Location: success.php?newname1='.$filename ) ; ?> Any help would be appriciated!! ta!! jonny Hi All Not so much help as here is a handy class for uploading images Please feel free to find security bugs and let me know. Also feel free to use it if you want. http://onlyican.com/test_samples/bl_upload_img.phps To use the class, simply use the following require_once('bl_upload_img.php'); $objUploadImg = new UploadImg(); //Set values here if you wish such as $objUploadImg->setFormField('myFormField'); // The Name from <input type="file" name="myFormField" /> $objUploadImg->setSaveDirMain($_SERVER['DOCUMENT_ROOT'].'/MyImageFolder'; //Make sure to set the permissions //You can change most settings, just look at the function setDetaultValues() to get the function name //Now upload the image if($objUploadImg->uploadImage()){ $strFileName = $objUploadImg->getFileNameMain(); }else{ echo 'Error uploading Image<br />'.$objUploadImg->getErrorMessage(); } Me and a friend are working on a nice secure Image Upload Script. The Upload Class <?php class imageUploader { public $image; // [name], [type], [tmp_name], [error], [size] public $maxFileSize; public $imageExtension; public function __construct($image, $max_file_size) { $this->image = $image; $this->maxFileSize = $max_file_size; } public function isValidImage() { $validExts = array("gif" => "image/gif", "jpeg" => "image/jpeg", "png" => "image/png"); if(in_array(strtolower($this->image["type"]), $validExts) == true) { foreach($validExts as $name => $value) { if(strtolower($this->image["type"]) == $value) { $this->imageExtension = $name; break; } } return true; } else { return false; } } public function isValidSize() { if($this->image["size"] > $this->maxFileSize) { return false; } else { return true; } } public function uploadImage() { if($this->image["error"] > 0) { $errors[] = "An error has occurred"; } elseif($this->isValidImage() == false) { $errors[] = "Invalid file type. Only use JPG, GIF or PNG"; } elseif($this->isValidSize() == false) { $errors[] = "Max file size exceeded."; } if(count((array) $errors) == 0) { move_uploaded_file($this->image["tmp_name"], "Images/" . $this->generateName(rand(10, 15)) . time() . "." . $this->imageExtension); } else { echo implode("<br />", $errors); } } public function createThumbnails() { } public function resizeImage($size_y, $size_x) { } public function generateName($length) { $randstr = ""; for ($i = 0; $i < $length; $i++) { $randnum = mt_rand(0, 61); if ($randnum < 10) { $randstr .= chr($randnum + 48); } elseif ($randnum < 36) { $randstr .= chr($randnum + 55); } else { $randstr .= chr($randnum + 61); } } return $randstr; } } ?> The Everyday HTML Code: [Select] <form action="" method="post" enctype="multipart/form-data"> <table> <tr> <td>Image</td> <td><input type="file" name="file" id="file" /></td> <td><input type="submit" name="submit" value="Submit" /></td> </tr> </table> </form> My friend did most of the work, but had to go to sleep. My problem is I have a deadline to finish this in under 3 hours for use on my website. What I need it to do is create thumbnails in a /Thumbnail/ sub-folder, with thumbnails being cropped to 100px x 100px. If the full image is larger than 600px x 600px they would have to be resized down to nothing more than 600px for the longest side. I wouldn't mind if they were 300px x 600px, just nothing larger than 600px. I'm willing to pay for this to be completed, I only have roughly $50 though. I know this isn't a freelance area, but it kind of suits this area too with a freelance option. After the upload script is done, I have to work on a php system to get the images and display them, so that I'm not directly linking images. So anyone got some spare time to help out? Hi Im trying to write a script to clean up my image directory which has quite a lot of unused images that have built up over time. In order to do this I am doing the following. First Create a database table called 'image_clean' Then I'm searching through 3 tables and collecting all the image file names and dumping the names in the table 'image_clean' Can do that no problem. So now I have all the images I need in this one table 'image_clean' I now want to go through my directory 'image_uploads' and delete anything thats not in the 'image_clean' table. I know how to delete the files using unlink Im just unsure how to search through the directory file by file and check the file against the database. Im asumming I need to put them in an array. Could anyone give be a clue or two to get me started. I have no problem checking a database against a directory but when its the other way round 'checking a directory against a database I'm lost. What I might do is pop the files to delete in a new database called 'image_delete' so that I can then check the images to delete before I write the unlink script. But I'm just not sure how to pick up each file and compare it to the table. Thanks in advance. hello i am adding an image upload script, so users can upload a image with the recipe they are adding, but my script seems to not work, these are the files. add_recipe.php <?php // Start_session, check if user is logged in or not, and connect to the database all in one included file include_once("scripts/checkuserlog.php"); // Include the class files for auto making links out of full URLs and for Time Ago date formatting include_once("wi_class_files/autoMakeLinks.php"); include_once ("wi_class_files/agoTimeFormat.php"); // Create the two objects before we can use them below in this script $activeLinkObject = new autoActiveLink; $myObject = new convertToAgo; ?> <?php // Include this script for random member display on home page include_once "scripts/homePage_randomMembers.php"; ?> <?php $sql_blabs = mysql_query("SELECT id, mem_id, the_blab, blab_date FROM blabbing ORDER BY blab_date DESC LIMIT 30"); $blabberDisplayList = ""; // Initialize the variable here while($row = mysql_fetch_array($sql_blabs)){ $blabid = $row["id"]; $uid = $row["mem_id"]; $the_blab = $row["the_blab"]; $notokinarray = array("fag", "gay", "shit", "fuck", "stupid", "idiot", "asshole", "cunt", "douche"); $okinarray = array("sorcerer", "grey", "shug", "farg", "smart", "awesome guy", "asshole", "cake", "dude"); $the_blab = str_replace($notokinarray, $okinarray, $the_blab); $the_blab = ($activeLinkObject -> makeActiveLink($the_blab)); $blab_date = $row["blab_date"]; $convertedTime = ($myObject -> convert_datetime($blab_date)); $whenBlab = ($myObject -> makeAgo($convertedTime)); //$blab_date = strftime("%b %d, %Y %I:%M:%S %p", strtotime($blab_date)); // Inner sql query $sql_mem_data = mysql_query("SELECT id, username, firstname, lastname FROM myMembers WHERE id='$uid' LIMIT 1"); while($row = mysql_fetch_array($sql_mem_data)){ $uid = $row["id"]; $username = $row["username"]; $firstname = $row["firstname"]; if ($firstname != "") {$username = $firstname; } // (I added usernames late in my system, this line is not needed for you) /////// Mechanism to Display Pic. See if they have uploaded a pic or not ////////////////////////// $ucheck_pic = "members/$uid/image01.jpg"; $udefault_pic = "members/0/image01.jpg"; if (file_exists($ucheck_pic)) { $blabber_pic = '<div style="overflow:hidden; width:40px; height:40px;"><img src="' . $ucheck_pic . '" width="40px" border="0" /></div>'; // forces picture to be 100px wide and no more } else { $blabber_pic = "<img src=\"$udefault_pic\" width=\"40px\" height=\"40px\" border=\"0\" />"; // forces default picture to be 100px wide and no more } $blabberDisplayList .= ' <table width="100%" align="center" cellpadding="4" bgcolor="#CCCCCC"> <tr> <td width="7%" bgcolor="#FFFFFF" valign="top"><a href="profile.php?id=' . $uid . '">' . $blabber_pic . '</a> </td> <td width="93%" bgcolor="#EFEFEF" style="line-height:1.5em;" valign="top"><span class="greenColor textsize10">' . $whenBlab . ' <a href="profile.php?id=' . $uid . '">' . $username . '</a> said: </span><br /> ' . $the_blab . '</td> </tr> </table>'; } } ?> <!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=ISO-8859-1" /> <meta name="Description" content="Web Intersect is a deft combination of powerful free open source software for social networking, mixed with insider guidance and tutorials as to how it is made at its core for maximum adaptability. The goal is to give you a free website system that has a network or community integrated into it to allow people to join and interact with your website when you have the need." /> <meta name="Keywords" content="web intersect, how to build community, build social network, how to build website, learn free online, php and mysql, internet crossroads, directory, friend, business, update, profile, connect, all, website, blog, social network, connecting people, youtube, myspace, facebook, twitter, dynamic, portal, community, technical, expert, professional, personal, find, school, build, join, combine, marketing, optimization, spider, search, engine, seo, script" /> <title>CookBookers</title> <link href="style/main.css" rel="stylesheet" type="text/css" /> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <style type="text/css"> #Layer1 { height:210px; } body { background-color: #3c60a4; } .style4 {font-size: 36px} </style> </head> <body> <p> <?php include_once "header_template.php"; ?> </head> <body style="margin:0px;"> <center> </p> <p> </p> <table border="0" align="center" cellpadding="0" cellspacing="0" class="mainBodyTable"> <tr> <td width="124" valign="top"> <td width="776" colspan="2" align="left" valign="top" style="background-color:#EFEFEF; border:#999 0px; padding:10px;"> <table border="0" cellpadding="6"> </table> <table width="574" border="0"> <form enctype="multipart/form-data" action="include/recipe.php" method="post"> <span class="style4">Add Recipie</span> <tr> <th width="232" scope="col"></th> <th width="332" scope="col"> </th> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Public:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input name="Pub" value="1" type="checkbox" id="Pub"/> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Title:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="title" /> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Prep time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="prep" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Cooking time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="cook" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Makes:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="make" /> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Ingrediants:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="ingr" cols="40"></textarea> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Method: </span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="desc" cols="40"></textarea> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Notes:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="note" cols="40"></textarea> </span></td> </tr> <tr> <td><input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> Choose a picture to upload: <input name="uploaded_file" type="file" /></td> </tr> <tr> <td><input name="submit" type="submit" style="padding:5px 10px;" value="Submit" /></td> </tr> <tr> <td> </td> </tr> </table> </tr> </table> </td> </tr> </table> <?php include_once "footer_template.php"; ?> </body> recipe.php (upload form script) <?php //include("session.php"); include("database.php"); @session_start(); $user = $_SESSION['username']; mysql_real_escape_string($user); //die($user); $Pub=$_POST['Pub']; $title=$_POST['title']; $prep=$_POST['prep']; $cook=$_POST['cook']; $make=$_POST['make']; $ingr=$_POST['ingr']; $desc=$_POST['desc']; $note=$_POST['note']; //if($user=="Guest"||$user==""){ //header("Location: ../index.php"); //} //else{ $database->AddRecipe($user,$Pub,$title,$prep,$cook,$make,$ingr,$desc,$note); $uploaded_file=$_POST['files']['uploaded_file'] //Сheck that we have a file if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 350Kb $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 350000)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/upload/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { echo "It's done! The file has been saved as: ".$newname; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } } else { echo "Error: Only .jpg images under 350Kb are accepted for upload"; } } else { echo "Error: No file uploaded"; } header("Location: ../recipe_added.php"); //} ?> Hey Friends,
I am new to this forum, and does not know anything about programming. And I require very small help from the experts of forum. I have downloaded free image hosting script from web & it is not working fine, it gets stuck at basic.php (one of the file in script). I am sharing the script here also sharing the website. My website : bsm1313.5gbfree.com
Note : I have uploaded a rar file. Kindly change extension to .rar from .php. as it was not allowing me to upload the rar file.
Any kind of help is highly highly appreciated. Thanks a ton in advance.
Attached Files
easyimagehoster_1.32.php 35.46KB
5 downloads sure, I know how to output a picture with a php script. the problem is, the host I use, they won't let me edit the php.ini file to look through png files for PHP scripts before outputting. Of course, it is bad practice anyways... Is there any way to make it easy for a user to download the image with a .png extension instead of .php. (I know this is done automatically in windows 7, like: image.php.png because it reads the content type). Any good ideas? =) This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=318987.0 I'm new to programming so take it easy on me but I wrote this script for php and it's not complete yet but I could use some advice on file upload security. Besides recreating the image, checking token/request and setting apache settings what else can I do to secure this application. Here's my code:
header('Content-Type: application/json'); $uploaded = array(); if(!empty($_FILES['file']['name'][0])) { $allowedExts = array("gif", "jpeg", "pjpeg", "x-png", "jpg", "png"); foreach ($_FILES['file']['tmp_name'] as $k => $v) { $name = $_FILES['file']['name'][$k]; $type = $_FILES['file']['type'][$k]; $error = $_FILES["file"]["error"][$k]; $size = $_FILES["file"]["size"][$k]; $tempDir = $_FILES["file"]["tmp_name"][$k]; $lowerName = strtolower($name); $temp = explode(".", $lowerName); $extension = end($temp); if ((($type == "image/gif") || ($type == "image/jpeg") || ($type == "image/jpg") || ($type == "image/pjpeg") || ($type == "image/x-png") || ($type == "image/png")) && ($size < 20000) && in_array($extension, $allowedExts)) { if ($error > 0) { echo "Return Code: " . $error . "<br>"; } else { $imageInfo = getimagesize($tempDir); if($imageInfo['mime'] != 'image/gif' && $imageInfo['mime'] != 'image/jpeg' && $imageInfo['mime'] != 'image/jpg' && $imageInfo['mime'] != 'image/pjpeg' && $imageInfo['mime'] != 'image/x-png' && $imageInfo['mime'] != 'image/png') { echo 'Sorry we only accept GIF, JPEG, JPG, PJPEG, X-PNG, PNG image files!'; }else { switch($type) { case 'image/gif': $newName = md5(uniqid()). '.' .time(). '.gif'; break; case 'image/jpeg': $newName = md5(uniqid()). '.' .time(). '.jpeg'; break; case 'image/jpg': $newName = md5(uniqid()). '.' .time(). '.jpg'; break; case 'image/pjpeg': $newName = md5(uniqid()). '.' .time(). '.pjpeg'; break; case 'image/x-png': $newName = md5(uniqid()). '.' .time(). '.x-png'; break; case 'image/png': $newName = md5(uniqid()). '.' .time(). '.png'; break; } if (file_exists('images/' .Session::get(Config::get('session/session_name')). '/' .$newName)) { echo escape($name) . " already exists. "; } else { if(move_uploaded_file($tempDir, 'images/' .Session::get(Config::get('session/session_name')). '/' .$newName)) { $uploaded[] = array( 'name' => $name, 'file' => 'images/' .Session::get(Config::get('session/session_name')). '/' .$newName ); } } } } } else { echo 'Sorry we only accept GIF, JPEG, JPG, PJPEG, X-PNG, PNG image files!'; } } }I've been researching apache Mod_mime but can't find enough info to wrap my mind around it. Edited by Millertime1, 12 August 2014 - 01:00 PM. Hi Guys, I have an issue with the following script which is throwing this error Quote( ! ) Parse error: syntax error, unexpected end of file in C:\wamp64\www\script\images.php on line 41 I just can not see the error, can anyone help (not even sure the script is going to work) <?php /* settings */ //folder for images saving $saveDir = "c:\wamp64\www\script\images\"; //database connection // Turn off all error reporting error_reporting(0); $conn = mysqli_connect('localhost', 'root', '', 'tbl_temp_products'); //start and end table row to prevent timeout or hard server work $start = '1'; $end = '200'; /* end of settings */ //query for fetching the image urls $sql = 'SELECT image_url FROM tbl_temp_products ORDER BY id DESC LIMIT ' . $start . ',' . $end . ''; $res = $conn->query($sql); $count = 0; //this is for count the total row fetched $notify = ''; //this is for seeing result or errors while ($row = $res->fetch_assoc()) { $url = $row(['image_url']); $dest = $saveDir . clean($row(['image_url'])) . '.jpg'; if (!file_exists($dest)){ //prevent file overwriting if (copy($url, $dest)){ $notify.= 'image saved: '. $row(['image_url']); $count++; }else{ $notify.= 'ERROR saving image: '. $row(['image_url']); }else{ $notify.= 'image already exists: '. $row(['image_url']); } } //output result echo 'TOTAL IMAGE SAVED: ' .$count .'\n'; echo $notify; ?>
|