deleting file with unlink function php - 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);

Related

Update file in database and upload file

thank you in advance for your help, i need to make a system were i can upload and update a file into my database record. To do so i made this code but for some reason i cant seem to see what i have done wrong i can update the "status and so on" but the file is not uploaded into my desired directory and the record is missing in my database too, so all the rest works just fine, except the file itself, does not get updated. Here is my code, again thanks in advance!
<?php
if(isset($_POST['submit_btn']))
{
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
require 'modules/conn.php';
$target = "../account-files/";
$target = $target . basename( $_FILES['Filename']['name']);
}
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id ='".$_POST['id']."', status ='".$_POST['status']."', counts ='".$_POST['counts']."', Filename ='".$_POST['Filename']."' WHERE id = '".$id."'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
?>
Everything else gets updated in my database, but as i said, the file and the record of the file name does not, also its not uploaded into my directory. Please help me, an example would be very much appreciated.
Updated code i can get the records into the database but still no upload into the directory.
$target = "../account-files/";
$target = $target . basename( $_FILES['Filename']['name']);
if(isset($_POST['submit_btn']))
{
move_uploaded_file($_FILES['Filename']['tmp_name'], $target);
require 'modules/conn.php';
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id = $id, status = '$status', counts = $counts , Filename = '$Filename' WHERE id = '$id'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
This last solution is correct i hope i can contribute also to other members, see solution credits bellow at the correct reply to my post, that guy rocks! Thumbs up so what was the error? Simple, the path i had was wrong...
this one is wrong:
$target = "../account-files/";
This is correct and fixes all
$target = "account-files/";
Do you really have the POST['Filename']? I think you should put the variables in you query instead of .POST
Try the code below:
if(isset($_POST['submit_btn']))
{
$target_dir = "../account-files/";
$target_file = $target_dir . basename( $_FILES['Filename']['name']);
move_uploaded_file($_FILES['Filename']['tmp_name'], $target_file);
require 'modules/conn.php';
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id = $id, status =
'$status', counts = $counts , Filename = '$Filename' WHERE id =
'".$id."'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
And also please make sure that you have the enctype="multipart/form-data" on your form tag.
You make some mistakes:
how you can upload the file first and then determine the target
why are you updating id? while id is its primary key
i
if(isset($_POST['submit_btn'])){
$target = "../account-files/";
$fname = $_FILES['filename']['name'];
if(!empty($target) && !empty($fname)){
move_uploaded_file($_FILES['filename']['tmp_name'], $target.$fname);
}
}

Deleting file from folder

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
}

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 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