How to get file name from full path with PHP - 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.

Related

Delete image file from directory in PHP on remote server and localhost

I'm trying to figure out, how to delete correctly image file with summernote from directory folder on remote server and localhost.
So, image successfully uploaded from summernote editor and located by directory path:
C:/xampp/htdocs/user/blog/uploads/img-uploads/154_20220702.png
and C:\xampp\htdocs\user\blog\admin\editor-delete.php code:
<?php
$src = $_POST['src'];
$path = "../uploads/img-uploads/";
$dir = basename($path);
$file_name = str_replace($dir, '', $src);
unlink($file_name);
if ($file_name) {
echo 'File Delete Successfully';
}
?>
or
$src = $_POST['src'];
$dir = "../uploads/img-uploads/";
$file_name = str_replace($dir, '', $src);
unlink($file_name);
if ($file_name) {
echo 'File Delete Successfully';
}
Warning: unlink(): http does not allow unlinking in
C:\xampp\htdocs\user\blog\admin\editor-delete.php
$src = $_POST['src'];
$dir = "../uploads/img-uploads/";
$file_name = str_replace($dir, '', $src);
unlink($_SERVER['DOCUMENT_ROOT'] . $file_name);
if ($file_name) {
echo 'File Delete Successfully';
}
Localhost correct path must be C:/xampp/htdocs/blog/uploads/img-uploads/154_20220702.png, but with unlink($_SERVER['DOCUMENT_ROOT'] .'/'. $file_name); the path contains extra http://localhost/user/ in C:/xampp/htdocs/http://localhost/user/blog/uploads/img-uploads/154_20220702.png
Warning:
unlink(C:/xampp/htdocshttp://localhost/user/blog/uploads/img-uploads/154_20220702.png):
No such file or directory in
C:\xampp\htdocs\user\blog\admin\editor-delete.php
File Delete Successfully
jquery-3.6.0.min.js:5177 XHR finished loading: POST
"http://localhost/user/blog/admin/editor-delete.php".
I cannot completely test this but I think you could change the editor-delete.php script like this. Judging by the paths cited in the question you need to construct the absolute path by leaving the admin directory traversing the file structure into uploads/img-uploads so chdir and getcwd are two useful functions for this. The notes in the code show what I mean.
The piece of code that displays the File Delete Successfully is based upon a variable which will always be true (effectively) rather than the more meaningful result from the actual unlink operation so you should use that returned value to fork your program logic.
<?php
/*
C:\xampp\htdocs\user\blog\admin\editor-delete.php
so:
chdir('../') leads to C:\xampp\htdocs\user\blog\
chdir('../uploads/img-uploads') should lead to C:\xampp\htdocs\user\blog\uploads\img-uploads
*/
if( isset( $_POST['src'] ) ){
# Change working directory for current script operations
# - go up one level out of "admin" and into the uploads folder.
chdir('../uploads/img-uploads');
# default value for use later in output message
$status=false;
# construct the full path to local file using getcwd() to find working directory.
$path=sprintf( '%s/%s', getcwd(), basename( $_POST['src'] ) );
# if the file exists - delete it or warn ( inspect the path! )
if( file_exists( $path ) )$status=#unlink( $path );
else exit( sprintf( 'Unable to find file: "%s"', $path ) );
# prevent cached results tainting file checks
clearstatcache();
echo $status ? 'File deleted successfully' : 'Sorry, that file could not be deleted';
}
?>

PHP copy command folder

My currency working directory is ../main
I have a script which accepts files to be uploaded.
I have the following code but instead of coping the file into the ../_assets folder, it copies it into the ../main folder with the filename as ../_assets/correct.csv.
Any idea what might be wrong here?
Thanks
const IMPORT_FILE_DIR = "..\_assets\\";
private $file_name = "";
$this->file_name = Page::IMPORT_FILE_DIR . $_FILES['file_in']['name'];
$result= copy( $_FILES['file_in']['tmp_name'],$this->file_name);
Here fileName is = "..\_assets\correct2.csv"

How to rename() and copy() a file to another directory with php

I am trying to copy a file to another directory, but to prevent overwriting a file inside it with the same name, I check it first and if a file with the same name already exists, then I want to rename the file from, lets say file.jpg to file(1).jpg and copy it. I do not succeed in renaming it "on the fly".
This is what I have so far:
$src_file_url = $_POST['copyfile']; //eg uploads/name/file.jpg
$fileName = basename($src_file_url);
$new_dest = $_POST['copyfile-destination'];
/* New file name and path for this file */
$dest_file = 'uploads/'.$UserID.'/'.$new_dest.'/'.$fileName;
if (file_exists($dest_file)) {
rename($src_file_url, $fileName.'(1)');
copy( $src_file_url, $dest_file );
exit;
}

Laravel S3 image upload creates a folder with the filename automatically

I'm using Laravel 5.4.*. I've this simple code in a helper file to upload images/gif in S3 bucket under a folder named say "instant_gifs/". The code is below:
if ( !function_exists('uploadFile') ) {
function uploadFile($fileContent, $fileName, $size='full', $disk='s3')
{
$rv = '';
if( empty($fileContent) ) {
return $rv;
}
if($size == 'full') {
dump($fileName);
$path = Storage::disk($disk)->put(
$fileName,
$fileContent,
'public'
);
}
if ( $path ) {
$rv = $fileName;
}
return $rv;
}
}
From the controller, I'm calling the helper method as below:
$file = $request->gif;
$file_name = 'instant_gifs/' . $user_id . '_' . time() . '_' . $file->getClientOriginalName();
$result = uploadFile($file, $file_name);
In the the $fileName parameter of the helper method, I'm providing the fileName as for example in this format:
"instant_gifs/83_1518596022_giphy.gif"
but after the upload, I see that the file gets stored under this folder
"vvstorage/instant_gifs/83_1518596022_giphy.gif/CRm1o1YEcvX3fAulDeDfwT7DIMCxOKG8WFGcA3lB.gif"
with a random file name
CRm1o1YEcvX3fAulDeDfwT7DIMCxOKG8WFGcA3lB.gif
Whereas, according to the code, it should get stored in this path:
"vvstorage/instant_gifs/83_1518596022_giphy.gif"
Doesn't get any explanation why this is happening. Any clue will be appreciated.
BucketName = vvstorage
Folder I'm mimicking = instant_gifs
After some research & testing, found the issue. put() method expects the 2nd parameter as the file contents or stream not the file object. In my code, I was sending the file as $file = $request->gif; or $file = $request->file('gif'); hoping that Storage class will implicitly get the file contents. But to get the expected result, I needed to call the helper method from the controller as below. Notice the file_get_contents() part.
$file = $request->gif;
$file_name = 'instant_gifs/' . $user_id . '_' . time() . '_' . $file>getClientOriginalName();
$result = uploadFile( file_get_contents($file), $file_name );
Now, I got the image correctly stored under the correct path for example in /instant_gifs/9_1518633281_IMG_7491.jpg.
Now, let me compare/summarize the available methods for achieving the same result:
1) put():
$path = Storage::disk('s3')->put(
'/instant_gifs/9_1518633281_IMG_7491.jpg', #$path
file_get_contents($request->file('gif')), #$fileContent
'public' #$visibility
Got it stored in /vvstorage/instant_gifs/9_1518633281_IMG_7491.jpg
2) putFileAs(): To achieve the same thing withputFileAs(), I needed to write it as below. 1st parameter expects the directory name, I left it blank as I'm mimicking the directory name in s3 through the filename.
$path = Storage::disk('s3')->putFileAs(
'', ## 1st parameter expects directory name, I left it blank as I'm mimicking the directory name through the filename
'/instant_gifs/9_1518633281_IMG_7491.jpg',
$request->file('gif'), ## 3rd parameter file resource
['visibility' => 'public'] #$options
);
Got it stored in /vvstorage/instant_gifs/9_1518633281_IMG_7491.jpg
3) storeAs():
$path = $request->file('gif')->storeAs(
'', #$path
'/instant_gifs/9_1518633281_IMG_7491.jpg', #$fileName
['disk'=>'s3', 'visibility'=>'public'] #$options
);
Got it stored in /vvstorage/instant_gifs/9_1518633281_IMG_7491.jpg
Extras::
4) For storing Thumbnails through put(). Example of stream() ...
$imgThumb = Image::make($request->file('image'))->resize(300, 300)->stream(); ##create thumbnail
$path = Storage::disk('s3')->put(
'profilethumbs/' . $imgName,
$imgThumb->__toString(),
'public'
);
Hope that it helps someone.
1.) Why is there vvstorage in the url?
It is appending that route because your root folder inside of your configuration for S3 is set as vvstorage, so whenever you upload to S3 all files will be prepended with vvstorage.
2.) Why random name even when you passed the name of the file?
Because when using put the file will get a unique ID generated and set as it's file name so no matter what you pass, it won't save the file under the name you wanted. But if you use putFileAs then you can override the default behaviour of put and pass a name of the file.
Hope this clarifies it

PHP - How to unlink a file with no file extention

This work great to delete php, txt and images but I recently starting using an image resize that inserts temp images in to my trash folder.
* example name 2616cf442b6cd3e1313161551fad6078 *
File type: text/x-generic
Permission: 0644
Tried renaming to .txt with no luck
$cleantrash =(DOCROOT."/woobe/myfiles/trash/");
$cleantrash = opendir($cleantrash);
while (($filex_clean = readdir($cleantrash)) !== false) {
if($filex_clean != "." && $filex_clean != ".." && $filex_clean != "index.php") {
echo "<b>Cleaing Trash...</b> $filex_clean<br>";
unlink($filex_clean);
}
}
closedir($cleantrash);
*EDIT *
$newname = basename($filename, ".bmp").".jpg";
rename($filename, $newname);
and the files are gone lol. No unlink useds? so where did they go?
The readdir() function returns file names without their paths (relative to the resource directory parameter you pass it).
The unlink() function expects the full file path. My guess would be that you need to save the $cleantrash path instead of overwriting it with the resource from opendir(), and then do something like:
unlink($cleantrash . $filex_clean);

Categories