PHP unlink() not working to delete files? - php

PHP unlink() not working to delete files
my code is deleting in database properly but cant deleted from file how pls help me how to delete data in my uploaded file?
<?php
$id = $_POST['id'];
include_once('db.php');
$objDbCon = new db_connect();
$strSQL = "DELETE FROM study_material WHERE id='$id'";
$objQuery = $objDbCon->Query($strSQL);
unlink('../uploaded/');
if ($objQuery) {
echo "Delete Sucessfully";
} else {enter code here
echo "Error";
}
?>

Use this,
unlink($_SERVER['DOCUMENT_ROOT']).'/projectname'.$filename);
where
$filename is ./folderuploads/filename.extension

unlink() is used to delete files and you try to delete directory using this function ('../uploaded/' is directory not a file). If you want to remove empty directory you need to use rmdir() function instead

The parameter for unlink() function must be a filename rather than a directory.

Try this code:
1:- select file from your table.
2:- unlink file from directory
3:- last delete row from table
unlink('../uploaded/filename');

It's important to make sure that the files/folders have the correct permissions also in addition to the other answers.
PHP usually runs as the user and so if you don't have the correct permissions to manage the file, you won't be able to do anything with it.
In SSH:
chown -R user:user /path/to/folder
This will set all of your files to the user PHP is using. Obviously replace user:user with root:root for example.

Related

permission denied when i try to unlink an image in the folder using php [duplicate]

I make a site and it has this feature to upload a file and that file is uploaded to a server
Im just a newbie to php I download xampp and I run this site that i made in my local machine.
My site is like this you upload a file then that file will be uploaded to a server, but when i tried unlink() because when i try to remove the filename to a database I also want to remove that pic on the server, but instead I got an error and it says "Permission denied".
question:
How can I got permission to use unlink();?
I only run this on my localmachine using xampp
Permission denied error happens because you're trying to delete a file without having enough/right permissions for doing that.
To do this you must be using superuser account or be the same user that have uploaded the file.
You can go to the directory from your command line and check the permissions that are set to the file.
The easiest solution is to loggin as administrator/root and delete the file.
Here is another work around:
// define if we under Windows
$tmp = dirname(__FILE__);
if (strpos($tmp, '/', 0)!==false) {
define('WINDOWS_SERVER', false);
} else {
define('WINDOWS_SERVER', true);
}
$deleteError = 0;
if (!WINDOWS_SERVER) {
if (!unlink($fileName)) {
$deleteError = 1;
}
} else {
$lines = array();
exec("DEL /F/Q \"$fileName\"", $lines, $deleteError);
}
if ($deleteError) {
echo 'file delete error';
}
And some more: PHP Manual, unlink(), Post 106952
I would recommend, always first to check PHP Manual (in case your question concerns PHP), just go to the page with function that you have problems with and just click search CTRL+F in your browser and enter, for example, Windows, and as a result, in your case, you would find at least 7 related posts to that or very close to that what you were looking for.
Read this URL
How to use Unlink() function
I found this information in the comments of the function unlink()
Under Windows System and Apache, denied access to file is an usual error to unlink file. To delete file you must to change file's owern. An example:
<?php
chown($TempDirectory."/".$FileName,666); //Insert an Invalid UserId to set to Nobody Owern; 666 is my standard for "Nobody"
unlink($TempDirectory."/".$FileName);
?>
So try something like this:
$Path = './doc/stuffs/sample.docx';
chown($Path, 666);
if ( unlink($Path) )
echo "success";
else
echo "fail";
EDIT 1
Try to use this in the path:
$Path = '.'.DIRECTORY_SEPARATOR.'doc'.DIRECTORY_SEPARATOR.'stuffs'.DIRECTORY_SEPARATOR.'sample.docx';

A way to change the ownership of Apache to order creating txt file

Could you please tell me how to change Apache ownership in Windows if you guys know, since I cannot create txt files using PHP without permission. According to my issue, I need to be able to authorise a file to be made.
What I am trying to do is create a script that records keystrokes in the Firefox extension section. This script will send the data to an Apache PHP file and store it in a text file. I would appreciate your response if you could.
<?php
session_start();
if (!isset($_POST['key'])) {
echo ("Didn't received any new KEY strokes Yet!");
exit(0);
}
//read and write = a+, If the file does not exist, attempt to create it
$file_log = fopen("key.txt","a+");
if (!isset($_SESSION['site']) || $_SESSION['site'] != $_POST['site']) {
$_SESSION['site'] = $_POST['site'];
fwrite($file_log, "| site : ".$_POST['site']." | ");
}
fwrite($file_log,$_POST['key']);
fclose($file_log);
echo("text saved successfully");
It looks like you are not defining a full path for the file.
Depending on where php is running just calling fopen("key.txt","a+") might default to the root directory.
When creating/modifying files you should specify the full path to the file
fopen("/var/www/mydir/example/path/key.txt","a+")

unlink(..): No such file or directory in codeigniter

I am using codeigniter3. now I want to delete records as well as related images but records deleted but it doesn't delete the images from the folder. every record has 3 images.
public function delete_by_id_and_img($id) {
$image_file_name = $this->db->select('material_image')->get_where('tbl_raw_material', array('id' => $id))->row()->material_image;
$cwd = getcwd(); // save the current working directory
$image_file_path = $cwd."\\public\img\\";
chdir($image_file_path);
unlink($image_file_name);
chdir($cwd); // Restore the previous working directory
$this->db->where('id', $id);
$this->db->delete('tbl_raw_material');
return true;
}
I'm not sure but is your syntax with two \ in your path before public and after img correct?
$image_file_path = $cwd."\\public\img\\";
Also check if / this will work for you , since \ I think, is for linux
You can use something like this:
$image_file_path='/project/folder/file_to_delete';
unlink($image_file_path);
You have to give full path of the file.
Remove file from the folder - denied access of file so change the user and then unlink file
chown($path, 666); //Insert an Invalid UserId to set to Nobody Owern;
unlink($path);

File can be opened in FTP but not in HTTP after upload from site

I am writing a PHP script that enables a user to upload a picture and then displays it on their page. Everything works fine up until the part where they need to display it. I run the form and submit it and the picture shows up in the directory in my FTP. I can download that file from the FTP and view it on my computer. I can visit the FTP url of that image, login and see it fine.
When I go to the HTTP version of the exact same URL, I get a 404 error. I have checked the permissions on the folder and it's ok to read and write for a user. I even checked the permissions on the file itself after it's uploaded and it's fine. Here's my PHP code when uploading the file:
<?php
include('connect.php');
$user_id = $_SESSION['user_id'];
if($_POST['submit']){
//GET FILE ATTRIBUTES
$name = $_FILES['myfile']['name'];
$size = $_FILES['myfile']['size'];
$tmp_name = $_FILES['myfile']['tmp_name'];
if ($name){
//start upload process
$location = "pics/$name";
move_uploaded_file($tmp_name,$location);
$sql = "UPDATE tbl_name SET imagelocation='$location' WHERE user_id='$user_id'";
$query = $mysqli->query($sql);
header('location:profile.php');
}
else{
die("Please select a file! <a href='profile.php'>GO BACK</a>");
}
}
?>
Any idea what this could be? I haven't seen this problem before.
i think folder permission may not be right when you created the folder with mkdir(). hope setting right permission will solve the problem.
It works now. I deleted the folder and recreated the folder with the same name. The folder was initially created through mkdir in PHP so I'm sure that had something to do with it. If anybody has any insight into why the folder wouldn't work with mkdir, feel free to post here. Thanks!

Why i am not able to delete the files(PHP)?

I use a form where i have listed the data from database like title, date etc. from the database and using checkboxes i use the multiple delete operation
For example my code look like this
<form method="post" action="action.php">
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $row['id']; ?>"/>
<input name="delete" type="submit" id="delete" value="Delete"/>
and in the action.php the code is like this
$checkbox = $_POST['checkbox'];
//count the number of selected checkboxes in an array
$count = count($checkbox);
//Create a for loop to delete
for($i=0;$i<$count;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM news WHERE id='$del_id'";
$result_delete_data = mysql_query($sql);
}
Now the table i want to delete actually have 5 table entities like title, timestamp,pic_title,pic_brief,pic_detail the last three entities i.e pic_title, pic_brief and pic_detail is actually storing the path of the image for example the value stored in one of the 3 entity would look like this upload/file/pic_title1.jpg
My problem is when i run my first for loop it successfully deletes the table without any problem but the file which exist in the file directory remains intact. i want to delete that file too, to remove that file i thought of adding another for loop which i did something like this
for($j=0;$j<$count;$j++){
$delete_id = $checkbox[$j];
$query = "SELECT news.pic_title, news.pic_brief, news.pic_detail FROM news WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
unlink($row['pic_title']);
unlink($row['pic_brief']);
unlink($row['pic_detail']);
}
The above code is unable to delete the requested file, my Query string is perfectly working fine i tested it by removing the unlink function and printing the values, it prints all the selected value , but it is refusing to delete the file and when i try to run the loop it shows error in the last three line, while i am pretty sure that, $row['pic_title'], $row['pic_brief'], $row['pic_brief'], have the full path of the image.
unlink($row['pic_title']);
unlink($row['pic_brief']);
unlink($row['pic_brief']);
where i am going wrong?
P.S: There is nothing wrong with file permission because when i individually try to run the function unlink it deletes the file from the same directory.
EDIT : This is the error message i get
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 580
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 581
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 582
To be more precise i tested this function individually in php and it is working perfectly fine
$target = 'upload/file/file1.jpg';
unlink($target);
and for this reason i dont think the file permission is causing the error, i guess i am going wrong somewhere with the logic.
#Lekensteyn got me the solution, thank you Lekensteyn.
actually i had to first hold the value in a variable and then unlink the file. the working code looks like this.
for($j=0;$j<$count;$j++){
$delete_id = $checkbox[$j];
$query = "SELECT * FROM news WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$pic_title = $row['pic_title'];
$pic_brief = $row['pic_brief'];
$pic_detail = $row['pic_detail'];
unlink($pic_title);
unlink($pic_brief);
unlink($pic_detail);
}
It could be file permissions. You need to be the owner of the file in order to delete it.
Some hosters run the website under the user 'apache' (or similar), but the files are owned by the ftpuser (accountxxxx for example).
Check the current working dir too, with echo getcwd() if the paths not absolute.
Your script is vulnerable to SQL injection too, a post request with checkbox[]='||1||' deletes everything.
Add
error_reporting(E_ALL);
at the top of your script.
Your problem is program flow related and can be found only by using debugging.
Start from displaying ALL errors occurred and repair them. This will most likely lead you to the reason you could not delete your files.
Probably your path to upload is the problem. In your test script:
$target = 'upload/file/file1.jpg';
unlink($target);
I bet you ran that from a directory right below 'upload/' right?
And this delete script, it's probably not in the same directory?
I recommend using the full path to the 'upload/file/' directory; this will vary depending on your configuration, but probably looks like /www/htdocs/upload/file or /var/www/public_html/upload/file.
To make the script more transportable, you can use the PHP constant FILE to figure out the directory. I usually set this app/site wide in a bootstrap or universal configuration file, along the lines of
define('PATH', dirname(__FILE__)); # sets PATH with the directory name of the bootstrap file where this code lives
I sometimes key on something in my path I can rely on, say my app name. Say my bootstrap is here:
/www/apps/golf-scorecard/bootstrap.php
I might split on 'golf-scorecard'.
list($path,) = explode('golf-scorecard',dirname(__FILE__)); # $path should be /www/apps/
define('PATH', $path.'golf-scorecard'); # since I split on it, I have to add it back in
This means if I move the app/site to another server, or clone it from a repository onto a machine where the document root is, say /home/username/apps/golf-scorecard/htdocs/, then it won't matter. It does couple the app name but I am okay with that.
first thing is you need to check the file permissions .you need to give 777 permission to the folder.and then follow below code
$target = 'upload/file/file1.jpg';
unlink($target);

Categories