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.
Related
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.
I am trying to move an image file previously uploaded into a tmp directory to a permament location. I have used this tutorial as a starting point:
maxoffsky.com/code-blog/uploading-files-in-laravel-4/
I have amended the code as I am uploading the files earlier and accessing them later through a url provided by the form. The code below shows what I am doing:
$form_element = "image_1"; // hidden form element containing the tmp location
$tmp_path = $form_data[$form_element]; // gets the tmp url from hidden element
$file = fopen($tmp_path, 'r'); // opens the file
$destinationPath = 'images/adverts/'.$advert->id; // specifies a new folder
$filename = $file->getClientOriginalName(); // retrieves the name of the file
$upload_success = $file->move($destinationPath, $filename); // moves the file to its new location
The problem I am having is that in the tutorial, they use the code:
$file = Input::file('file'); // Laravel syntax for $_POST['file']
This retrieves the file from the html form itself. From there the functions $file->getClientOriginalName() and $file->move() work correctly.
However, in mine, as my form doesnt provide an actual file, just a link to one, I am trying to access the file and perform the same operations, however I get this error:
Call to a member function getClientOriginalName() on a non-object
I dont think that fopen() is returning the same type as $_POST['file'] hence it isnt working.
How can I make my code work?
Many thanks
I had the same issue, just add in the Form::open in array the enctype:
enctype='multipart/form-data'
and your problems are solved! I have forgotten it and banging my head to the wall after that I started harder to bang it when I saw it.
PS. You have a little misconception. Input::file('file') it's not syntax for $_POST['file'], but for $_FILES['file']
Given this one a few hours research and thought but I'm not getting anywhere.
I have managed to get an image file to upload through AJAX using a FormData object. When the file reaches the php code I am able to access its info such as 'name' and 'type' by using:
$_FILES['newFile']['name'];
$_FILES['newFile']['type'];
And so on, which means that the file must be uploading as intended, I just can't seem to save it to a file from there.
I have tried:
$file = file_get_contents($_FILES["newFile"]['tmp_name']);
imagejpeg($file, '/img/uploads/' . $_FILES["newFile"]['name']);
But then imagejpeg gives me the error "Expects paramater1 to be resource, string given."
So I tried:
$file = imagecreatefromstring(file_get_contents($_FILES["newFile"]['tmp_name']));
imagejpeg($file, '/img/uploads/' . $_FILES["newFile"]['name']);
I now receive the error: /"imagejpeg('/img/uploads/image.jpg'): Failed to open stream. No such file or directory."
Can someone explain how I get the image from the array to a file on disk?
You have to use the move_uploaded_file function like this:
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"], $pathfilename)
Use php function move_uploaded_file("$_FILES['newFile']['tmp_name']","Location_where_you_want_to_save");
Figured it out! Obviously "/img/uploads/" was the issue. PHP doesn't recognize a forward slash as the root directory! My fault!
move_uploaded_file($_FILES["newFile"]['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/img/uploads/' . $_FILES["newFile"]['name']);
Using $_SERVER['DOCUMENT_ROOT'] before the new file path worked perfectly.
I'm trying to upload some photos and handle this with the build in Laravel functions. But I can't for the life of me figure out how to do this properly. I have been able to actually upload something, but I've run into a few problems. This is the code I have right now:
If looked at the documentation, and found this function: $file = Input::file('photo'); I've used this function, and what the content of $file becomes is an instance of Symfony\Component\HttpFoundation\File\UploadedFile, which, as the documentation tells us, "extends the PHP SplFileInfo class and provides a variety of methods for interacting with the file." http://laravel.com/docs/4.2/requests#files
Then I used this function Input::file('photo')->move($destinationPath); which should but the file in the desired folder on the server. And it did. But now comes the problem. Now all uploaded files have a filename like phpgoJnLc, and without an extension.
I've looked at the functions available from SplFileInfo and tried getExtension which give me an empty string and getFilename which also gives me something like phpgoJnLc.
Then I looked around on the internet and found a few part of code from Laravel 3, where they did something like this:
$filename = Str::random(20) .'.'. File::extension(Input::file('photo.name'));
But the result of this is give me only the result from Str::random(20) followed by a dot. Again, no file extension.
So, what am I doing wrong? How to upload a file with Laravel 4?
Looking in that same class file I see a getClientOriginalName() function...
$file = Input::file('photo');
$file->move($destinationPath,$file->getClientOriginalName());
... which ais ssuming you want to keep the original name your client sets... which could be hazardous, do some safety checks on it would be my advice. Getting the extensionname only is done with ->getClientOriginalExtension(), so you could also only save that part & add a random string before that in the second argument of the move() function.
This worked for me, especially when you want to change the name of the uploaded image:
$filename = 'New_Name'.'.'.Input::file('photo')->getClientOriginalExtension();
You can also generate a name for the file with the original file extension like so:
$filename = Str::random(20) . '.' . Input::file('image')->guessExtension();
if you try to use the following in Laravel 4:
$filename = Str::random(20) .'.'. File::extension(Input::file('photo.name'));
you will get this error:
'Call to undefined method Illuminate\Filesystem\Filesystem::guessExtension()'
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);