PHP - Unlink Issue?
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! Similar TutorialsHello. 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 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 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 all, Please can somebody help me sort my script out? I want it to delete the sql contents in the chosen table, and delete the file stored on server at the same time. URL for server is stored in the database. Everything works except for when it comes to deleting the file off the server. I just can't work it out/get my head around it. Many Thanks in advance if you can help, Steve Code: [Select] <?php require_once('Connections/localhost.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $query_Recordset1 = "SELECT Images FROM testimonials WHERE Testimonial_Id=%s"; $img_dir = 'uploaded_images/'; $image_name = $row_RecordSet1['Images']; if ((isset($_GET['del'])) && ($_GET['del'] != "")) { unlink($img_dir . $row['Images']); // unlink($img_dir.$image_name); $deleteSQL = sprintf("DELETE FROM testimonials WHERE Testimonial_Id=%s", GetSQLValueString($_GET['del'], "int")); mysql_select_db($database_localhost, $localhost); $Result1 = mysql_query($deleteSQL, $localhost) or die(mysql_error()); $deleteGoTo = "index.php"; if (isset($_SERVER['QUERY_STRING'])) { $deleteGoTo .= (strpos($deleteGoTo, '?')) ? "&" : "?"; $deleteGoTo .= $_SERVER['QUERY_STRING']; } header(sprintf("Location: %s", $deleteGoTo)); } if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $maxRows_Recordset1 = 10; $pageNum_Recordset1 = 0; if (isset($_GET['pageNum_Recordset1'])) { $pageNum_Recordset1 = $_GET['pageNum_Recordset1']; } $startRow_Recordset1 = $pageNum_Recordset1 * $maxRows_Recordset1; mysql_select_db($database_localhost, $localhost); $query_Recordset1 = "SELECT * FROM testimonials ORDER BY SortOrder ASC"; $query_limit_Recordset1 = sprintf("%s LIMIT %d, %d", $query_Recordset1, $startRow_Recordset1, $maxRows_Recordset1); $Recordset1 = mysql_query($query_limit_Recordset1, $localhost) or die(mysql_error()); $row_Recordset1 = mysql_fetch_assoc($Recordset1); if (isset($_GET['totalRows_Recordset1'])) { $totalRows_Recordset1 = $_GET['totalRows_Recordset1']; } else { $all_Recordset1 = mysql_query($query_Recordset1); $totalRows_Recordset1 = mysql_num_rows($all_Recordset1); } $totalPages_Recordset1 = ceil($totalRows_Recordset1/$maxRows_Recordset1)-1; ?> <!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>Sub-Lime Renovations Admin Area - View Testimonials</title> </head> <body> <div align="center"> <h1><strong>Sub-Lime Renovations Administration Area</strong></h1> </div> <p align="center"><a href="index.php">Admin Home</a> | <a href="add_testimonials.php">Add Testimonials</a></p> <p> </p> <p> </p> <table border="1" align="center" cellpadding="1" cellspacing="1"> <tr> <td>Customer Name</td> <td>Town</td> <td>Testimonial</td> <td>Sort Order</td> <td>Images</td> </tr> <?php do { ?> <tr> <td><?php echo $row_Recordset1['CustomerName']; ?></td> <td><?php echo $row_Recordset1['Town']; ?></td> <td><?php echo $row_Recordset1['Testimonial']; ?></td> <td><?php echo $row_Recordset1['SortOrder']; ?></td> <td><img width ="100" height="100" src="/AdministrationAreaSublime/<?php echo $row_Recordset1['Images']; ?>" alt="" /></td> <td><a href="edit_testimonials.php?Testimonial_Id=<?php echo $row_Recordset1['Testimonial_Id']; ?>">Edit</a></td> <td><input type="button" name="del" id="del" value="Delete" onClick="document.location.href='testimonials.php?del=<?php echo $row_Recordset1['Testimonial_Id']?>'" /></td></tr> <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?> </table> <p> </p> </body> </html> <?php mysql_free_result($Recordset1); ?> Hi guys, I'm a newbie in php programming and i would like to ask you guys about my issue... am trying to do a script that deletes a file from server and then upload an image to the server... unfortunately it doesn't work... i was able to get the upload part but after putting in the unlink() it doesn't work... the file is deleted from the server however it upload doesn't... hope you guys can assist me with this... thanks in advance... if(file_exists($file_src)){ unlink($file_src); } if(!empty($_FILES['userfile']['name'])){ //file variables $file_name = $_FILES['userfile']['name']; $temp_name = $_FILES['userfile']['tmp_name']; $file_type = $_FILES['userfile']['type']; //get extension of the file $base = basename($file_name); $extension = substr($base, strlen($base)-4, strlen($base)); //only these file types will be allowed $allowed_extensions = array(".txt", "docx", ".doc"); //check that this file type is allowed if(!in_array($extension,$allowed_extensions)){ header('Location:modify.php?action=errorupload&id='.$row['index']); } else{ move_uploaded_file($_FILES['userfile']['tmp_name'], "../files/" . $_FILES['userfile']['name']); $sql2 = "UPDATE t_board SET `writer` = '".$this->writer."', `subject` = '".$this->subject."', `message` = '".$this->message."', `filename` = '".$this->files['name']."' WHERE `index` = '".$this->id."'"; $query2 = mysql_query($sql2); $sql3 = "SELECT * FROM t_board WHERE `index` = '".$this->id."'"; $query3 = mysql_query($sql3); $row2 = mysql_fetch_array($query3); header("Location: view.php?action=edited&writer=".$row2['index']); }//in_array Hi. I'm trying to make my folder management tool able to remove stuff. Problem is, I get permission denied.
I've checked the NFTS perms for the share and for the folder. It's also not read only. I logged into my other workstation as the service account the web server is using and opened a DOS window and did "rd \\server\share\folder" and it removed it no problem. It just fails in PHP. Any idea what I should be looking at? Thanks!
Edited by Strahan, 02 August 2014 - 05:06 PM. I wonder whether someone may be able to help please. I've put together the following page http://www.mapmyfinds.co.uk/development/deletetest.php which allows users to view a gallery of their uploaded images. I'm now starting to work on the `deletion` functionality and I've attached a suitable icon and the Javascript code so the user can select the image to delete. From the research I've done, I know that to delete the files from my server I need to use the PHP `unlink` command. The problem I'm having is I'm not sure how to tie up the 'deletion' selection made by the user and the physical deletion of the files. I've added my `unlink` code below which uses the relative path and then for the thumbnails, Ive added the echo source filename, so the image in the Thumbnails folder matches the one of the same name in the gallery being deleted, but as I said, it's at this point that I'm not sure what to do next. Code: [Select] <?php unlink($path); unlink($path . 'Thumbnails/' . "<?php echo $source; ?>"); ?> I just wondered whether someone could perhaps have a look at this please and possibly provide some guidance on how I can link up the Javascript `click` event and the deletion of the files. Many thanks and kind regards I want to delete an image file from a folder using unlink. The code is : Code: [Select] $movie_id = $checkbox[$i]; $sql = "DELETE from movie_basic_details where `movie_id` = '$movie_id'"; $result = mysql_query($sql) or die(mysql_error()); $sql1 = "DELETE from movie_details where `movie_id` = '$movie_id'"; $result = mysql_query($sql1) or die(mysql_error()); $sql2 = "DELETE from movie_stars where `movie_id` = '$movie_id'"; $result = mysql_query($sql2) or die(mysql_error()); $query = "select movie_name from movie_basic_details where movie_id = '$movie_id'"; $res = mysql_query($query) or die(mysql_error()); $data = mysql_fetch_array($res); unlink("upload/movies/".$data['movie_name']); } The entries in the database have been deleted but only the image corresponds to that entry do not get deleted. The following warning comes up : Warning: unlink(upload/movies/) [function.unlink]: Permission denied in C:\wamp\www\ContentPanel\deletemovies.php on line 23 I have uploaded the files using $_FILES server variable and move_uploaded_file function. I am running this script on windows 7. Please Help. 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??? 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. any 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"; } Hello everyone. I am having trouble trying to write some script that will unlink all files in a directory. Can anyone help me? I am not sure of the best way to do this? Thankyou. Hey guys, I've written a script that is suppose to Display the files within a specified directory /documents/ with check boxes to the right of them.. This worked out great. Then I wanted to devise a method to remove or unlink the selected files (via check box) when the user pressed a Submit button.. File Permissions on the server are 777 and I have hardcoded an unlink to test to see if it works and it does.. So the bug lies within my code.. Before I post the code let me explain my method in doing this. I created a for loop to name each check box after the corresponding file to the left and created a variable with the file name (to use later) Then on button press I made a for loop (it goes up to 50 because I wasn't sure how to make it the exact number of files and I didn't want to overload the server with say 1000000 :?) that goes through and checks the check box's values and if they equal 1, unlink the file in /documents/ Here's the code: Code: [Select] <html> <body> <form action="" method="post" class="delete"> <?php $dir = "documents/"; if ($handle = opendir($dir)) { echo '<h2>List of Files in '.$dir.'</h2>'; echo '<table>'; for ($i = -2; false !== ($file = readdir($handle)); $i++) { if ($file != "." && $file != "..") { echo '<tr><td><a href="'.$dir.''.$file.'">'.$file.'</a></td><td><input type="checkbox" name="Del['.$i.']" /></td</tr>'; $DelFile[$i] = $file; } } echo '</table>'; closedir($handle); } ?> <br /> <input type="submit" name="submit" value="Delete Checked Files" /> </form> <?php for ($i = 0; $i <= 50; $i++) if ('Del['.$i.']' == 1) unlink("'.$dir.''.$DelFile[$i].'"); ?> </body> </html> Help is extremely appreciated, and Thanks in advance guys! Hi guys, I using the following code if ($handle = opendir('temp_photo')) { while (false !== ($file = readdir($handle))) { $filelastmodified = filemtime($file); if(($filelastmodified-time()) > 24*3600) { unlink($file); } } closedir($handle); } I want it to look in the directory and remove all the files that are older than 24 hours old. When I run the code I get the following error.. Warning: filemtime() [function.filemtime]: stat failed for image1.jpg Warning: filemtime() [function.filemtime]: stat failed for image2.jpg Warning: filemtime() [function.filemtime]: stat failed for image3.jpg Warning: filemtime() [function.filemtime]: stat failed for image4.jpg It seems to read the directory, but it doesn't remove them and I receive the error message. Any ideas of what may be going on or do you have a script that may resolve this issue? Thanks, Dan 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? 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 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... |