removing en extension from a file in a loop - php

im trying to remove the file extension from each file name in a loop so ball.jpg can be echoed as ball, but it isnt working for me
I have this code
$files = array();
foreach($src_files as $file)
{
$ext = strrchr($file, '.');
if(in_array($ext, $extensions))
{
array_push( $files, $file);
$thumb = $src_folder.'/'.$file;
$fileName = basename($file);
$place = preg_replace("/\.[^.]+$/", "", $fileName);
}
}

Try this:
$src_files = array('/tmp/path/file1.txt', '/tmp/path/file2.txt.php', '/tmp/not.ext');
$extensions = array('.txt', '.php');
$files = array();
foreach ($src_files as $file)
{
$ext = strrchr($file, '.');
var_dump($ext);
if (in_array($ext, $extensions))
{
array_push($files, $file);
//$thumb = $src_folder.'/'.$file;
$pathInfo = pathinfo($file);
$fileName = $pathInfo['basename'];
$place = $pathInfo['filename'];
var_dump($pathInfo);
}
}
If you just want the filename, without extension, use pathinfo($fileName, PATHINFO_FILENAME);. See here for more information.
If you don't want to use pathinfo(), you can also use string manipulation techniques:
$place = substr($fileName, 0 , (strrpos($fileName, ".")));
strrpos() is like strpos(), but searches for a character starting from the end of the string and working backwards.

Related

Extension in php file

I created a page that can upload file to my database, but when a filename has (.), it doesnt save properly. For example I upload a file named imagefile.50.jpg, it just saves as image20.50
<?php
function upload_image()
{
if(isset($_FILES["user_image"]))
{
$extension = explode('.', $_FILES['user_image']['name']);
$new_name = $extension[0] . '.' . $extension[1];
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
return $new_name;
}
}
To get the filename and extension of a file, you can use pathinfo, i.e.:
$file = "some_dir/somefile.test.php"; # $_FILES['user_image']['name']
$path_parts = pathinfo($file);
$fn = $path_parts['filename'];
$ext = $path_parts['extension'];
print $fn."\n";
print $ext;
Output:
somefile.test
php

Renaming files in PHP?

I want the script to go into the folder 'images', take every file, cut the first four characters and rename it.
PHP
<?php
$path = './images/';
if ($handle = opendir($path))
{
while (false !== ($fileName = readdir($handle)))
{
if($fileName!=".." && $fileName!=".")
{
$newName = substr($fileName, 4);
$fileName = $path . $fileName;
$newName = $path . $newName;
rename($fileName, $newName);
}
}
closedir($handle);
}
?>
This is how the files in the images folder are named:
0,78test-1.jpg
0,32test-2.jpg
0,43test-3.jpg
0,99test-4.jpg
and this is what i want them to look like:
test-1.jpg
test-2.jpg
test-3.jpg
test-4.jpg
The problem is the script cuts out the first 8, 12 or 16 characters, not four as i want it! So when i execute it my files look like this:
-1.jpg
-2.jpg
-3.jpg
-4.jpg
UPDATE
I also tracked the packages to make sure i am not executing the script multiple times. The script is only executed once!
A slightly different approach though essentially the same with the substr part this worked fine for tests on local system.
$dir='c:/temp2/tmpimgs/';
$files=glob( $dir . '*.*' );
$files=preg_grep( '#(\.jpg$|\.jpeg$|\.png$)#i', $files );
foreach( $files as $filename ){
try{
$path=pathinfo( $filename, PATHINFO_DIRNAME );
$name=pathinfo( $filename, PATHINFO_BASENAME );
$newname=$path . DIRECTORY_SEPARATOR . substr( $name, 4, strlen( $name ) );
if( strlen( $filename ) > 4 ) rename( $filename, $newname );
} catch( Exception $e ){
echo $e->getTraceAsString();
}
}
You may want to try this little Function. It would do just the proper renaming for you:
<?php
$path = './images/';
function renameFilesInDir($dir){
$files = scandir($dir);
// LOOP THROUGH THE FILES AND RENAME THEM
// APPROPRIATELY...
foreach($files as $key=>$file){
$fileName = $dir . DIRECTORY_SEPARATOR . $file;
if(is_file($fileName) && !preg_match("#^\.#", $file)){
$newFileName = preg_replace("#\d{1,},\d{1,}#", "", $fileName);
rename($fileName, $newFileName);
}
}
}
renameFilesInDir($path);
<?php
$path = './images/';
if ($handle = opendir($path))
{
while (false !== ($fileName = readdir($handle)))
{
if($fileName!=".." && $fileName!=".")
{
//change below line and find first occurence of '-' and then replace everything before this with 'test' or any keyword
$newName = substr($fileName, 4);
$fileName = $path . $fileName;
$newName = $path . $newName;
rename($fileName, $newName);
}
}
closedir($handle);
}
?>

Check if file (multiple extension possible ) exists?

I got ascript which helps me to add some data into a csv file, based on the fact if a image is inside a folder or not (exits or not). Files are images, so I need to check if the file exists, and if it is a png, jpg, jpeg, gif.
So far it only check if it a JPG but I would like it to find the file exists if it's a PNG or JPEG or even GIF.
<?php
$columns = array("row1","row2","row3","row4","row5","row6","row7","row8","row9",
"row10","row11","row12","row13","row14","row15","row16","row17","row18"
);
$rootDir = "/path/to/images/folder/files";
$file = fopen("database.csv", "r") or die('fopen database failed');
$newFile = fopen("newdata.csv", "w") or die('fopen newdata.csv failed');
while (($data = fgetcsv($file, 999999, ";")) !== FALSE) {
$row = array_combine($columns, $data);
$filename = $row['row4'].".jpg"; // could be png or jpEg, or even gif
if (file_exists("$rootDir/$filename")) {
$row['image'] = .$filename; //also needs correct extension of image which exists.
$row['small_image'] = .$filename;
$row['thumbnail'] = .$filename;
}
fputcsv($newFile, array_values($row), ";",'"' );
}
fclose($file);
fclose($newFile);
?>
You can do something like this:
// your code
$possible_extensions = array("jpg", "jpeg", "png", "gif");
$row = array_combine($columns, $data);
foreach($possible_extensions as $ext){
$filename = $row['row4'] . "." . $ext;
if (file_exists("$rootDir/$filename")) {
$row['image'] = .$filename;
$row['small_image'] = .$filename;
$row['thumbnail'] = .$filename;
break;
}
}
fputcsv($newFile, array_values($row), ";",'"' );
// your code
Edited:
If you want to perform case-insensitive file_exists() check then here's the solution,
The following fileExists() function returns the full path file if found, and false if not.
function fileExists($fileName, $caseSensitive = true) {
if(file_exists($fileName)) {
return $fileName;
}
if($caseSensitive) return false;
// Handle case insensitive requests
$directoryName = dirname($fileName);
$fileArray = glob($directoryName . '/*', GLOB_NOSORT);
$fileNameLowerCase = strtolower($fileName);
foreach($fileArray as $file) {
if(strtolower($file) == $fileNameLowerCase) {
return $file;
}
}
return false;
}
Here's the source:
PHP Case Insensitive Version of file_exists()
And now your code,
// your code
$possible_extensions = array("jpg", "jpeg", "png", "gif");
$row = array_combine($columns, $data);
foreach($possible_extensions as $ext){
$filename = $row['row4'] . "." . $ext;
if ($filename = fileExists("$rootDir/$filename", false)) {
$row['image'] = .$filename; //also needs correct extension of image which exists.
$row['small_image'] = .$filename;
$row['thumbnail'] = .$filename;
break;
}
}
fputcsv($newFile, array_values($row), ";",'"' );
// your code

Change file name Laravel 4

How can I change name of uploaded file in Laravel 4.
So far I have been doing it like this:
$file = Input::file('file');
$destinationPath = 'public/downloads/';
if (!file_exists($destinationPath)) {
mkdir("./".$destinationPath, 0777, true);
}
$filename = $file->getClientOriginalName();
But if I have 2 files with the same name I guess it gets rewritten, so I would like to have something like (2) added at the end of the second file name or to change the file name completely
The first step is to check if the file exists. If it doesn't, extract the filename and extension with pathinfo() and then rename it with the following code:
$img_name = strtolower(pathinfo($image_name, PATHINFO_FILENAME));
$img_ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
$filecounter = 1;
while (file_exists($destinationPath)) {
$img_duplicate = $img_name . '_' . ++$filecounter . '.'. $img_ext;
$destinationPath = $destinationPath . $img_duplicate;
}
The loop will continue renaming files as file_1, file_2 etc. as long as the condition file_exists($destinationPath) returns true.
I know this question is closed, but this is a way to check if a filename is already taken, so the original file is not overwriten:
(... in the controller: ... )
$path = public_path().'\\uploads\\';
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
$original_filename = pathinfo($fileName, PATHINFO_FILENAME);
$new_filename = $this->getNewFileName($original_filename, $extension, $path);
$upload_success = Input::file('file')->move($path, $new_filename);
this function get an "unused" filename:
public function getNewFileName($filename, $extension, $path){
$i = 1;
$new_filename = $filename.'.'.$extension;
while( File::exists($path.$new_filename) )
$new_filename = $filename.' ('.$i++.').'.$extension;
return $new_filename;
}

Get the file extension [duplicate]

This question already has answers here:
How to get a file's extension in PHP?
(31 answers)
Closed 2 years ago.
I'm exploding on "." to get file format and name:
list($txt, $ext) = explode(".", $name);
The problem is that some files have names with dots.
How do I explote on the LAST "." so that I get $name=pic.n2 and $ext=jpg from: pic.n2.jpg?
Use pathinfo:
$pi = pathinfo($name);
$txt = $pi['filename'];
$ext = $pi['extension'];
$name = pathinfo($file, PATHINFO_FILENAME);
$ext = pathinfo($file, PATHINFO_EXTENSION);
http://www.php.net/pathinfo
use this
$array = explode(".", $name);
end($array); // move the internal pointer to the end of the array
$filetype = current($array);
thanks
Use Pathinfo or mime_content_type to get file type information
$filetype = pathinfo($file, PATHINFO_FILENAME);
$mimetype = mime_content_type($file);
Use PHP's pathinfo() function.
See more information here http://php.net/manual/en/function.pathinfo.php
$file_part = pathinfo('123.test.php');
Example:
echo $file_part['extension'];
echo $file_part['filename'];
Output:
php
123.test
<?php
$path = 'http://www.mytest.com/public/images/portfolio/i-vis/abc.y1.jpg';
echo $path."<br/>";
$name = basename($path);
$dir = dirname($path);
echo $name."<br/>";
echo $dir."<br/>";
$pi = pathinfo($path);
$txt = $pi['filename']."_trans";
$ext = $pi['extension'];
echo $dir."/".$txt.".".$ext;
?>
you can write your own function as
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
You might try something like this:
<?php
$file = 'a.cool.picture.jpg';
$ext = substr($file, strrpos($file, '.')+1, strlen($file)-strrpos($file, '.'));
$name = substr($file, 0, strrpos($file, '.'));
echo $name.'.'.$ext;
?>
The key functions are strrpos() which finds the last occurrence of a character (a "." in this case) and substr() which returns a sub string. You find the last "." in the file, and sub string it. Hope that helps.
It is better to use one of the solutions above, but there is also a solution using the explode function:
$filename = "some.file.name.ext";
list($ext, $name) = explode(".", strrev($filename), 2);
$name = strrev($name);
$ext = strrev($ext);
What this solution does is the following:
1. reverse string, so it will look like: txe.eman.elif.emos
2. explode it, you will get something like: $ext = "txe", $name = "eman.elif.emos"
3. reverse each of the variables to get the correct results

Categories