PHP - Unlink : Permission Denied
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. Similar TutorialsHi. 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. Hmm, hello everyone, i'm running my php in an ubuntu server and I'm trying to run a command using exec (i.e. 'echo 1 > /var/www/test.txt') but I always get a permission denied issue, although i've already changed the permissions to 777 (read-write-execute) Any solution? I am getting this error Warning: ftp_put() [function.ftp-put]: Can't open that file: Permission denied in /home/chris/public_html/site-name/wp-content/setup.php on line 62 Code: [Select] $conn_id = ftp_connect($host, 21) or die ("Cannot connect to host"); ftp_login($conn_id, $usr, $pwd) or die("Cannot login"); // turn on passive mode transfers (some servers need this) // ftp_pasv ($conn_id, true); $upload = ftp_put($conn_id, $file[0], $file[1], FTP_ASCII); print (!$upload) ? die('Cannot upload') : 'Upload complete'; print "\n"; The permissions to the file is 0644, if I change it to 0777 ftp_put complains and says the file is not found. How can I ftp this file? What is going on? Thanks, Chris Hi, On login page load, (even before submitting user name and pass) Debugger finds "permission denied error", can see it he goldpharm.co.il/authentication.php Now, when a user submit's user name and pass, nothing happens, it stays on the login page. I am not sure in what code the bug is , can you tell by the bug error in this page: goldpharm.co.il/authentication.php ? and how can it be fixed? , should I post the code? Thanks. Hi I have an image uploading script that won't upload images... It worked at one point when i had folder permission at 0777 but i was told that is risky so i changed it to 0775 Now it won't work and i can't use 0777. Any one know what i need to do to get it to work? This is my script: Code: [Select] <?php $salt = 35322232414; $name = $salt.$safe; $name = md5($name); if(isset($_POST['submit'])){ if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 1000000)) { if ($_FILES["file"]["error"] > 0) { echo $_FILES["file"]["error"]; } else { $filename = md5(serverdate()) . $_FILES["file"]["name"]; if (file_exists("userimages/".$name."/".$filename)) { echo "Image already uploaded!"; } else { if (is_dir("userimages/".$name) == FALSE){ mkdir("userimages/".$name, 0775); //permissions } move_uploaded_file($_FILES["file"]["tmp_name"], "userimages/".$name."/" . $filename); echo "Image has been uploaded!"; } Error i get: Quote Warning: move_uploaded_file(images/73640de25b7d656733ce2f808a330f18/7fc9cb9cf5ae1f7a5dd9105d3f9559fb_63.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in uploadfile.php on line 41 Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpjrX3SO' to 'images/73640de25b7d656733ce2f808a330f18/7fc9cb9cf5ae1f7a5dd9105d3f9559fb_63.jpg' in uploadfile.php on line 4 I have a PHP web system that store in a windows server. In the system, there is a function for user to upload files to another server (Shared server in Unix). When i try to upload a file, it gives warning: Warning: move_uploaded_file(\\unixserver/sharedfolder/upload/test.txt) [function.move-uploaded-file]: failed to open stream: Permission denied in C:\wamp\www\upload\index.php on line 40 For your information, my username has been assigned in xxx's group that has access to read and write on that folder. Besides, i'm able to open,create and delete files on that folder's server manually (samba). The safe mode setting is off. Does anybody has any idea why this thing happen? I'm getting this error when I try to fwrite to a directory: Quote failed to open stream: Permission denied I have added the user www-data to the group which has permission to the directory? The directory is this: /home/directory1/documents directory1 = drwxr-x--- documents = drwxrwx--- Does anyone know whats going on? I'm trying to open a URL using fopen() and I keep getting this error: Code: [Select] Failed to open stream: Permission deniedI can not work out what is wrong, it's not a firewall as far as I can tell. I am using apache web server on linux. I am using PHP for web designing. On web server, i want to show the configuration data by reading the ini file. I am creating this ini file from one php code itself. If this php code i run through linux terminal, the file is created with file and group owner as root.(i am having sudo rights on machine) Then if i try to read the ini file from my apache web server, it gives warning as failed to open stream: permission denied. I have tried changing the owner, and permissions to 777 of the file. Still it is not readable.
On the other hand, if i run the php code of ini file creation through web server, ini file is created with file and group owner as apche. and web server is able to read/ write the file.
But i want to create that file from root or some other user and later read/written by apache.
How to give this access permission?
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 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 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 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 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, 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! 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 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 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! |