Php set file name

Работа с именами файлов в PHP

Набор PHP функций для работы с путями и именами файлов.

Получить имя файла

echo basename('path/file.png'); // file.png

Имя файла без расширения

$info = pathinfo('path/file.png'); echo $info['filename']; // file /* или */ echo pathinfo('path/donut.png', PATHINFO_FILENAME); // file

Получить расширение файла

echo mb_strtolower(mb_substr(mb_strrchr('path/file.png', '.'), 1)); // png /* или */ echo pathinfo('path/file.png', PATHINFO_EXTENSION); // png

Заменить расширение файла

Заменить расширение .jpeg на .jpg:

$file_name = 'file.jpeg'; $file_new = preg_replace('/\.jpeg$/', '.jpg', $file_name); echo $file_new; // file.jpg

Заменить несколько расширений на одно (.jpg, .jpeg, .png на .webp):

$file_name = 'file.jpeg'; $file_new = preg_replace('/\.(jpg|jpeg|png)$/', '.webp', $file_name); echo $file_new; // file.webp

Дописать текст в конец названия файла

$info = pathinfo('path/file.png'); $name = $info['dirname'] . '/' . $info['filename'] . '-' . time() . '.' . $info['extension']; echo $name; // path/file-1610877618.png

Безопасное сохранение файла

Чтобы не затереть существующий файл на сервере можно применить данную функцию.

В функцию передаётся путь и имя файла, если на сервере уже существует такой файл, функция к концу файла приписывает префикс. Также если директория не существует, пытается её создать.

function safe_file($filename) < $dir = dirname($filename); if (!is_dir($dir)) < mkdir($dir, 0777, true); >$info = pathinfo($filename); $name = $dir . '/' . $info['filename']; $prefix = ''; $ext = (empty($info['extension'])) ? '' : '.' . $info['extension']; if (is_file($name . $ext)) < $i = 1; $prefix = '_' . $i; while (is_file($name . $prefix . $ext)) < $prefix = '_' . ++$i; >> return $name . $prefix . $ext; > // Если в директории есть файл log.txt, файл будет сохранен с названием log_1.txt file_put_contents(safe_file(__DIR__ . '/log.txt'), $text);

Источник

Читайте также:  Python file name matching

Simple Change File Name in PHP

rename a file php

In this tutorial, we will create a Simple Change File Name using PHP. This code will launch a modal to update a filename when the user clicks the update button. The system uses the MySQLi UPDATE query to update the new information in the database base on the given file id and also change the file itself using rename(). This PHP built-in function renames the existing folder in the local file server by providing the old filename and new filename. This a user-friendly program. Feel free to modify and use it for your system.

We will be using PHP as a scripting language that interprets in the webserver such as xamp, wamp, etc. It is widely used by modern website application to handle and protect user confidential information.

Getting Started:

First, you have to download & install XAMPP or any local server that runs PHP scripts. Here’s the link for the XAMPP server https://www.apachefriends.org/index.html .

And this is the link for the jquery that I used in this tutorial https://jquery.com/ .

Lastly, this is the link for the bootstrap that I used for the layout design https://getbootstrap.com/ .

Creating Database

Open your database web server then create a database name in it db_change_file ; after that, click Import, then locate the database file inside the folder of the application then click ok.

change filename in php

Creating the database connection

Open your any kind of text editor(notepad++, etc..). Then just copy/paste the code below then name it conn.php.

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into your text editor, then save it as index.php.

        

PHP - Simple Change File Name


?>
File Name File Location Action

Creating Upload Query

This code contains the upload query of the application. This code will upload the file information to the MySQLi database server. To do that just copy and write this block of codes inside the text editor, then save it as upload.php.

alert('Successfully uploaded!')"; echo ""; >else< echo ""; echo ""; > > ?>

Creating the Main Function

This code contains the main function of the application. This code will change the filename when the button is clicked. To make this just copy and write these block of codes below inside the text editor, then save it as change.php

alert('Successfully change filename!')"; echo""; > >else< echo""; echo""; > > ?>

There you have it we successfully created Simple Change File Name using PHP. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

Источник

PHP Change File Name in Folder Tutorial

Today, I will learn you how to change file name in folder using php. This article goes in detailed on php rename file name in folder. We will look at example of how to rename file name in php. Here you will learn how to change uploaded file name in php. you will do the following things for how to change file name using php.

If you need to rename file in folder php code then we can use «rename()» function of php. php provide rename function to rename your file from one place to another.

Below, I will give you very simple example and syntax how it works to change file name in folder in php.

bool rename( string $source, string $destination, resource $context )

You can see bellow parameter in details:

$source: you need to give file path that you want to rename.

$destination: you need to give file path for destination source.

$context: this is optional, It specifies the context resource created with stream_context_create() function.

/* Existing File name */

$filePath = ‘images/demo.jpeg’;

/* New File name */

$newFileName = ‘images/demo_new.jpeg’;

/* Rename File name */

if( !rename($filePath, $newFileName) ) <

echo «File can’t be renamed!»;

>

else <

echo «File has been renamed!»;

>

?>

✌️ Like this article? Follow me on Twitter and Facebook. You can also subscribe to RSS Feed.

You might also like.

Источник

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