PHP - Deleting Images From Folder On Server
Can someone tell me how I can remove or delete an image from a folder on a server using PHP? I tried this:
Code: [Select] unlink("http://midwestcreativeconsulting.com/jhrevell/wp-content/themes/twentyten_3/upload/" . $location); before my delete MySQL statement, but I keep getting this error: Warning: unlink() [function.unlink]: http does not allow unlinking in /home/midwestc/public_html/jhrevell/wp-content/themes/twentyten_3/removejewelry.php on line 22 Can anyone help and tell me how I can make it work? Similar TutorialsHii everyone. I'm using the following code to save a file into a folder, and allow files to be deleted from the folder. the upload works fine. The delete does work, but sometimes you have to click on the delete link a few times before the file is deleted. i'm wondering if someone can see where the problem is in the code. Also, when the file is deleted, the history entry is not added. i'm a bit confused why it doesn't. i'd appreciate any assistance which you can provide. thank you. Code: [Select] <?php include('db.php'); $CommID = $_GET['CommID']; // prevent server timeout if uploads take longer than 30 seconds. set_time_limit(0); if (isset($_GET['action'])) { $action = $_GET['action']; } else { $action = ''; } if (($action == 'view' or $action == 'dnld') and isset($_GET['id'])) { $id = $_GET['id']; // User is retrieving a file $sql = "SELECT * FROM communicationsattachments WHERE id = '$id'"; $result = @mysql_query($sql); if (!$result) { exit('Database error: ' . mysql_error()); } $file = mysql_fetch_array($result); if (!$file) { exit('No files found in database!'); } $uploadDir = "upload/"; $filename = $file['name']; $mimetype = $file['type']; $disposition = 'inline'; $filePath = $uploadDir . $filename; if ($action == 'dnld') { $disposition = 'attachment'; if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5') or strpos($_SERVER['HTTP_USER_AGENT'], 'Opera 7')) { $mimetype = 'application/x-download'; } } header("content-disposition: $disposition; name=$filename"); header("content-type: $type"); readfile($filename); exit(); } elseif ($action == 'del' and isset($_GET['id'])) { $id = $_GET['id']; $sql = "SELECT * FROM communicationsattachments WHERE id='$id'"; $result = @mysql_query($sql); if (!$result) { exit('Database error: ' . mysql_error()); } $file = mysql_fetch_array($result); if (!$file) { exit('File with given ID not found in database!'); } chdir('upload/'); $uploadDir = "upload/"; $filename = $file['name']; $mimetype = $file['type']; $disposition = 'inline'; $path="upload/" . $filename; if(unlink($path)) echo "File has been deleted file "; // User is deleting a file mysql_query ("DELETE FROM communicationsattachments WHERE id='$id'") or die(mysql_error()); // fetch name of case owner based on CommID Number $sql = "SELECT communications.CommID, communications.ActionOwner FROM communications WHERE communications.CommID='$CommID'"; $result = mysql_query($sql); if (!$result) { echo "Could not successfully run query ($sql) from DB: " . mysql_error(); exit; } if (mysql_num_rows($result) == 0) { echo "No case owner found"; exit; } while ($row = mysql_fetch_assoc($result)) { $CaseOwner = $row["ActionOwner"]; } // Inserts history into the communications history table mysql_query("INSERT INTO communicationshistory (CommID, DateRecorded, TimeRecorded, StatusNotes) VALUES ('$CommID', CURDATE(), NOW(), 'Attachment Saved by $CaseOwner')") or die(mysql_error()); // header('location: ' . $_SERVER['PHP_SELF']); exit(); } elseif (isset($_FILES['upload'])) { // Bail out if the file isn't really an upload. if (!is_uploaded_file($_FILES['upload']['tmp_name'])) { echo "There was no file uploaded!"; //header('location: ' . $_SERVER['PHP_SELF']); exit; } $uploadDir = "upload/"; $fileName = $_FILES['upload']['name']; $tmpName = $_FILES['upload']['tmp_name']; $fileSize = $_FILES['upload']['size']; $fileType = $_FILES['upload']['type']; $uploaddesc = $_POST['desc']; $filePath = $uploadDir . $fileName; $result = move_uploaded_file($tmpName, $filePath); if (!$result) { echo "Error uploading file"; } if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); } $query = "INSERT INTO communicationsattachments (name, type, description, CommID, size, path ) ". "VALUES ('$fileName', '$fileType', '$uploaddesc', '$CommID', '$fileSize', '$filePath')"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); echo "<br>Files uploaded<br>"; // fetch name of case owner based on Mega Case Number $sql = "SELECT communications.CommID, communications.ActionOwner FROM communications WHERE communications.CommID='$CommID'"; $result = mysql_query($sql); if (!$result) { echo "Could not successfully run query ($sql) from DB: " . mysql_error(); exit; } if (mysql_num_rows($result) == 0) { echo "No case owner found"; exit; } while ($row = mysql_fetch_assoc($result)) { $CaseOwner = $row["ActionOwner"]; } // Inserts history into the communications history table mysql_query("INSERT INTO communicationshistory (CommID, DateRecorded, TimeRecorded, StatusNotes) VALUES ('$CommID', CURDATE(), NOW(), 'Attachment Saved by $CaseOwner')") or die(mysql_error()); } // Default page view: lists stored files $sql = "SELECT * FROM communicationsattachments WHERE CommID=$CommID"; $filelist = @mysql_query($sql); if (!$filelist) { exit('Database error: ' . mysql_error()); } ?> <!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></title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link href="styles.css" rel="stylesheet" type="text/css" /> <style type="text/css"> body { background-color: #cad7f6; } </style> <script type="text/javascript"> function refresh_parent(){ window.parent.location = window.parent.location.href; } </script> </head> <body> <div style="margin:20PX; background-color:#cad7f6; "> <form action="" method="post" enctype="multipart/form-data" > Upload File: <input type="file" name="upload" /> File Description: (not required) <input type="text" name="desc" maxlength="255" /> <input type="submit" value="Upload" onclick="refresh_parent()"/> <input name="MAX_FILE_SIZE" type="hidden" value="10737418240" /> </form> Files stored in the datebase for CommID <?php echo $CommID; ?> are listed below. You may attach as many files as necessary.<br /><br /> <table> <tr> <th>Filename: </th> <th>Description: </th> <th>Size: </th> </tr> <?php if (mysql_num_rows($filelist) > 0) { while ($f = mysql_fetch_array($filelist)) { ?> <tr valign="top"> <td width="200px"><?php echo $f['name']; ?> </td> <td width="200px"><?php echo $f['description']; ?> </td> <td><?php echo $f['size']; ?> </td> <td> [<a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=dnld&id=<?php echo $f['id']; ?>">Download</a> | <a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=del&id=<?php echo $f['id']; ?>" onclick="refresh_parent()">Delete</a>] </td> </tr> <?php } } else { ?> <tr><td colspan="3">No Files!</td></tr> <?php } ?> </table> </div> </body> </html> Hi, I deleted my image in the server folder, but still my image is showing, what might be the problem, Confused, I have cleared my browser cache and restarted, but nothing helps me, if anyone have idea about this pls share with me Thanks, I have this script from http://lampload.com/...,view.download/ (I am not using a database) I can upload images fine, I can view files, but I want to delete them. When I press the delete button, nothing happens
http://www.jayg.co.u...oad_gallery.php
<form>
<?php $dir = dirname(__FILENAME__)."/images/gallery" ; $files1 = scandir($dir); foreach($files1 as $file){ if(strlen($file) >=3){ $foil = strstr($file, 'jpg'); // As of PHP 5.3.0 $foil = $file; $pos = strpos($file, 'css'); if ($foil==true){ echo '<input type="checkbox" name="filenames[]" value="'.$foil.'" />'; echo "<img width='130' height='38' src='images/gallery/$file' /><br/>"; // for live host //echo "<img width='130' height='38' src='/ABOOK/SORTING/gallery-dynamic/images/gallery/ $file' /><br/>"; } } }?> <input type="submit" name="mysubmit2" value="Delete"> </form>
any ideas please?
thanks
Hi, I have a form where a user selects a file to attach to the email. At the moment when you select a file it uploads from the user device. How do i change this so that a user can attach a file from a folder on the server. For example the folder name is uploadinvoice so when the user selects the browse button to attach a file it opens up the uploadinvoice folder on the server so the user can select the file from there ?
Thanks
coding i have at moment function ValidateEmail($email) { $pattern = '/^([0-9a-z]([-.\w]*[0-9a-z])*@(([0-9a-z])+([-\w]*[0-9a-z])*\.)+[a-z]{2,6})$/i'; return preg_match($pattern, $email); } if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['formid']) && $_POST['formid'] == 'form1') { $mailto = $_POST['youremail']; $mailfrom = isset($_POST['myemail']) ? $_POST['myemail'] : $mailto; $subject = 'Message'; $message = 'Message'; $success_url = './test.php'; $error_url = ''; $eol = "\n"; $error = ''; $internalfields = array ("submit", "reset", "send", "filesize", "formid", "captcha_code", "recaptcha_challenge_field", "recaptcha_response_field", "g-recaptcha-response"); $boundary = md5(uniqid(time())); $header = 'From: '.$mailfrom.$eol; $header .= 'Reply-To: '.$mailfrom.$eol; $header .= 'MIME-Version: 1.0'.$eol; $header .= 'Content-Type: multipart/mixed; boundary="'.$boundary.'"'.$eol; $header .= 'X-Mailer: PHP v'.phpversion().$eol; try { if (!ValidateEmail($mailfrom)) { $error .= "The specified email address (" . $mailfrom . ") is invalid!\n<br>"; throw new Exception($error); } $message .= $eol; foreach ($_POST as $key => $value) { if (!in_array(strtolower($key), $internalfields)) { if (!is_array($value)) { $message .= ucwords(str_replace("_", " ", $key)) . " : " . $value . $eol; } else { $message .= ucwords(str_replace("_", " ", $key)) . " : " . implode(",", $value) . $eol; } } } $body = 'This is a multi-part message in MIME format.'.$eol.$eol; $body .= '--'.$boundary.$eol; $body .= 'Content-Type: text/plain; charset=ISO-8859-1'.$eol; $body .= 'Content-Transfer-Encoding: 8bit'.$eol; $body .= $eol.stripslashes($message).$eol; if (!empty($_FILES)) { foreach ($_FILES as $key => $value) { if ($_FILES[$key]['error'] == 0) { $body .= '--'.$boundary.$eol; $body .= 'Content-Type: '.$_FILES[$key]['type'].'; name='.$_FILES[$key]['name'].$eol; $body .= 'Content-Transfer-Encoding: base64'.$eol; $body .= 'Content-Disposition: attachment; filename='.$_FILES[$key]['name'].$eol; $body .= $eol.chunk_split(base64_encode(file_get_contents($_FILES[$key]['tmp_name']))).$eol; } } } $body .= '--'.$boundary.'--'.$eol; if ($mailto != '') { mail($mailto, $subject, $body, $header); } header('Location: '.$success_url); } catch (Exception $e) { $errorcode = file_get_contents($error_url); $replace = "##error##"; $errorcode = str_replace($replace, $e->getMessage(), $errorcode); echo $errorcode; } exit;
} Hello, I'm trying to have my index.php to open/run another test.php file. I'm having my own server that I play with, that I run Ubuntu on. So the index.php are located at /var/www/ directory, but I want to run a file that are located at /testing/test.php The final test.php is file for showing pictures, and I don't want to out all the pictures under the /var/www/ location. It's alot of photos. I don't know much about php but I have been trying this: <?php header("Location: /var/www/testing/test.php"); //These below are desperat old tries. //header("Location: ./testing/test.php"); //header("Location: ../testing/test.php"); //$handle = fopen("/privat/Web_pictures/test.php", "r"); //"/testing/test.php" // header("Location: ./test.php"); //This one actually works, but I'm still in the wrong folder (/var/www/) echo "test "; // NN4 requires that we output something... exit(); ?> Thankful for help! Hi, ive recently created a gallery website and im happy with the way everything currently works. However the main drawback is the site uploads using a html webfom which is great for remote users or the odd image. However, as i want to mass upload my existing collection i will need the ability to read a selected folder and then to carry out all the same processes that existed from the existing html form upload. Im also using gdlibrary and checking file types to ensure they are within my allowed list, but im wondering if there are any other common security alerts i should be aware of to keep things a little bit safer if/when i publish outside of my LAN. So in a nut shell i need some assistance with changing my upload process to work for more than one file at a time, ideally by reading a folder, or at least reading X amount of files at a time - processing them then moving onto next batch of files in the list. Then the next part i need help with is checking/improving basic security of the system Hi, Where to install this PHPMailer? It is on WebServer or it will work if I install it in the same folders where my webpages are? Thanks. Hi, I want to be able to click on the photo and go to the next one in a folder. I have this code already, I just am not quite sure how to finish it. -George Code: [Select] <?php $count = $_GET['count']; $dir = "images"; $names = array(); $handle = opendir($dir); while ($name = readdir($handle)){ if(is_dir("$dir/$name")) { if($name != '.' && $name != '..') { echo "directory: $name\n"; } } elseif ($name != '.DS_Store' ) { $names[] = $name; } } closedir($handle); $numberofitems = count($names); $numberofitems--; if ($count <= $numberofitems){ echo "<p>"; echo "<img src='images/".$names[$count]."'>"; } else {echo "end";} ?> I made an upload image system, the images are stored in a folder, while the image name is stored in database. When I try to execute the image name, it works successfully, but when I try to disply the image from the folder by using the image name in the database, I fail each time. The folder where the images are being stored is named: saveimage Here is the query: Code: [Select] <?php mysql_connect('localhost', 'root', '') or die ('Connection Failed'); mysql_select_db('imagedatabase'); $images = mysql_query("SELECT * FROM img WHERE email='$lemail'"); while($row = mysql_fetch_array($images)) { echo "<img src='saveimage/'".$row['img_description']; } ?> I have a bad way with words, so if the title doesnt make much sense nor my post, I apolagize! But I am using a while loop and mysql_fetch_array to echo all information in a table in mysql. With each entry, I have included a button that executes a delete query for that entry. Code: [Select] $delquery="DELETE FROM requests WHERE user = '".$row['user']."'"; mysql_query($delquery,$link2); echo "<font size='19px' color='#009933'>User deleted from request database.When I click the button, the message is echod in every entry listed on the page, and nothing happens. I figured Id use delete from the username, so that way mysql will know which one to delete... but Idk when I think about it thats dumb and makes no sense. Im stuck. This side of the application im trying to make is the admin side where I can process requests. After I process the request I delete it from the database so I know I processed it. I have no idea what query to use for this. Anybody know how I could do this? Thanks I'm trying to write code that will let me pull 10 out of 15 images out of a folder and display them on my site. The images are all different, and I don't want dupes to show. So far, I have the following code figured out: --------------- $s = array ("image.jpg", "image2.jpg"); // as many images as you want $n = rand(1,len($s)); // randomly pick a number between 1 and the length of the array echo "<img src='". $s[$n] .'">"; // create an image tag for the randomly selected imagine (value of the randomly defined key) array_pop($s, $n); // This piece isn't right, it needs to EXTRACT and delete the $n array element. // Next random image $n = rand(1,len($s)); echo "<img src='". $s[$n] .'">"; --------------- Any ideas what array_pop should be to work properly? Thank you for the help! The problem: I'm trying to create a page which outputs images from a folder which I have been able to do, but the problem I'm having is not being able to get the page to display the most recent image according to file modification date at the top. The first set of code below outputs the image timestamps in descending order, from newest to oldest which is what I want, but as soon as I change/add a couple lines of code (Shown in the second lot of code) to get the image file name along with the timestamp, the echoed list (timestamp and file names) gets muddled up in a random order. In short; As soon as the file names are retrieved with the timestamp, the list goes from being organised descendingly, to not. Show timestamp only code (1st lot of code): <?php //Open images directory $ignore = array("..","."); $dir = opendir("images1"); $images = array(); $sortedimages = array(); //List files in images directory while (($file = readdir($dir)) !== false) if (!in_array($file, $ignore)) $images[] = $file; foreach ($images as $image) { $filetime = filemtime("images1/$image"); $sortedimages[] = $filetime; } rsort($sortedimages); foreach ($sortedimages as $sorted) { //foreach ($sorted as $key => $value) //{ echo "$sorted<br/>"; } //} closedir($dir); ?> The show timestamp and file name code (2nd lot of code): <?php //Open images directory $ignore = array("..","."); $dir = opendir("images1"); $images = array(); $sortedimages = array(); //List files in images directory while (($file = readdir($dir)) !== false) if (!in_array($file, $ignore)) $images[] = $file; foreach ($images as $image) { $filetime = filemtime("images1/$image"); $sortedimages[] = array($filetime => $image); } rsort($sortedimages); foreach ($sortedimages as $sorted) { foreach ($sorted as $key => $value) { echo "$key and $value<br/>"; } } closedir($dir); ?> The changes made in the 2nd script from the 1st: //Changed: $sortedimages[] = $filetime; ---> $sortedimages[] = array($filetime => $image); //Included the previously commented out: foreach ($sorted as $key => $value) { } //Changed: echo "$sorted<br/>"; ---> echo "$key and $value<br/>"; Thanks for any help! Hi
I echo out images from a folder. The problem is that I have a html file in the same folder but I don't want to echo that out. How can I write my code to get rid of the html in the output?
Here my code:
<?php $filetype = '*.html'; $dirname = substr('$filetype'); $i=0; if (isset($_POST['submit2'])) { //get the dir from POST $selected_dir = $_POST['myDirs']; //now get the files from within the selected dir and echo them to the screen foreach(glob($selected_dir . DIRECTORY_SEPARATOR . '*') as $dirname) { echo substr($dirname, 0, -4); echo '<img src="'.$dirname.'" />'; echo "<label><div class=\"radiobt\"><input type='radio' name='radio1' value='$i'/></div></label>"; } } ?>P.S. when I echo out : substr($dirname, 0, -4); I want to get ride of the html filename there too. How can I do so something like this? Im using this code to call all the images in a folder: Code: [Select] $handle = opendir(dirname(realpath(__FILE__)).'/images/'); while($file = readdir($handle)){ if($file !== '.' && $file !== '..'){ echo '<img src="admin/img/uploads/'.$file.'" border="0" />'; } } My html says the images are present but they aren't visable on screen: Code: [Select] <div id="contentbody"> <img src="admin/img/uploads/send-button-sprite copy.png" border="0" /> <img src="admin/img/uploads/test" border="0" /> <img src="admin/img/uploads/counter.jpg" border="0" /> <img src="admin/img/uploads/send-button-sprite.png" border="0" /> </div> Any help is much appreciated! I have searched around and found this code that suggests that I should be able to read an image file and echo it directly in to the page without hyperlinking to the file that is outside the public folder, but i get the error message that it is not there even though the file is. Warning: getimagesize() [function.getimagesize]: Unable to access "/home/****/upload/AAABBBCCC.JPG" in /home/****/public_html/client.php on line 40 Code: [Select] $image = "AAABBBCCC.JPG"; $path= "/home/****/upload/"; $details = getimagesize($path . $image); header ('Content-Type: ' . $details['mime']); echo file_get_contents($path . $image); Hey guys, i'm new to this site and would need some help with coding. So i'm making a car part website which should has brand/model search. It's a dropdown search which will get the brand / model from database and should display all the parts for that exact model, from folder. Database structure which i have is id, master, name. ( Here's some pictures to clear out what i'm doing. http://imgur.com/a/7XwVd ) So the problem is that it does not get the images from folder named ex: *_audi_a3.jpg. And link to codes what have been written already. Parts.php: http://pastebin.com/q6vdypge Update.php: http://pastebin.com/DymhGQ17 Search_images.php: http://pastebin.com/LF5Q0i8f Core.js: http://pastebin.com/bgc0y4TS I don't know what's wrong with it sadly. One thing i noticed when i used firebug it gives error on category when searching error:true. Hope you guys understand what i mean here, and also all help is appreciated. And move this post if it's in wrong place. Thanks! Edited by aeonius, 17 October 2014 - 12:15 PM. Basically i have a folder with 100+ images they are NOT all the same extension, what im wanting to do is use PHP to find all the images and put them all in a database. how would i go about doing this? thanks Hello once again, i got this code that takes all images from a folder and displays them close to each other. Heres the code: <?php $dir = 'uploads/thumbs/watermarkedthumbs/'; $file_display = array ('jpg', 'jpeg', 'png', 'gif'); if (file_exists($dir) == false) { echo 'tt'; } else { $dir_contents = scandir($dir); foreach ($dir_contents as $file) { $file_type = strtolower(end(explode('.', $file))); if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) { echo '<img src="', $dir, '/', $file, '" alt="', $file, '" />'; } } } ?> How do i add margins in between them? i wanna make it smth like 'margin-left:10px, margin-top-10px'. Also, how do i add an 'overflow'? i mean, my images currently are displayed in a div, and i wanna make it so that if the folder has lets say 9 images, it would only display 6 of them, and the rest would be displayed in the same div after i click a button or smth (like '1' for the first div and '2' would appear if theres an overflow, and when i click '2' the rest of the images would appear). To make these adjustments do i need to make a different php file or do i change something in this code? thanks in advance. |