Codeigniter 4: Uploading files with move_uploaded_file - php

I just started moving CodeIgniter 3 project to CodeIgniter 4.
Everything works fine except file upload.
I would like to keep the user uploaded files in /writable/uploads. Below is the code I use to move the uploaded file to desired location.
$target_dir = '/writable/uploads/recordings/';
$target_file = $target_dir . basename($_FILES["gfile"]["name"]);
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);
if($FileType != "mp3") {
$vmuploadOk = 1;
}
else
$vmuploadOk = 1;
if ($vmuploadOk == 1) {
$greetfile = $id . "g" . basename($_FILES["gfile"]["name"]);
$target_filenew = $target_dir . $greetfile;
move_uploaded_file($_FILES["gfile"]["tmp_name"], $target_filenew);
}
I assume that it is because CI4 keeps writable folder outside public folder.

You are not using CodeIgniter's built in functions. Everything shown in your code are PHP functions. If you want to leverage built in CI functions, then look through the documentation as linked by #Boominathan Elango.
To get the file from the request:
$file = $this->request->getFile('here_goes_input_name');
As specified here
To move the file using CI function:
$file->move(WRITEPATH.'uploads', $newName);
As specified here

This worked for me and I hope it will also work for you. In codeigniter 4 please use this to upload your files and move it in your controller.
if($imagefile = $this->request->getFiles())
{
if($img = $imagefile['gfile'])
{
if ($img->isValid() && ! $img->hasMoved())
{
$newName = $img->getRandomName(); //This is if you want to change the file name to encrypted name
$img->move(WRITEPATH.'uploads', $newName);
// You can continue here to write a code to save the name to database
// db_connect() or model format
}
}
}
OR
if($img = $this->request->getFile('gfile'))
{
if ($img->isValid() && ! $img->hasMoved())
{
$newName = $img->getRandomName();
$img->move(ROOTPATH . 'public/uploads/images/users', $newName);
// You can continue here to write a code to save the name to database
// db_connect() or model format
}
}
Then in your html input field
<input type="file" name="gfile">
I hope this works else call my attention

Related

PHP move image in AJAX functionality

I have been triggering AJAX funtctionality and part of my function is
private function saveImageOfThePlace()
{
$image_name = $this->json['order']['image_temp']; // phpBDobOY
$ext = $this->json['order']['ext']; // jpg
$full_path = 'wp-content/plugins/WindProofCurtainsCalculator/Temp/'.$image_name.'.'.$ext;
$new_path = 'wp-content/plugins/WindProofCurtainsCalculator/uploaded_images/'.$image_name.'.'.$ext;
if ( file_exists($full_path) ) {
//copy($full_path, $new_path);
unlink($full_path);
}
// move_uploaded_file($_FILES['image']['tmp_name'], plugin_dir_path( dirname( __FILE__, 2 )).$this->json['order']['image']);
return $this;
}
I can see everything else is working correctly, but only I am stuck at this part.
I want to move image to another folder and if anyone can help me will be very thankful!
I tried with your code in my localhost. It's working fine and moves file uploads to uploaded_images directory if the file exists. Also, it will not delete the original if the copy failed.
$file_destination = 'wp-content/uploads/007-team-work 1-min.png';
$file_destination_new = 'wp-content/uploads/uploaded_images/007-team-work 1-min.png';
if( file_exists($file_destination) ) {
if(copy($file_destination, $file_destination_new)) {
unlink($file_destination);
}
}
Make sure your data is correct, try debugging. Make sure your $full_path exist and $new_path folder is exist.

Downloading uploaded file php

I'm new to yii framework and we have a project in school about uploading and downloading files and I kind of need some assistance...
I followed this link as a sample exactly as it is and it really does upload to the uploads folder in yii but now I'm trying to download it using this code in my view:
$id= $_GET['id'];
$media = Document::model()->findByPk($id);
$path = Yii::app()->basePath . '/../uploads';
$name = $media->doc_file;
Yii::app()->request->sendFile($name, file_get_contents($path."/".$name));
but when it downloads, it wont open because the file format is not supported... any idea how I can
I did a little modification on your code. Pass the id through the url on the view and that will hit the download action inside your controller. You should be good to go with this
public function actionDownload($id)
{
$media = Document::model()->findByPk($id);
$path = Yii::app()->request->baseURL . '/uploads';
$file = $path . '/'.$media->doc_file;
if (file_exists($file)) {
return Yii::app()->getRequest()->sendFile($name, #file_get_contents($path));
}else{
//throw an error here
}
}

PHP - Renaming a file to disallow duplicates

So I am using this script to upload a file to a directory and show it live.
<?php
function UploadImage($settings = false)
{
// Input allows you to change where your file is coming from so you can port this code easily
$inputname = (isset($settings['input']) && !empty($settings['input']))? $settings['input'] : "fileToUpload";
// Sets your document root for easy uploading reference
$root_dir = (isset($settings['root']) && !empty($settings['root']))? $settings['root'] : $_SERVER['DOCUMENT_ROOT'];
// Allows you to set a folder where your file will be dropped, good for porting elsewhere
$target_dir = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : "/uploads/";
// Check the file is not empty (if you want to change the name of the file are uploading)
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]);
// If empty name, just return false and end the process
if(empty($filename))
return false;
// Check if the upload spot is a real folder
if(!is_dir($root_dir.$target_dir))
// If not, create the folder recursively
mkdir($root_dir.$target_dir,0755,true);
// Create a root-based upload path
$target_file = $root_dir.$target_dir.$filename;
// If the file is uploaded successfully...
if(move_uploaded_file($_FILES[$inputname]["tmp_name"],$target_file)) {
// Save out all the stats of the upload
$stats['filename'] = $filename;
$stats['fullpath'] = $target_file;
$stats['localpath'] = $target_dir.$filename;
$stats['filesize'] = filesize($target_file);
// Return the stats
return $stats;
}
// Return false
return false;
}
?>
<?php
// Make sure the above function is included...
// Check file is uploaded
if(isset($_FILES["fileToUpload"]["name"]) && !empty($_FILES["fileToUpload"]["name"])) {
// Process and return results
$file = UploadImage();
// If success, show image
if($file != false) { ?>
<img src="<?php echo $file['localpath']; ?>" />
<?php
}
}
?>
The thing I am worried about is that if a person uploads a file with the same name as another person, it will overwrite it. How would I go along scraping the filename from the url and just adding a random string in place of the file name.
Explanation: When someone uploads a picture, it currently shows up as
www.example.com/%filename%.png.
I would like it to show up as
www.example.com/randomstring.png
to make it almost impossible for images to overwrite each other.
Thank you for the help,
A php noob
As contributed in the comments, I added a timestamp to the end of the filename like so:
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]) . date('YmdHis');
Thank you for the help

PHP Codeigniter Uploading Class, rename files with specific schema

I am having a spot of trouble with Codeigniter and getting files to rename within the upload process from the Upload Library it has to offer. Now before anyone says it, I am not looking for "encrypted" file names.
My Problem is in uploading images you have a good handful of types you could be dealing with. So how does one change the file name using the file_name config option to a specific schema (which I already have the schema part up and working). But maintain the same file type?
Right now I am attempting
$upload_config['file_name'] = $generated_filename_from_schema
Only problem is $generated_filename_from_schema doesnt have a file extension, and leaving the file extension out of the equation CI seems to ignore it altogether and just takes the file and append_1, _2, _3 as it goes up if the files have the same name, otherwise it just leaves the name intact.
Now I have to pass the $config to CI so it will upload the file, but how can I determin what kind of file I am working with before it trys to upload so I can use my name generation schema.
*edit*
$upload_config['upload_path'] = realpath(APPPATH.'../images/');
$upload_config['allowed_types'] = 'gif|jpg|png';
$upload_config['max_size'] = 0;
$upload_config['max_width'] = 0;
$upload_config['max_height'] = 0;
$upload_config['remove_spaces'] = true;
$upload_config['file_name'] = $this->genfunc->genFileName($uid);
if($this->input->post('uploads'))
{
$this->load->library('upload');
$this->upload->initialize($upload_config);
if (!$this->upload->do_upload())
{
//echo 'error';
echo $config['upload_path'];
$this->data['errors'] = $this->upload->display_errors();
}
else
{
//echo 'uploaded';
$this->data['upload_data'] = $this->upload->data();
}
}
You can use $_FILES array to get original name of file.
Extract extension of original file.Then, append to your new file name.
Try as below
$ext = end(explode(".", $_FILES[$input_file_field_name]['name']));
$upload_config['file_name'] = $this->genfunc->genFileName($uid).'.'.$ext;
Personally, I find CodeIgniter's file uploading class to be somewhat cumbersome. If you want a vanilla PHP solution:
function submit_image(){
$f = $_FILES['image'];
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($f['tmp_name']);
if(in_array($detectedType, $allowedTypes)){
$pi = pathinfo($f['name']);
$ext = $pi['extension'];
$target = $this->genfunc->genFileName($uid) "." . $ext;
if(move_uploaded_file($f['tmp_name'], $target)){
/*success*/
}
else {/*couldn't save the file (perhaps permission error?*/}
}
else {/*invalid file type*/}
}

MootoolsFancy Upload

i have just come across what i think i need for my front end multi uploader script in joomla.
Mootools fancy upload looks great! but i am having trouble when i uncomment the script that uploads the images inside the uploads folder?
All i have done is uncommented the default script inside the test file and created a folder called uploads which i set to 757 and also tried 777
But for some reason the uploader now returns some strange error about md 5 hash stuff?
eastern_beach_jetty.jpgAn error occured:
Warning: md5_file(/tmp/phpUjHol4) [function.md5-file]: failed to open stream: No such file or directory in /home/user/www.mydomain.com.au/test/server/script.php on line 133
{"status":"1","name":"eastern_beach_jetty.jpg","hash":false}
The fancy uploader website from where i got the script is here http://digitarald.de/project/fancyupload/
Any help on this would be so greatly apprecited,
thank you.
John
Coincidentally, I did the same mistake as you, the reason is that the first move tmp file to the destination folder, and then referring to the tmp file, which no longer exists, because it is in the target folder. I know that the late response, but it was as if someone had the same problem.
Not:
move_uploaded_file($_FILES['Filedata']['tmp_name'], '../uploads/' . $_FILES['Filedata']['name']);
$return['src'] = '/uploads/' . $_FILES['Filedata']['name'];
if ($error) {
(...)
} else {
(...)
// $return['hash'] = md5_file($_FILES['Filedata']['tmp_name']);
// ... and if available, we get image data
$info = #getimagesize($_FILES['Filedata']['tmp_name']);
if ($info) {
$return['width'] = $info[0];
$return['height'] = $info[1];
$return['mime'] = $info['mime'];
}
}
Yes:
if ($error) {
(...)
} else {
(...)
// $return['hash'] = md5_file($_FILES['Filedata']['tmp_name']);
// ... and if available, we get image data
$info = #getimagesize($_FILES['Filedata']['tmp_name']);
if ($info) {
$return['width'] = $info[0];
$return['height'] = $info[1];
$return['mime'] = $info['mime'];
}
}
move_uploaded_file($_FILES['Filedata']['tmp_name'], '../uploads/' . $_FILES['Filedata']['name']);
$return['src'] = '/uploads/' . $_FILES['Filedata']['name'];

Categories