Codeigniter - unlink delete file not working - php

I have a problem with unlink or delete file with codeigniter
Here is my controller
function delete($id_post=''){
$this->home_model->delete($id_post);
$this->session->set_flashdata('danger', "Your photo has been deleted...");
redirect("home");
}
And this is my model
function delete($id_post=''){
$file_name = $this->db->query("SELECT doc FROM post WHERE post.id_post='$id_post'");
unlink(base_url("uploads/" . $file_name));
$sql = "DELETE FROM post WHERE id_post=?";
$outp = $this->db->query($sql,array($id_post));
}
Doc is the name of column that contain image.
If i click button delete, it delete a data in database and works successfully but not the image in file folder. I want, when i delete a data it is also delete image in file folder uploads. Uploads folder is in the root aplication system.
Any answer?
Many thanks...

The query() function returns a database result object. So replace your model code with:
function delete($id_post=''){
$file_name = $this->db->query("SELECT doc FROM post WHERE post.id_post='$id_post'");
$row = $file_name->row();
$file_name = $row['doc'];
unlink(base_url("uploads/" . $file_name));
$sql = "DELETE FROM post WHERE id_post=?";
$outp = $this->db->query($sql,array($id_post));
}

Try this:
$this->load->helper("url");
unlink(base_url("uploads/" . $file_name));

function delete($id_post=''){
$file_name = $this->db->query("SELECT doc FROM post WHERE post.id_post='$id_post'");
$res = $this->db->result(); // this returns an object of all results
$row = $res[0];
$filename = $row['doc']; // get the file name from array
// do the delete after getting the filename
}

Instead of this
$file_name = $this->db->query("SELECT doc FROM post WHERE post.id_post='$id_post'");
please replace this
$file_name = $this->db->query("SELECT doc FROM post WHERE post.id_post='".$id_post."'")->row()->doc;

This is because you does not fetch your result resource.
Use:
$query = $this->db->query("SELECT doc FROM post WHERE post.id_post='$id_post'");
$row = $query->result();
$file_name = str_replace('localhost/latihan/uploads/','',$this->db->query("SELECT doc FROM post WHERE post.id_post='".$id_post."'")->row()->doc);
unlink("uploads/" . $file_name);

can use this using directory path
unlink(FCPATH.'uploads/yourfile');

You are trying to delete your file with URL address you have to specifiy local document address like this:
unlink($_SERVER['DOCUMENT_ROOT']."uploads/".$filename);
here is similiar question:
Cannot unlink file in Codeigniter

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);
}
}

downloaded file cannot open(damage) codeigniter

i have a file with extension PDF and DOCX, and when i download it from my server, the file cannot opened and the size become 1kb, when in my server folder it has 199kb size. iam using database to store the file path and filename, here is my view to download the file
View
<?php echo $details->FILE_NAME; ?>
and my controller
Admin_Controls.php
function download_proposal($id_pemesanan) {
$this->load->helper('download');
$this->load->model('gedung/gedung_model');
$temp_id = substr($id_pemesanan, 7); //i cut the string because it content prefix string
$data = $this->gedung_model->get_proposal_by_id($temp_id);
$path = file_get_contents($data->PATH.$data->FILE_NAME);
$file_name = $data->FILE_NAME;
force_download($file_name, $data);
}
my model
Gedung_Model.php
public function get_proposal_by_id($id_pemesanan) {
$sql = "SELECT * FROM pemesanan_details WHERE ID_PEMESANAN = $id_pemesanan";
$query = $this->db->query($sql);
$hasil = $query->row();
return $hasil;
}
my problem is just after i download the file, it becomes corrupted and cannot open, like i say the size become 1kb. all works well from user click to download until the download process
Thanks in advice
I would like to check the path . You can use absolute path of the file for testing purpose instead of dynamic generated path .

PHP Delete file

I am trying to develop a user page for a forum and I'm kinda struggling with the image upload.
The problem is that I would like to limit the user to only be able to upload one single image, but be able to change it anytime. so basically, I would like to either overwrite the existing file either delete the old picture and add a new one instead.
At this point I have a piece of code that adds a timestamp at the end of the file (which I don't really need actually).
CODE:
if(isset($_POST['upload']))
{
$extension=strstr($_FILES['uploadedfile']['name'], ".");
$filename = "_/userfiles/userpics/".basename($_FILES['uploadedfile']['name'],
$extension);
$target = "_/userfiles/userpics/".basename($_FILES['uploadedfile']['name']);
$valid = true;
if(file_exists($target))
{
$filename = $filename . time();
$target = $filename . $extension;
}
if($valid)
{
// move the file into the folder of our choise
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
$img_sql = "INSERT INTO sp_userimage (imageid, path, id) value ('', '".$target."', '".$_SESSION['userid']."')";
$img_result = mysql_query($img_sql);
echo "upload sucessfull";
}
Make use of unlink() in PHP Manual.
if(file_exists($target))
{
unlink($target); // deletes file
//$filename = $filename . time();
//$target = $filename . $extension;
}
I think this might be a bit better suited for you. You might have to edit it a tad.
if($valid)
{
// Check if user has a file.
$img_check = mysql_query("SELECT * FROM sp_userimage WHERE id = " . (int) $_SESION['user_id']);
if( mysql_num_rows($img_check) > 0 ){
$row = mysql_fetch_object($img_check);
// Delete the file.
unlink($row->path);
}
// move the file into the folder of our choise
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
$img_sql = "INSERT INTO sp_userimage (imageid, path, id) value ('', '".$target."', '".$_SESSION['userid']."')";
$img_result = mysql_query($img_sql);
echo "upload sucessfull";
}
It might be easier to normalize the image type (e.g. only jpegs) and then name the file as the userid. For example:
$target = 'userpics' . DIRECTORY_SEPARATOR . $_SESSION['userid'];
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
This will simply overwrite the old picture with the new one. Given that this type of filename is deterministic, you also don't need to store the filename in the database.
Use unlink() function
read more here PHP unlink
okay ,if u want to delete the file for that particular user only.
then store the filename vs user in some MapTable in db.
mysql_query("CREATE TABLE t_usr_file_map(
usr_id INT NOT NULL ,
file_name VARCHAR(100),
)")
or die(mysql_error());
and at the time of reupload , fetch the filename from the table for that user , unlink it and reupload the fresh one again.
OR,
or u can use PHP file_rename function at the time of upload. rename filename to the userid
rename ( string $oldname , string $newname [, resource $context ] )
and u can always do unlink based on user-id
Its very simple by unlink()
as:
unlink(dirname(__FILE__) . "/../../public_files/" . $filename);
if (file_exists($path))
{
$filename= rand(1,99).$filename;
unlink($oldfile);
}
move_uploaded_file($_FILES['file']['tmp_name'],$filename);

CodeIgniter - error trying to view uploaded pdf files

I'm having difficulty trying to view a pdf file outside of the webroot folder.
This is the view file - I'm grabbing the file id from the URL and then querying the db to get all the file info stored from the upload.
$fid = $_GET['fid'];
$query = $this->db->query("SELECT * FROM files WHERE FID = $fid");
$fileinfo = $query->result();
foreach ($fileinfo as $row)
{
$fname = $row->file_name;
$ftype = $row->file_type;
$fpath = $row->file_path;
$full_path = $row->full_path;
$raw_name = $row->raw_name;
$client_name = $row->client_name;
$file_ext = $row->file_ext;
$file_size = $row->file_size;
$is_image = $row->is_image;
$width = $row->image_width;
$height = $row->image_height;
$img_type = $row->image_type;
$img_size = $row->image_size_str;
$orig_name = $row->orig_name;
$created = $row->created;
}
Then I'm taking that info and passing it to the File_viewer_model using the following:
$this->load->model('File_viewer_model');
$this->File_viewer_model->getFileInfo($fname,$ftype);
The function in the model that receives the data is as follows:
function getFileInfo($fname,$ftype){
$path = '/home/sitename/uploads/' . $fname;
header('Content-Type: ' . $ftype);
header('Content-Length: ' . filesize($path));
readfile($path);
}
The problem is when I click on the link to open a new tab and try to display the file, I get the following error:
File does not begin with '%PDF-'.
The file is in a 777 permissions directory called uploads right outside of the webroot - I've been all over the web and there seems to be several methods to display a pdf file, none of which seem to work for me. Any help would be appreciated. Thanks!
Solved: The problem was I was passing a header_view page in the controller before the $this->load->view('file_viewer_view'); section.
The PDF viewer was trying to parse the header_view first before the header('Content-Type: application/pdf') code in the file_viewer_view and thus generating the error.
I removed everything from the controller before the $this->load->view('file_viewer_view'); and it works like a champ!
Hopefully, this will save someone several hours of banging your head against the wall like I experienced!

Tying in unlink() with sql delete

I have setup a simple while loop which returns all images in a table along with their respective title and description so that users can update the details accordingly for each image.
The images are returned with a checkbox which allows user to delete images as per php code
if($_POST['doDelete'] == 'Delete') {
if(!empty($_POST['u'])) {
foreach ($_POST['u'] as $uid) {
$id = filter($uid);
mysql_query("delete from landscape where id='$id'");
}
}
$ret = $_SERVER['PHP_SELF'] . '?'.$_POST['query_str'];;
header("Location: $ret");
exit();
}
How do I incorporate the unlink() function into the page so that the file is also removed from the server?
Just use Unlink() with in loop like :
foreach ($_POST['u'] as $uid) {
$id = filter($uid);
if(mysql_query("delete from landscape where id='$id'")){
unlink( '/path/to/images/' . $id);
}
}
I have used If because if the file deleted successfully from the database only then it will be deleted from the server.
Also If you have moved the file into folder by the name of file then First get information about file from database by $id and then use
unlink( '/path/to/images/' . $file_name);
instead
unlink( '/path/to/images/' . $id);
Hope it will help you.
If the images are named in accordance with the ID:
foreach ($_POST['u'] as $uid) {
$id = filter($uid);
mysql_query("delete from landscape where id='$id'");
unlink( '/path/to/images/' . $id);
}
Be sure to properly escape $id before using it in your query or in the unlink statement.
Well, where are the files stored on the server? How are they stored? Just call unlink with the file path that leads to where the image is stored.

Categories