How delete file and image after upload from codeigniter??

by haylee.mertz , in category: PHP Frameworks , 10 months ago

How delete file and image after upload from codeigniter??

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 10 months ago

@haylee.mertz 

To delete a file and image after uploading it using CodeIgniter, you can use the unlink() function in PHP.


First, make sure you have the file path and filename. Assuming you have stored the file path and name in a variable called $file_path, you can use the following code to delete the file:

1
2
3
4
5
6
7
8
$file_path = 'path/to/file.jpg'; // Replace with your actual file path

if (file_exists($file_path)) {
    unlink($file_path); // Delete the file
    echo 'File deleted successfully.';
} else {
    echo 'File does not exist.';
}


You can place this code in your controller or model after the file upload process is completed. Make sure to replace 'path/to/file.jpg' with the actual path and filename of the uploaded file.


If you want to delete the image from the database as well, you should have stored the file information or its ID in the database during the upload process. You can retrieve the file information from the database and use the same unlink() function to delete the file from the server.


Here's an example assuming you have stored the file ID in a variable called $file_id:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
$file_id = 1; // Replace with your actual file ID

// Retrieve the file information from the database
$file = $this->db->get_where('files', array('id' => $file_id))->row();

if ($file) {
    // Delete the file from the server
    $file_path = $file->path;
    if (file_exists($file_path)) {
        unlink($file_path); // Delete the file
        echo 'File deleted successfully.';
    } else {
        echo 'File does not exist.';
    }

    // Delete the file information from the database
    $this->db->where('id', $file_id);
    $this->db->delete('files');
    echo 'File information deleted from the database.';
} else {
    echo 'File does not exist in the database.';
}


Again, make sure to replace the database table name ('files') and column names ('id', 'path') with your actual table and column names.