Php change file extension

How can I change a file’s extension using PHP?

In modern operating systems, filenames very well might contain periods long before the file extension, for instance:

PHP provides a way to find the filename without the extension that takes this into account, then just add the new extension:

function replace_extension($filename, $new_extension)

To me, this is the best answer because it’s using a function in PHP for what it was designed for. It also does the computation in one single command, which means less C code in the guts of PHP.

I think this should keep the path information: return $info[‘dirname’].»/».$info[‘filename’] . ‘.’ . $new_extension;

substr_replace($file , 'png', strrpos($file , '.') +1) 

Will change any extension to what you want. Replace png with what ever your desired extension would be.

Replace extension, keep path information

function replace_extension($filename, $new_extension)

Oh my . I am so used to Magento where they define DS = DIRECTORY_SEPARATOR . Edited my answer. Thanks.

May be it’s not safe because it change not only extension. For example, on Windows it may be change one separator to another.

‘c:\\windows\\system32/drivers/etc/some.file..png’ — change to ‘jpg’ give next result: ‘c:\\windows\\system32/drivers/etc\\some.file..jpg’ — separator before filename changed. It may be cause some side effects in some cases.

The function takes strings, it doesn’t matter if those strings are string literals or string variables.

Once you have the filename in a string, first use regex to replace the extension with an extension of your choice. Here’s a small function that’ll do that:

function replace_extension($filename, $new_extension) < return preg_replace('/\..+$/', '.' . $new_extension, $filename); >

Then use the rename() function to rename the file with the new filename.

Actually this is a bad idea. In modern operating systems, filenames may contain periods within the name, for instance when chaning the extension to «.tif», «this.is.a.test.pdf» when used in this would strip it to «this.tif» Instead, use: $info = pathinfo($filename); return $info[‘filename’] . «.» . $new_extension;

preg_replace(‘/\.[^.]+$/’, ‘.’ . $extension, $file) to match the last found . but will not work if file has no extension

Just replace it with regexp:

$filename = preg_replace('"\.bmp$"', '.jpg', $filename); 

You can also extend this code to remove other image extensions, not just bmp:

$filename = preg_replace('"\.(bmp|gif)$"', '.jpg', $filename); 

For regex fans, modified version of Thanh Trung’s ‘preg_replace’ solution that will always contain the new extension (so that if you write a file conversion program, you won’t accidentally overwrite the source file with the result) would be:

preg_replace('/\.[^.]+$/', '.', $file) . $extension 

This is a clever solution. By using a regex to simply strip the extension and then using string concatenate to apply the new extension it works under more conditions then any of the other solutions provided.

substr($filename, 0, -strlen(pathinfo($filename, PATHINFO_EXTENSION))).$new_extension 

Changes made only on extension part. Leaves other info unchanged.

Читайте также:  Css примеры красивых форм

@klodoma Yep. But question about change from one extension to another. So it expect some extension present.

$oldname = 'path/photo.jpg'; $newname = (dirname($oldname) ? dirname($oldname) . DIRECTORY_SEPARATOR : '') . basename($oldname, 'jpg') . 'exe'; 
$newname = (dirname($oldname) ? dirname($oldname) . DIRECTORY_SEPARATOR : '') . basename($oldname, pathinfo($path, PATHINFO_EXTENSION)) . 'exe'; 

Many good answers have been suggested. I thought it would be helpful to evaluate and compare their performance. Here are the results:

  • answer by Tony Maro ( pathinfo ) took 0.000031040740966797 seconds. Note: It has the drawback for not including full path.
  • answer by Matt ( substr_replace ) took 0.000010013580322266 seconds.
  • answer by Jeremy Ruten ( preg_replace ) took 0.00070095062255859 seconds.

Therefore, I would suggest substr_replace , since it’s simpler and faster than others.

Just as a note, There is the following solution too which took 0.000014066696166992 seconds. Still couldn’t beat substr_replace :

$parts = explode('.', $inpath); $parts[count( $parts ) - 1] = 'exe'; $outpath = implode('.', $parts); 

Источник

PHP change file extension and force download

I’m storing files by reference, which means every file uploaded gets renamed to «temp_n», and stored in the database like ID, Name, Originalname, Mime . So when I roll a download for any file, I go to the url getfile.php?i=$id and grab the filed based off of the id. Here’s my problem, it doesn’t handle the files well, it will not show/force download the images, and it should force download any file there is. I’ll do this to force download:

$url = "http".(!empty($_SERVER['HTTPS'])?"s":"")."://".$_SERVER['SERVER_NAME'].dirname($_SERVER['SCRIPT_NAME']); $dir = '/uploads/messaging/'.$room.'/'; $path = $url.$dir; header("Content-Type: " . $mime); readfile($path.$tname); 

For the specified examples, $room is 1 and is a valid folder, $path is a valid path. I have tried storing the extension as well, and doing readfile($path.$tname.$ext) where $ext was .png, but it failed. I’ve messed around with headers, but max I got it to force it to download getfile.php file instead of the file in question. The PHP code would contain this:

 
Warning: readfile(http://url/uploads/messaging/1/upload_IvRWZc) [function.readfile]: failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in script/url on line 32

Where line 32 is the header in question, such as header(«Content-Type: application/force-download»); or header(‘Content-Type: application/octet-stream’); . The current examples shows a broken image link, it knows it’s an image (based off of the mime) but it doesn’t show it. What it should do is simply download the file requested. There is no .htaccess in the folders and they are running 755 permission set. PS. I’m not trying to trick users into downloading crap, I’m trying to make a secure file storage so nobody uploads funnyshell.php to my server and has a blast with it.

Читайте также:  Python импорт csv файла

Источник

Как я могу изменить расширение файла с помощью PHP?

Мне нужно было это, чтобы изменить все расширения изображений с галереей на нижний регистр. В итоге я сделал следующее:

// Converts image file extensions to all lowercase $currentdir = opendir($gallerydir); while(false !== ($file = readdir($currentdir))) < if(strpos($file,'.JPG',1) || strpos($file,'.GIF',1) || strpos($file,'.PNG',1)) < $srcfile = "$gallerydir/$file"; $filearray = explode(".",$file); $count = count($filearray); $pos = $count - 1; $filearray[$pos] = strtolower($filearray[$pos]); $file = implode(".",$filearray); $dstfile = "$gallerydir/$file"; rename($srcfile,$dstfile); >> 

В современных операционных системах имена файлов очень хорошо могут содержать периоды задолго до расширения файла, например:

PHP предоставляет способ найти имя файла без расширения, которое учитывает это, а затем просто добавить новое расширение:

function replace_extension($filename, $new_extension)

Для меня это лучший ответ, потому что он использует функцию в PHP для того, для чего он был разработан. Он также выполняет вычисления в одной команде, что означает меньше кода на языке C в кишечнике PHP.

Я думаю, что это должно сохранить информацию о пути: return $ info [‘dirname’]. «/». $ Info [‘filename’]. » , $ New_extension;

substr_replace($file , 'png', strrpos($file , '.') +1) 

Изменит любое расширение на то, что вы хотите. Замените png тем, что было бы вашим желаемым расширением.

Как только у вас есть имя файла в строке, сначала используйте регулярное выражение, чтобы заменить расширение на расширение по вашему выбору. Вот небольшая функция, которая сделает это:

function replace_extension($filename, $new_extension) < return preg_replace('/\..+$/', '.' . $new_extension, $filename); >

Затем используйте функцию rename(), чтобы переименовать файл с новым именем файла.

На самом деле это плохая идея. В современных операционных системах имена файлов могут содержать точки внутри имени, например, при изменении расширения на «.tif», «this.is.a.test.pdf» при использовании в этом случае оно будет заменено на «this.tif». Вместо этого , используйте: $ info = pathinfo ($ filename); вернуть $ info [‘filename’]. «» , $ New_extension;

Читайте также:  Opencv gpu python install

preg_replace(‘/\.[^.]+$/’, ‘.’ . $extension, $file) чтобы соответствовать последнему найденному . но не будет работать, если файл не имеет расширения

Функция принимает строки, не имеет значения, являются ли эти строки строковыми литералами или строковыми переменными.

@me_ me_ — Почему ты жалуешься на то, что это не ответ мне ? Я только что прокомментировал это почти десять лет назад.

@me_ — То, что ОП не понимает фундаментальных основ языка программирования, прежде чем задавать вопрос о конкретной задаче, не дает ответа, который предполагает, что знание плохое. Если это так, то каждый ответ должен включать вводное руководство по программированию.

@me_ — Что не имеет ничего общего с ОП, не знающим основ, таких как «Строка — это строка, независимо от того, является ли она строковым литералом или переменной»

@me_ — Это просто возвращает нас к моему предыдущему комментарию. Если вы думаете, что это некачественный ответ, потому что это ответ только по ссылке, почему вы направили свой комментарий на меня, чтобы объяснить то, что этот ответ не потрудился бы объяснить, если бы это был не только ответ по ссылке? Направьте свой комментарий на человека, который написал ответ! Или просто отметьте это как низкое качество и двигайтесь дальше!

Источник

Php Change a File Extension Easily

How can I change a file’s extension using PHP? The answer is very simple because PHP provides out of the box functionality to deal with files. Although, for file path, naming, directory name we can use some functions like pathinfo, basename and dirname.

pathinfo returns an array with key value. You can use following keys to get the specified value.

pathinfo Keys

php  $URL = "https://www.useyourlocaldevelopment.com/images/logo.jpg";   $path_parts = pathinfo ($URL);   echo $path_parts['dirname'], "
"
;
echo $path_parts['basename'], "
"
;
echo $path_parts['extension'], "
"
;
echo $path_parts['filename'], "
"
;
echo $path_parts['dirname'] ."/". $path_parts['filename'].".png";

Other than pathinfo we have basename and dirname. These two functions return the string.

php  $URL = "https://www.useyourlocaldevelopment.com/images/logo.jpg";   echo basename ($URL), "
"
; // basename return fileName with extension
echo dirname ($URL), "
"
; //dirname retrn directory Name

Источник

Оцените статью