I try to unlink an image in CodeIgniter, but the unlink function shows:
notice Undefined index: userfile
Here is my code
<?php
function get_from_post(){
$data['logo_name'] = $this->input->post('logo_name',TRUE);
$data['logo_thumb'] = $_FILES['userfile']['name'];
return $data;
}
function deleteconf($data){
$data= $this->get_from_post();
$update_id=$this->uri->segment(3);
#unlink(base_url.'image/logo_thumb'.$logo_thumb);
$query= $this->_delete($update_id);
}
?>
the unlink function shows notice Undefined index: userfile
The upload form, using multipart/form-data
Make sure you've use enctype="multipart/form-data" attribute/value for your upload form.
<form action="" method="post" accept-charset="utf-8" enctype="multipart/form-data">
From the MDN:
enctype
multipart/form-data: Use this value if you are using an <input>
element with the type attribute set to "file".
If you're going to use CodeIgniter form helper, you could use form_open_multipart() function:
This function is absolutely identical to the form_open() tag above
except that it adds a multipart attribute, which is necessary if you
would like to use the form to upload files with.
Deleting files, File path vs URL address
PHP unlink() function accepts the Path of the file as the first argument. Not the URL Address.
The base_url() helper function returns the URL address of the site, which you've set in the config.php file.
You'll have to use the path of the file on your server, as follows:
unlink('/path/to/image/image_name.jpg'); // This is an absolute path to the file
You could use an Absolute or Relative path, but note that the relative path is relative to the index.php file. i.e. If the image/ folder is placed beside index.php file, you should use image/image_name.jpg as the file path:
unlink('image/image_name.jpg'); // This is a relative path to the file
If you want to upload a photo for user profile and also
at the time the old user photo should be deleted by
using unlink method in codeignitor
$query = $this->db->where('profile_id',$profile_id)->get('users')->row();
$result = $query->photo;
$result = http://localhost/abc/user_photo/FE12563.jpg
if ($result) {
$dd = substr($result, strlen(base_url()));
unlink($dd);
return $this->db->set('photo',$photo)->where('profile_id',$profile_id)->update('users');
}
First check your file input name. Is it "userfile" or not?
if not then add it and then run it once again.
function get_from_post(){
$filename = $_POST['logo_name'];
$path = $_SERVER['DOCUMENT_ROOT'].'/projectname/uploads/'.$filename ;
if(is_file($path)){
unlink($path);
echo 'File '.$filename.' has been deleted';
} else {
echo 'Could not delete '.$filename.', file does not exist';
}
}
base_url() function returns url of you project but here you have to use directory path of file which you want to delete.
$path = BASEPATH.'/assets/upload/employees/contracts/';
$get_file = $path.$con_id.'.jpg';
if(file_exists($get_file)){
unlink($get_file);
}
instead of unlink(base_url("/assets/upload/employees/contracts/'.$con_id."));
First unlink function work only with path (without url), so please remove base_url() function.
Then in your first function $_FILES array doesn't contain userfile index, that's why getting error.
NOTE:- Before using unlink i would like to use also file_exists() function, first it will check if file is exist on same path then use unlink function (for error handling).
Like that -
<?php
if(file_exists(filePath))
{
unlink(filePath);
}
?>
Please fix both issue.
Thanks
Suppose you have the file name in the database and your file is abc.jpg. Then to unlink that in Code Igniter just do -
$file = "abc.jpg";
$prev_file_path = "./assets/uploads/files/".$file;
if(file_exists($prev_file_path ))
unlink($prev_file_path );
My file upload path is "public_html/assets/uploads/files/". I am writing the above code in my controller which is "public_html/application/controllers/MyController.php". So the path will be same which I used in my CI file upload section. i.e.
...
$config['upload_path'] = './assets/uploads/files';
...
So we used relative path in both the upload and unlink section. So if the upload works perfectly then this will also work perfectly.
You can do like this, you need to get first the path of directory from where you have uploaded your image.
Exemple:
//this is your url
$mainPath='https://google.com/uploads/image/16.jpeg';
$uploadedDirectory=str_replace("https://google.com/","./", $mainPath);
//now you get path like this ./uploads/image/16.jpeg
if(unlink($uploadedDirectory)) {
$this->db->where('prodId',$id);
$this->db->delete('products');
}
$this->load->helper("file");
just add above line before unlink
unlink($path);
Can you please use this code to remove image on folder.
unlink(realpath('uploads/' . $_image));
"uploads" : Image exist in uploads folder.
"$_image" : Image file name
PHP functions:
1 : unlink()
2 : realpath()
The above code successfully working on my site to delete image on folder.
try this code
unlink(base_url().'/image/logo_thumb'.$logo_thumb);
Note: You didn't assign / declare $logo_thumb in your deleteconf().
Please check your code.
Related
I have a function that will upload product images to dropbox after an order has been made in my website.
I customize the path name to :
$dropBoxRoot = '/Comp#'.$user['company_id'].'/Prop#'.$user['object_id'].'/Order#'.$orderId.'/'.$product;
I checked if the said path has existed by using the getDelta function.
//let's assume $this-client has already instantiated
$checkIfFolderExist = $this->client->getDelta(null, $dropBoxRoot);
After that, I uploaded that image by doing this:
//the actual path : /Comp#119/Prop#5/Order#120/Product1/image.png
$this->client->uploadFile($dropBoxRoot.'/'.$fileName, WriteMode::add(), $file, $size);
The image is uploaded in the dropbox. I can see it there inside the path but after uploading, the uploadFile function returns an exception:
(1/1) InvalidArgumentException
'path': bad path: must start with "/": "image.png"
in Path.php (line 141)
If anyone has the same situation, I would like to ask your advices. Thanks in advance!
I just found out that it will return the error if the path parameter is concatenated.
In uploadFile function, I made it like this:
$dropBoxRoot.'/'.$fileName
So I make a new variable to concatenate the final path:
$finalPath = $dropBoxRoot.'/'.$fileName;
$this->client->uploadFile($finalPath, WriteMode::add(), $file, $size);
And so it returns without the exception this time.
I would to create a program that upload a file and whatever it is inside the file i would output it through the use of the textarea. But my problem is I can't get the full path of the uploaded file due to security of the browser. I tried using this How to get the path of a file before its uploaded? as a reference but it only show the fakepath. Main problem is I can't get the full path to store it in a variable. Any idea how to do this?
Im using this code to get the file name
<?php
if(isset($_POST['btnSubmit']))
{
$fileName = $_POST['file'];
$fullPath = (realpath).$fileName;
--here there must be a variable that will hold the fullpath but the $fullPath is wrong way to declare.
echo $fullPath."\n\n";
}
?>
I am having a problem with move_uploaded_file().
I am trying to upload a image path to a database, which is working perfectly and everything is being uploaded and stored into the database correctly.
However, for some reason the move_uploaded_file is not working at all, it does not produce the file in the directory where I want it to, in fact it doesn't produce any file at all.
The file uploaded in the form has a name of leftfileToUpload and this is the current code I am using.
$filetemp = $_FILES['leftfileToUpload']['tmp_name'];
$filename = $_FILES['leftfileToUpload']['name'];
$filetype = $_FILES['leftfileToUpload']['type'];
$filepath = "business-ads/".$filename;
This is the code for moving the uploaded file.
move_uploaded_file($filetemp, $filepath);
Thanks in advance
Try this
$target_dir = "business-ads/";
$filepath = $target_dir . basename($_FILES["leftfileToUpload"]["name"]);
move_uploaded_file($_FILES["leftfileToUpload"]["tmp_name"], $filepath)
Reference - click here
Try using the real path to the directory you wish to upload to.
For instance "/var/www/html/website/business-ads/".$filename
Also make sure the web server has write access to the folder.
You need to check following details :
1) Check your directory "business-ads" exist or not.
2) Check your directory "business-ads" has permission to write files.
You need to give permission to write in that folder.
make sure that your given path is correct in respect to your current file path.
you may use.
if (is_dir("business-ads"))
{
move_uploaded_file($filetemp, $filepath);
} else {
die('directory not found.');
}
In my project I have a folder secure in root. The project package looks like:
application
secure
system
...........
Inside secure folder I am uploading some images on form submit using
$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');
and it is working properly. Now while on editing the details, using another form, if I am uploading a new image instead of the current image file, I want to unlink the current one and then upload new file.
For this I am using the code:
unlink(base_url("secure/".$data['row']->videothumbnail));
I also tried with
unlink('/secure/'.$data['row']->videothumbnail);
where $data['row']->videothumbnail) is the current image file from database. New file is successfully uploaded. But old file is not getting unlinked. I have set the permission of secure folder to 777. But the images are uploaded with read only permission. Is it because of this, it is not getting unlinked?
Can anyone help me to solve this?
Thanks in advance.
Try this:
Set the permission dynamically using:
#chmod('./secure/'.$data['row']->videothumbnail, 0777);
then try unlink:
#unlink('./secure/'.$data['row']->videothumbnail);
Try echoing the path that you are providing to unlink function.
It should be something like this:
base_url()."secure/".$data['row']->videothumbnail;
I also had this issue even after setting the right permission on the folder. But the following code worked for me.
unlink(realpath(APPPATH . '../uploads').'/'.$ImageName);
Try to use $_SERVER['DOCUMENT_ROOT'] instead of base_url
$this->load->helper("file")
unlink(base_url('folder/file.ext'));
location:
\app\controller
\system\libraries
**folder\file.ext**
$unlinkUrl = "secure/".$data['row']->videothumbnail;
if(file_exists($unlinkUrl)){
unlink($unlinkUrl);
}
else{
echo $unlinkUrl." is not available";
}
I think you are just making a stupid mistake.
Firstly, the first param of unlink should be a relative path or absolute path, but base_url function will return you a path contains domain name, HOW CAN YOU DELETE A FILE ON REMOTE SERVER ?
Secondly, '/secure/'.$data['row']->videothumbnail here is not a relative path but a absolute path
YOU MUST change it into /the/absolute/path/to/secure/ or ./the/relative/path/to/secure/ (DO NOT MISS THE DOT)
use this to unlink
$oldthumb = "secure/".$data['row']->videothumbnail;
#unlink($oldthumb);
First Load the $this->load->helper("file") and then unlink it
unlink("secure/".$data['row']->videothumbnail);
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');
}
Though i came in late but someone might need this .
unlink(FCPATH."secure/".$data['row']->videothumbnail)
**FCPATH** - path to front controller, usually index.php
**APPPATH** - path to application folder
**BASEPATH** - path to system folder.
I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);