'How to unlink image?

im using modal bootstrap with codeignitter 4. I can delete the data in database but cannot unlink the image. here my code :

Model :

public function deleteProduct($id)
{
    $query = $this->db->table('produk')->delete(array('kode' => $id));
    return $query;
}

Controller :

 public function delete()
{
    $model = new produkModel();
    $id = $this->request->getPost('kode');
    $produk = $this->produkModel->find($id);
    
    if ($produk['gambar'] != 'default.png') {
      
        unlink('imgproduk/' . $produk['gambar']);
    }
    $model->deleteProduct($id);
    return redirect()->to('/Tabel_Produk');
}

i want to delete the image in directory but dont delete the default.img



Solution 1:[1]

Use complete folder path to delete/access image through PHP by using $_SERVER['DOCUMENT_ROOT'] to get server path.

 public function delete(){
    $model = new produkModel();
    $id = $this->request->getPost('kode');
    $produk = $this->produkModel->find($id);
    
    if ($produk['gambar'] != 'default.png') {
      
        unlink($_SERVER['DOCUMENT_ROOT'].'/imgproduk/' . $produk['gambar']);
    }
    $model->deleteProduct($id);
    return redirect()->to('/Tabel_Produk');
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Farhan