Deleting file from folder - php

I'm not quite sure where the problem lies.
But the code won't unlink the file :(
<?php include_once("sessions.php");
require_once("connect.php");
if(isset($_POST['delete'])){
$album_id = $_SESSION['album_id'];
$checkbox = $_POST['photo_checkbox'];
$count = count($checkbox);
for($i = 0; $i < $count; $i++) {
$id = (int) $checkbox[$i]; // Parse your value to integer
if ($id > 0) { // and check if it's bigger then 0
$query = "SELECT * FROM media WHERE id = $id";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($result)){
$file = $row['path'];
if(!unlink($file)){
$_SESSION["edit_message"] = "<br>Something went wrong while deleting shit ... please try your editing again." .$file;
header ("Location: ../fotos.php?album=".$album_id."");
exit;
}
}
$query = "DELETE FROM media WHERE id = $id";
$result = mysqli_query($connection, $query);
}
}
if($result){
$_SESSION["edit_message"] = "<br>Successfully deleted !";
header ("Location: ../fotos.php?album=".$album_id."");
exit;}
}
?>
If I take out the unlink loop part and just go straight to the deleting from the db it works fine.
What am I missing?
Might it be the permissions that are hindering the code from executing ?
EDIT :
Changed the permissions of the file to 0777 now. So it should really work ...
But still doesn't seem to. ! :/
I have no ideas now.
Maybe the loop isn't working properly ?
Thanx for your help
Cheers
Chris

$file2 = chmod($file, 0777);
if(!unlink($file2)){
$file2 is getting the return value of chmod, which is a bool. You're then trying to unlink a true/false value. Perhaps you meant to unlink($file) ?
Edit to reflect your changes:
If $file is not a fully qualified path name $file will be relative to the current working directory of where ever the script is running from. Ensure $file is a full path name.

Write permissions on the file are not sufficient you need write permissions on the directory itself to be able to delete a file within it.
You should first check the file exists, you should then check that you have the correct permissions on the directory NOT the file.
if(file_exists($file) && is_writeable(dirname($file))){
unlink($file);
}else{
//invalid path or permission problems
}

Related

deleting file with unlink function php

This script is working for deleting from mysql database, but it's not unlinking from local directory files. Can anyone help to fix this script? Here's the script
<?php
include "../config/database.php";
if(isset($_GET['kode'])){
$id = (int) $_GET['kode'];
$sql = "select * from anidata where id='$id'";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0 ){
$data = mysql_fetch_array($query);
//delete file
$path = 'upload/'.$data['image'];
#unlink($path);
//delete from database
mysql_query("delete from anidata where id='$id'");
}
}
header("Location: view.php");
?>
And thanks for helping anyway! :)
First try this to check if your file is deleted from directory
if( #unlink($path) ) {
mysql_query("DELETE FROM `anidata` WHERE id='$id'");
}
If not deleted from your database, check your assigned path in php code !!
This File are no delete Because file store out side of www folder and wemp server only working inside www directory .If you want to upload image on desktop or any other folder out side www folder same Condection apply No Uploading Done You Get An Error.
<?php
if(isset($_GET['kode'])){
$id = (int) $_GET['kode'];
$sql = "select * from anidata where id='$id'";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0 ){
$data = mysql_fetch_array($query);
//delete file
$path = 'upload/'.$data['image'];
#unlink($path);
//delete from database
mysql_query("delete from anidata where id='$id'");
}
}
header("Location: view.php");
?>
use unlink($path); instead of #unlink($path);

how to delete a file from a subfolder within a folder using php

I have to delete a file from the database and also to delete the file from the folder which is stored in server as files(folder)/newsletter(subfolder)/file1 using php.Iam using following code,the file is deleting from the database,but its not deleting from the folder,..plz help,thanks in advance.
my code is..
<?php
$id = intval($_REQUEST['id']);
include 'db/connection.php';
$sql1 = mysql_query("select * from newsletters where id=$id");
$results = mysql_fetch_array($sql);
if ($results["file"] != "") {
$image = $results["file"];
unlink('../files/newsletter/' . $image);
}
$sql = "delete from newsletters where id=$id";
$result = #mysql_query($sql);
if ($result) {
echo json_encode(array('success' => true));
} else {
echo json_encode(array('msg' => 'Some errors occured.'));
}
?>
Take care of this path "../files/newsletter/" should mention correct path and if your server is ubuntu based then change permissions to files ,newsletter folders.

deleting image from the storage folder in php

I want to delete the image from the storage folder at the time of deleting from the database also.
The image file is getting deleted from database but unable to delete from server storage folder.
The image is getting stored in http://url.com/foldername/files/newsletter
The below is the code i used..
<?php
$id = intval($_REQUEST['id']);
include 'db/connection.php';
$sql1 = mysql_query("select * from tablename where id=$id");
$results=mysql_fetch_array($sql1);
if($results["file"]!="") {
$image=$results["file"];
unlink("../files/newsletter/".$image);
}
$sql = "delete from tablename where id=$id";
$result = #mysql_query($sql);
if ($result){
echo json_encode(array('success'=>true));
} else {
echo json_encode(array('msg'=>'Some errors occured.'));
}
?>
Plz help in resolving..Thank you
try to add document root with your code to something like code below.
$imageWithPath = $_SERVER['DOCUMENT_ROOT']."/files/newsletter/".$image;
#unlink($imageWithPath);
Can you print out what your $results["file"] value is and check.
You are using mysql_fetch_array it should be inside while loop
$sql1 = mysql_query("select * from tablename where id=$id");
while($row = mysql_fetch_array($sql1)){
$image = $row["file"];
//make sure below path is correct.
$image_path = $_SERVER['DOCUMENT_ROOT'].'/foldername/files/newsletter/'.$image;
echo $image_path;//you can compare if the path is correct or not
//Also check if file exists here
if(file_exists(image_path)){
unlink($image_path);
}
else{
echo 'file doesnot exist';
}
}
Also you will need to have permissions to be able to delete the file. Make sure the apache or user that runs your script file have correct permission or ownership of the file.

PHP permission Denied using unlink and rmdir

i've been trying to figure out why my Php code is giving me a annoying error. I've tried countless functions from previous post but the error its been giving is "Permission Denied". From my understanding either i have to have special privledges to delete files, etc.. I've tried multiple solutions but I'm still getting this error. If anyone can point me in the right direction, that'll be great. Ive post a snippet of my code below.. Thanksss
$first_sub = "my_dir";
if(is_dir($first_sub)){
$read_sub1 = opendir($first_sub);
while(false !== ($files = readdir($read_sub1))){
if($files!="." && $files!=".."){
unlink($first_sub ."/". $files);
}
}
closedir($read_sub1);
You should set proper permission to your server directories:
Visit: http://bd1.php.net/chmod
<?php
// Read and write for owner, nothing for everybody else
chmod($first_sub ."/". $files, 0600);
// Read and write for owner, read for everybody else
chmod($first_sub ."/". $files, 0644);
// Everything for owner, read and execute for others
chmod($first_sub ."/". $files, 0755);
// Everything for owner, read and execute for owner's group
chmod($first_sub ."/". $files, 0750);
?>
just before unlink you can call this function.
I got that an error from unlink permission denied.
But I fix it. The error displays like this unlink(../foldername/) Permission denied.
My wrong code is like this:
$image = select_table('webpage', 'wp_name', '$id');
$update = "UPDATE webpage SET wp_image = NULL, wp_modifiedby = '{$position}', wp_datemodified = '{$date_now}' WHERE wp_name = '{$id}'";
if ( unlink('../webpage/'.$image_dir) && $qry_update = mysqli_query($connection, $update) ) {
// success
} else {
// failed
}
now i fix it
my correct code is like this:
$image = select_table('webpage', 'wp_name', $id);
$update = "UPDATE webpage SET wp_image = NULL, wp_modifiedby = '{$position}', wp_datemodified = '{$date_now}' WHERE wp_name = '{$id}'";
if ( unlink('../webpage/'.$image['wp_image']) && $qry_update = mysqli_query($connection, $update) ) {
// success
} else {
// failed
}
For those who land on this page, it may be as simple as not setting $files to an existing file.
It is unfortunate, but I found that the message: Warning: move_uploaded_file(): Unable to move can also mean file not found.
Not likely the cause of this OP's problem, but certainly worth verifying the file represented by the variable you pass actually exists in the directory.

PHP unlink function help

I wrote a PHP script to delete files selected in a gridview. This is the first time I've done this. The script works fine on my local development machine but I don't know if this is the proper way to do it. I'd like to find out what possible problems can I run into when deleting files and how can I modify this to prevent problems.
I was looking at this page to get the basic idea: http://www.php.net/manual/en/function.unlink.php
<?php
// get required includes
require_once(ROOT_PATH.'user/controls/snippets/error_messages.php');
require_once(ROOT_PATH.'user/controls/accordion/get_user_name.php');
// ------------------------------------------------------------
// DELETE SELECTED FILES
// ------------------------------------------------------------
if(isset($_POST['delete_file']) && isset($_POST['checked2']))
{
$checked = array_map('intval',$_POST['checked2']);
$delete_list = implode(", ", $checked);
// DB: get file names to delete
$get_file_names = mysqli_query($conn, "SELECT FileName FROM downloads WHERE DownloadId IN ($delete_list) AND UserName = '$user_name'")
or die($dataaccess_error);
// delete files from server
while($row = mysqli_fetch_array($get_file_names))
{
$dir = DOWNLOAD_DIRECTORY;
$file_name = $row['FileName'];
$file_to_delete = $dir.$file_name;
unlink($file_to_delete);
}
// DB: delete selected file references from db
$delete_selected = mysqli_query($conn, "DELETE FROM downloads WHERE DownloadId IN ($delete_list) AND UserName = '$user_name'")
or die($dataaccess_error);
if(mysqli_affected_rows($conn) > 0)
{
$effected_rows = mysqli_affected_rows($conn);
echo "<div class='msgBox2b noBorder'>SUCCESS: ($effected_rows) FILE(S) have been DELETED..</div>";
}
}
elseif(isset($_POST['delete_file']) && !isset($_POST['checked2']))
{
echo $msg_error;
}
?>
Thank you!
Edit: Would it be better this way?
$fh = fopen($file_to_delete, 'w') or die($failed_to_open_file);
fclose($fh);
unlink($file_to_delete);
Not all files can be unlinked because of permissions, so check the return value of that call.

Categories