PHP - Problem Deleting A File With Unlink()
Dear forum
I'm new to this forum and since I'm doing more and more php development, you'll probably going to see me more. For now I got this problem and I hope you guys can help me out =(. I'm building an administartion panel for a website. On this panel the administrator can upload pictures for a gallery. This part works, so normally permissions shouldn't be a problem. The file names are stored in my mysql database for example "pic2.jpg", "pic2.jpg", ... Now I got this form to delete pictures from a specific gallery. It deletes from the database but it just wont delete the files. I'm using a local xampp server. I got the following code: Code: $merk = $_POST["MerkLeegMaken"]; $sql = "SELECT * FROM catalogus WHERE merkId=" . $merk; $resultSet = mysql_query($sql); while ( $row = mysql_fetch_array($query) ) { $url = "../uploads/" . $row["foto"]; // this url is f.e. "../uploads/picture1.jpg", and I'm currently in "/administrationPanel/form.php fclose($url); unlink($url); } $sql = "DELETE FROM catalogus WHERE merkId=" . $merk; mysql_query($sql); $message = "<p class='success'>Het huidig merk is succesvol leeggemaakt.</p>"; (I got in my root dir the directory /uploads and the directory /administartionPanel, so ../uploads should be correct right?" I also tried to delete with "c:/xampp/xampp/htdocs/uploads/pic1.jpg" but that didn't work either. But shouldn't "../uploads/pic1.jpg" work anyway, since I use that same url as the source of an Image below the form. All my different url attempts didn't work. I kept finding the files in my windows explorer =( Hope someone can help. www.phpkode.com Similar Tutorialsany help with this please? it works fine with deleting database results but the unlink wont unlink file from dir? Code: [Select] else if($action=="del") { $id = $_GET["id"]; $cls = $_GET["cls"]; $dir = "gallery/$cls"; echo "<p align=\"center\">"; $owner = mysql_fetch_array(mysql_query("SELECT uid FROM gallery WHERE id='".$id."'")); if(mod(getuid_id($id))||getuid_id($id)==$owner[0]) { $res = mysql_query("DELETE FROM gallery WHERE id='".$id."'"); $res2 = mysql_query("DELETE FROM comments WHERE pid='".$id."'"); $res3 = mysql_query("DELETE FROM rate WHERE pid='".$id."'"); if($res||res2||res3 || unlink($dir)) { echo "Photo Deleted From Gallery<br/>"; }else{ echo "Database Error!<br/>"; } }else{ echo "You can't delete this Photo"; } After a user on my site deletes their account I want their profile picture to be deleted from my images folder. I was testing the unlink function on my index.php file and it is failing. Here is the error: Warning: unlink(/assets/img/avatars/users/jasongordon.png): No such file or directory in /home/www-data/big.com/index.php on line 86 My code was just: unlink('/assets/img/avatars/users/jasongordon.png'); I'm not sure why this fails because my file does exist. Basically i have a table show the contents of database (id, name, image type, image size). This is it, http://dvplus.webuda.com/testing/delete-image.php The image on the last column i want it have a href on that image that will delete the file directory that relevant on the table row. I tried to user <a href="<? unlink="" ?>img scr</a>....., any one got any idears??? I want to delete a file, I'm using Windows XP, however, it gives me Permission Denied: Code: [Select] $file =$row['img'] ; $filedel = "mages/".$file; unlink ($filedel); Is the code wrong? I tried setting permission to the folder but in vain... I have a download-list, and want to have a delete-button/link at each file. I have tried different codes, but i'm new to php and need some help. if ($handle = opendir('files/engelsk/')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $en .= '» <a href="/files/engelsk/'.$file.'">'.$file.'</a> - <i><a href="#">Delete file</a></i><br />'; } } closedir($handle); } It's the "<a href="#">Delete file</a>" I want to be the delete-button. Please help! I am trying to delete a file via unlink(). It's a .html file, stored in a folder on its own. // current directory $dir = dirname(__FILE__); $dir = str_replace('classes','',$dir); $file = str_replace('./',$dir,$fr['location']); unlink($fr['location']); if(!unlink($file)){ echo 'err'; } if(file_exists($file)){ echo 'ok1'; } The $fr['location'] stores the real location, as ./uploads/1303577497/barebones.html. I've tried every combination I can think of to delete it. I've even deleted it from FTP and re-uploaded it, in case it was a permissions issue, but it refuses to go. When I file_get_contents it, it appears as existing. Can anyone help? Hi, When i launch my code i get the following php error: Warning: unlink(../files/"yCUuH0223e3d6d046acb58678fbb54042e0fe.pdf") [function.unlink]: Invalid argument in C:\xampp\htdocs\intra\VVS\admin\fakture-edit.php on line 74 But in the dir: C:\xampp\htdocs\intra\VVS\files\ The file exists.. here's my php code: Code: [Select] $id = mysql_real_escape_string($_GET['id']); $fil = mysql_real_escape_string($_GET['fil']); $result2 = mysql_query("SELECT * FROM fakture WHERE id=('$id') LIMIT 1"); $row2 = mysql_fetch_array($result2); if ($_GET["op"] == "process") { if (!unlink('../files/"'.$fil.'"')) please just deleting this post I think i figured it out Hi fellas, i am wondering if someone can point me in the right direction? I have a simple upload script where users can upload thier profile picture, but if they want to change that picture i would like to delete the old one, to save space and time cleaning up the left overs. So, without further ado, i gather the info from the existing database: $existingimage = "/profileimage/". $userid2['image']; Then further on in the script when it comes time to add or update the image i have: if (!empty($existingimage)) {unlink($existingimage);} $insert= ("UPDATE userdatabase SET image='$finalname' WHERE user='$userid'"); mysql_query($insert); Only problem is, the unlink part dont work, the original image is still there! Any clues? Hey guys, first post and I've just returned to PHP after about 4 years of no coding, so be gentle! In a nutshell I'm creating a photo album and I've pretty much got the majority of it complete, apart from a few tweaks and the obvious ongoing development. I'm at the stage now where I need to moderate images being uploaded, so I've made an admin only script which displays the uploaded images with links that say approve and delete. Uploaded images are stored in uploads/ which are left there until i move them to img/, plus the filename is stored in mysql so I can "<img src='../uploads/".$row['filename']."' width='200'>". Now, I would like to make the Approve button move the image from uploads/ to img/ and I'd like the delete button to remove both the entry from MySQL and the file from the uploads folder and I'm not too sure on how to make it work. Here's what I have so far in the mod.php file (mod for moderation) Code: [Select] $image = mysql_query("SELECT * FROM images WHERE id"); while($row = mysql_fetch_assoc($image)) { echo " <table> <td> <tr> <img src='../uploads/".$row['filename']."' width='200'><br /> </tr> </td> <td> <tr> <a href=''>Approve</a> <a href=''>Delete</a> </tr> </td> </table> "; } You'll have to ignore the table tags, I'm still getting used to positioning items on the screen lol. Any clues would be greatly appreciated Live long and prosper. 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 writing a cookie using VB in an ASPX file: Code: [Select] username = "myname" If Request.Cookies("username") Is Nothing Then Response.Cookies.Set(New HttpCookie("username", username)) Response.Write("newcookie <br />") Else Response.Cookies.Set(Request.Cookies("username")) Response.Write("not nothing <br />") End If Response.Cookies("username").Expires = DateTime.Now.AddYears(1) and I can read it in PHP: Code: [Select] if (isset($_COOKIE['username'])) { $username = $_COOKIE['username']; } But when I kill it with PHP ... Code: [Select] if (isset($_COOKIE['username'])) { setcookie ("username", NULL, time()-3600*24*300 ); //300 days unset($_COOKIE["username"]); } ... the VB in the ASPX file still sees it and thinks it's an empty string, since it returns: "not nothing" It would seem that the cookie is still alive somewhere, no? And how do I kill it completely, so that the VB writes a new cookie with the same name? Hello. I wish to get a file name from a DB and then delete it from the server. I have tried the code below. It gets the full url to the photo I wish to delete. It looks like this WITHOUT the spaces: http : // www . mysite . com/users/photo.jpg Then it attempts to unlink it. Code: [Select] $result = mysql_query("SELECT PhotoURL FROM `$info` WHERE userid = '$UserID'") or die (mysql_error()); while ($row = mysql_fetch_array($result)) { $myFile = $row['PhotoURL']; unlink($myFile); } I get an error message like this (edited to remove my url, etc): Code: [Select] Warning: unlink() [function.unlink]: Unable to locate stream wrapper in /home/user/public_html/code.php : eval()'d code on line 64 What am I doing wrong? Also is there another way to delete server files? the code below creates a table that lets me choose a row to delete from mysql database <?php $host="host"; // Host name $username="user"; // Mysql username $password="pass"; // Mysql password $db_name="testdocs"; // Database name $tbl_name="Docs"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // Build SQL query if(!isset($_POST['delete'])) $sql="SELECT * FROM $tbl_name ORDER BY id"; else { $sql = "DELETE FROM $tbl_name WHERE"; // add row id to where section for($i=0;$i<count($_POST['checkbox']);$i++){ if($i != 0) $sql.= "AND "; $sql .= " id='" . $_POST['checkbox'][$i] . "'"; } } $result = mysql_query($sql); if(isset($_POST['delete'])) header('Location: index.php'); // redirect ?> <table align="center" width="400" border="0" cellspacing="1" cellpadding="0"> <tr> <td><form name="delete" method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>"> <table width="400" border="1" cellpadding="3" cellspacing="1"> <tr> <td colspan="5" align="center"><strong>Testimonials</strong> </td> </tr> <tr> <td align="center"><strong>Select</strong></td> <td align="center"><strong>ID</strong></td> <td align="center"><strong>Name</strong></td> <td align="center"><strong>Message</strong></td> <td align="center"><strong>Download</strong></td> </tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td align="center"> <input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"> </td> <td><? echo $rows['id']; ?></td> <td><? echo $rows['Name']; ?></td> <td><? echo $rows['Message']; ?></td> <td><? echo $rows['Download']; ?></td> </tr> <tr> <td colspan="5" align="center"><input name="delete" type="submit" id="delete" value="Delete"></td> </tr> <?php } mysql_close(); ?> </table> </form> </td> </tr> </table> but what i am trying to do is add unlink() to the script so when i delete a row it deletes the linked file. this bit is where the filename is shown like test.doc and the files are stored in the directory /test_docs <td><? echo $rows['Download']; ?></td> is there anyway to do it so it deletes the file Not used unlink function before so a bit unsure. I do need it to remove a file in a different directory than the one the unlink function is in - it's actually in a parent sub directory. Is there another way of doing this if unlink is unsuitable or can someone help me correct my code? Code: [Select] elseif ( $action == "dlt" && $step == "2" ) { mysql_query('DELETE FROM items WHERE auto_increment = "'.$auto_increment.'"') or die( mysql_error() ); $small = "../admin/imgs/small/90_'.$auto_increment.'.jpg"; unlink( $small ); $large = "../admin/imgs/small/250_'.$auto_increment.'.jpg"; unlink( $large ); } Cheers I have a config file that lists a file like so.. Code: [Select] $file1 = 'storagefolder/mydatabase.txt'; How can I delete the file "mydatabase.txt" that is in another directory 'storagefolder' ? Code: [Select] unlink($file1);gives an error that says not such file or directory hi again, i have a image uploading page, i wanna add a delete option to each image that was uploaded.. the code that im using is taking thumbnails from folder, displaying only 4 images per page, and when u click on thumbnail - original sized image comes up, heres the code: <?php $del = "delete"; //The directory to your images folder, with trailing slash $dir = "uploads/thumbs/watermarkedthumbs/"; $dir2 = "uploads/"; //Set the extensions you want to load, seperate by a comma. $extensions = "jpeg,jpg,png,gif"; //Set the number of images you want to display per page $imagesPerPage = 4; //Set the $page variable if(!isset($_GET['page'])){ $page = 1; }else{ $page = $_GET['page']; } //Load all images into an array $images = glob($dir."*.{".$extensions."}", GLOB_BRACE); $images2 = glob($dir2."*.{".$extensions."}", GLOB_BRACE); //Count the number of images $totalImages = count($images); $totalImages2 = count($images2); //Get the total pages $totalPages = ceil($totalImages / $imagesPerPage); $totalPages2 = ceil($totalImages2 / $imagesPerPage); //Make sure the page you are on is not greater then the total pages available. if($page > $totalPages){ //Set the currnet page to the total pages. $page = $totalPages; } //Now find where to start the loading from $from = ($page * $imagesPerPage) - $imagesPerPage; //Now start looping for($i = $from; $i < ($from + $imagesPerPage); $i++){ //We need to make sure that its within the range of totalImages. if($i < $totalImages){ //Now we can display the image! echo "<a href='{$images2[$i]}'><img style='border:thin solid #FFF;margin-top:10px;margin-left:10px;margin-right:10px ' src='{$images[$i]}'alt='{$images[$i]}' /></a>"; } } //Now to display the page numbers! for($p = 1; $p <= $totalPages; $p++){ if($p == $page){ $tmp_pages[] = "<strong>{$p}</strong>"; }else{ $tmp_pages[] = "<a href='?page={$p}'>{$p}</a>"; } } //Now display pages, seperated by a hyphon. echo "<br/>" . implode(" - ", $tmp_pages); ?> i was thinking of adding another echo he if($i < $totalImages){ //Now we can display the image! echo "<a href='{$images2[$i]}'><img style='border:thin solid #FFF;margin-top:10px;margin-left:10px;margin-right:10px ' src='{$images[$i]}'alt='{$images[$i]}' /></a>"; } and then doing something with unlink.. do i need to look for something else to add a delete button to each image uploaded? thanks Hi, I have a function that resides in a class, this function deletes a file in a specific folder. This works, the file is deleted but I get the warning that he can't find the file in the folder. So here's the error: Quote Warning: unlink(/Applications/MAMP/htdocs/wordpress/wp-content/plugins/flashplayer/player/songs/14-i_cant_go_on_ill_go_on_feat._vanessa_hudgens-everything_i_own.mp3) [function.unlink]: No such file or directory in /Applications/MAMP/htdocs/wordpress/wp-content/plugins/flashplayer/xml.php on line 122 And here's the code: Delete function: function remove_mp3_file(){ $target_path = dirname(__FILE__)."/player/songs/"; unlink($target_path.$this->filename); } function that calls the remove function: function remove_xml_item(){ //$this->open_xml_playlist(); $xml = new DOMDocument('1.0', 'UTF-8'); $xml->preserveWhiteSpace = false; $file = dirname(__FILE__)."/player/music.xml"; $xml->load($file); $xpath = new DOMXPath($xml); $query = '//song[title="'.htmlentities($this->title).'" and artist = "'.htmlentities($this->artist).'" ]'; $entries = $xpath->query( $query ); foreach( $entries as $entry ){ $entry->parentNode->removeChild($entry); } $savefile = $xml->save($file); $remove_file = $this->remove_mp3_file(); if( (!$savefile) && (!$remove_file) ){ return false; }elseif( ($savefile) && ($remove_file) ){ return true; } } First I thought that it was I set a variable that calls the delete function and then I use a if statement for this, but it wasn't that. Anyone an idea? Thanks! If I use code: while ($row = mysql_fetch_assoc($result)) { @unlink(SRV_ROOT . IMAGE_DIR . $row['image']); } What is the difference between @unlink(SRV_ROOT . IMAGE_DIR . $row['image']); AND unlink(SRV_ROOT . IMAGE_DIR . $row['image']); On this path is deleted image files, but why use symbol @ When it is used in syntax, and why? Tanks in advance |