Unable to remove file in CodeIgniter

Within the structure of my project, there is a directory labeled secure located in the root. The overall package of the project appears as follows:

application 
secure
system 
...........

Images are being uploaded inside the secure folder upon form submission using the following code snippets:

$config1['upload_path'] = './secure/';
$ext = end(explode(".", $_FILES['thumb_image']['name']));
$config1['file_name'] = time().$_FILES['thumb_image']['name'];
$config1['allowed_types'] = 'jpg|png|jpeg|gif|bmp|jpe|tiff|tif';
$this->load->library('upload', $config1);
$this->upload->initialize($config1);
$this->upload->do_upload('thumb_image');

The upload functionality works correctly. However, when attempting to edit details through another form and replacing the current image file with a new one, I aim to unlink the existing file before uploading the new one.

To achieve this, I have implemented the following code:

unlink(base_url("secure/".$data['row']->videothumbnail));

I have also tried:

unlink('/secure/'.$data['row']->videothumbnail);

where $data['row']->videothumbnail) represents the current image file stored in the database. While the new file uploads successfully, the old file remains intact and does not get unlinked. I have ensured that the permissions for the secure folder are set to 777. Could it be possible that the issue lies with the read-only permission set on the uploaded images preventing them from being unlinked?

If anyone could offer guidance on how to resolve this issue, I would greatly appreciate it.

Thank you in advance.

Answer №1

Give this a shot:

Adjust the permission dynamically with:

@chmod('./secure/'.$data['row']->videothumbnail, 0777);

After that, attempt to unlink:

@unlink('./secure/'.$data['row']->videothumbnail);

Answer №2

Consider incorporating the path you intend to unlink into the echo function.

Here's a suggestion:

echo base_url()."secure/".$data['row']->videothumbnail;

Answer №3

After ensuring that the folder permissions were correct, I encountered a similar problem. However, I was able to resolve it by using the code below:

unlink(realpath(APPPATH . '../uploads').'/'.$ImageName);      

Answer №4

Consider using $_SERVER['DOCUMENT_ROOT'] in place of base_url

Answer №5

$this->load->helper("file") 
unlink(base_url('folder/file.ext'));

location:

\app\controller

\system\libraries

**folder\file.ext**

Answer №6

$fileToDelete = "secure/".$info['row']->videothumbnail;
if(file_exists($fileToDelete)){
    unlink($fileToDelete);
}
else{
    echo $fileToDelete." cannot be found";    
}

Answer №7

It appears that a careless error has been made in your code.

  • To start, when using the unlink function, the first parameter should be either a relative or absolute path. However, by using the base_url function, you are getting a path that includes the domain name. This will not allow you to delete a file on a remote server.

  • Additionally, the path

    '/secure/'.$data['row']->videothumbnail
    is an absolute path, not a relative one.

Make sure to correct this by changing it to either /the/absolute/path/to/secure/ or ./the/relative/path/to/secure/ (DO NOT FORGET THE DOT)

Answer №8

utilize this to remove the link

$oldthumb = "secure/".$data['row']->videothumbnail;
@unlink($oldthumb);

Answer №9

Step one: Begin by loading the helper with

$this->load->helper("file")
, then proceed to unlink it.

unlink("secure/".$data['row']->videothumbnail);

Answer №10

if ($rowAffected > 0) {
                if ($isMediaUpload)
                    if (file_exists('./uploads/' . $this->input->post('img_url')))
                        unlink('./uploads/' . $this->input->post('img_url'));
                            redirect('/admin/configration', 'location');
            }

Answer №11

Even if I may have missed the original post, there could still be someone who finds this information useful.

unlink(FCPATH."secure/".$data['row']->videothumbnail)

**FCPATH** - refers to the path leading to the front controller, typically index.php
**APPPATH** - points to the application folder
**BASEPATH** - denotes the system folder.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve N records from the database for each ID in an array using Codeigniter

Looking for some assistance here after spending two days searching. My goal is to send an array of user ids to a CI model and retrieve the last 10 transactions for each id. I have been able to limit the total number of records, but I am struggling to figu ...

How can a backslash "" be added in Php using regex?

My goal is to insert a backslash "\" before all non-alphanumeric characters like "how are you \:\)". To achieve this, I attempted the following: $code = preg_replace('/([^A-Za-z0-9])/i', '\$1', $code); Unfortunatel ...

Send image data in base64 format to server using AJAX to save

My goal is to store a base64 image on a php server using the webcam-easy library (https://github.com/bensonruan/webcam-easy). I added a button to the index.html file of the demo: <button id="upload" onClick="postData()" style=" ...

Setting an if condition for JSON data being transmitted to an Android device through PHP involves establishing a conditional statement to handle

I am currently working on a PHP file that retrieves data from a MySQL database and sends it to an Android application as a JSON array. At the moment, all rows are being sent to the app, but I only want to send rows where the approved value is equal to 1. H ...

Having trouble retrieving JSON values from the AJAX success function in my CodeIgniter application

Hey everyone, I'm facing a simple error that's giving me a hard time. No matter what I do, I can't seem to access the JSON values in my code. Whenever I try to alert after parsing the JSON, it just shows me 'undefined'. Can anyone ...

wordpress the_content() is not displaying within the correct div container

I'm attempting to display category posts in the registered widget area using the following code snippet: function category_post_shortcode($atts){ extract( shortcode_atts( array( 'title' => '', 'link& ...

Display the variable on the document by clicking the button

Hello, I'm new here so please forgive me if I make any mistakes. I am working with the following PHP code: <?php $quoteFile = "quotes.txt"; //Store quotes in this file $fp = fopen($quoteFile, "r"); //Open file for reading $content = fread ...

PHP is unable to receive data from ajax requests

My goal is to detect which reply button I click and send its index to a PHP script. In jQuery: $(".reply").each(function (index5) { $(".reply_button").each(function (index_b) { if(index_b==index5){ $(this).on("click",functio ...

having difficulty showing the primary content page

I'm having trouble displaying a header, side navigation bar, and main content on my page with the code below. Instead of showing anything, I keep getting a parse error: unexpected end of file. What could be causing this issue? <!doctype html> ...

Guide on passing variable information within a single webpage using PHP PDO?

Currently, I am implementing pagination for a table containing approximately 1500 rows. $numperpage = 50; $countsql = $connect->prepare("select COUNT(id) from prana"); $countsql->execute(); $row = $countsql->fetch(); $numrecords = $row[0 ...

Tips for using a fluent interface to apply a method to all data member variables simultaneously

I have a class structured as follows: class example{ private $foo = array(); private $bar = array(); public function getFoo(){ return $this->foo; } public function getBar(){ return $this->bar; } //fo ...

PHP contact form not properly sending complete submission data

I'm facing an issue with my HTML contact form that utilizes JavaScript for a change function. Essentially, I have a dropdown menu for different subjects, and based on the selected option, specific fields should appear. However, when a user fills out t ...

How can one obtain a distinct identifier retroactively?

One thing that I am working on is changing button images upon clicking, but this isn't the main issue at hand. Each button corresponds to unique information retrieved from the database, and when clicked, the button should change and send the appropria ...

Even after calling session_destroy(), session variables persist

session_start(); $_SESSION['user'] = "789456"; $_SESSION['name'] = "dummy"; $_SESSION['id'] = "123"; print_r($_SESSION); session_destroy(); echo "Session End"; print_r($_SESSION); The following is the output I am getting: Ar ...

Experiencing a 500 internal server error while making an Ajax post request

I keep receiving a 500 internal server error when making an ajax post request. I am currently testing it on localhost and have verified that my route is correct. In the route I created for this call, I did not include the controller name and method in the ...

Removing leading zeros from numeric strings in JSON data

I am facing an issue with my jQuery-based JavaScript code that is making an Ajax call to a PHP function. updatemarkers.xhr = $.post( ih.url("/AjaxSearch/map_markers/"), params).done( function(json) { <stuff> } The PHP function returns the follo ...

Tips for splitting the json_encode output in Javascript

Looking for help with extracting specific values from JSON data retrieved via PHP and AJAX. I only want to display the agent name in my ID, not the entire object that includes "name" : "Testing". Here is the console output: [{"agent_module_id":"1","agen ...

What is the method for altering the date format of a published article?

I am looking to modify the date format of a published post in WordPress. Currently, the date format is <?php the_time('m.d.y'); ?></div>, which appears as "1.20.2018". My goal is to change it to "January 20, 2018". Can anyone guide ...

In PHP, the symbol "!=" is used to compare if a string is not equal to a

Seeking feedback on why setting a string variable prevents me from calling it within a function. For instance: $name = "name"; $quote_name = "'".$name."'"; //echo of $name = name //echo of $quote_name = 'name' In PHP, I encounter iss ...

The session's stored username will be modified if the variable $username is utilized

Initially, Script 1 is designed to send a username and password as a POST request in order to input data into a separate database (not directly related to the login system but used by an external program). Following this, Script 2 executes the following co ...