PHP move image in AJAX functionality - php

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.

Related

Codeigniter 4: Uploading files with move_uploaded_file

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

move_uploaded_file not working despite correct path and existing file

I'm really struggling with an issue relating the move_uploaded_file function of php.
The path should be correct, but see yourself:
$imgDir = "../img/".$CATEGORY;
$fileName = $_FILES['image']['name'];
$maxsize = 800;
$compQuality= 75;
if(!is_dir($imgDir)) {
mkdir($imgDir.'/tn', 0777, true);
chmod($imgDir, 0777);
chmod($imgDir, 0777);
}
$imgDir = $imgDir."/";
$imgTnDir = $imgDir."tn/";
I have also tested it by echo-ing everything and it seems to work, but when it comes to the move_uploaded_file it still does not work, even though I test if the file really exists:
if(file_exists($imgDir.$fileName)) {
$status = "The file ".$fileName." already exists, please choose a different title.";
}
if(!move_uploaded_file($_FILES['image']['tmp_name'], $imgDir.$fileName)) {
$status = "File upload failed, sorry.";
}
if(!empty($status)) {
echo $status;
exit();
}
I hope that someone can help me. If you want I can print anything out you need or give you more snippets of the code. The var $_FILES['image']['tmp_name'] does not only exist, but has a proper name by the way.
Also I have checked the php.ini and both uploading is allowed and the size is surely set high enough.
Thank you in advance.
make sure that you have the right path in $imgDir. You can try:
if(!is_writable($imgDir)) { exit('CANNOT_WRITE_IN_DIR'); }
and also you can use an absolute path, like this:
$imgDir = __DIR__ . "/../img/".$CATEGORY;

How to get file name from full path with PHP

This is my upload php:
if (trim($_FILES['path_filename']['name']))
{
if (File::upload($_FILES['path_filename'], dirname(realpath(__FILE__)) . '/../tests'))
{
$test->setPathFilename('../tests/' . $_FILES['path_filename']['name']);
}
}
}
else
{
if ($aux)
{
$aux = str_replace("\\", "/", $aux);
$aux = preg_replace("/[\/]+/", "/", $aux);
$test->setPathFilename($aux);
}
}
$_POST["upload_file"] = $test->getPathFilename();
This above code is working well, I mean, upload to server is working and also getting Path File Name and insert into sql table is working too.
Example: When I upload a file for example: ABC.jpg , it will upload to tests folder and also Path File Name is (( ../tests/ABC.jpg )) and it will insert to sql table.
The problem is here:
I changed global function to rename files automatically by using this following code:
Before It was:
$destinationName = $file['name'];
I changed it to:
$ext = pathinfo($file["name"], PATHINFO_EXTENSION);
$destinationName = sha1_file($file["tmp_name"]).time().".".$ext;
Now, After upload file to tests folder, it will be renamed automatically, but still Path File name is same, It's ABC.jpg not renamed file in tests folder.
How to get Renamed Path File Name ???
I really appreciate your help on this issue.
Thanks in advance
Use basename() to get the filename from a path.
$filename = basename('/path/to/file.ext');
This will give you: file.ext
To rename the path file name you could use this:
if ( !file_exists( $path ) ) {
mkdir( $path, 0777, true );
}
This will make sure the path exist and if it doesn't it will created. Now we can rename()
rename( __FILE__ "/new/path/".$file_name );
This will move it between directories if necessary.

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

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