- Переименовать или переместить файл или папку
- Переместить файл
- rename
- Список параметров
- Возвращаемые значения
- Список изменений
- Примеры
- PHP Rename File
- Introduction to the PHP rename file function
- PHP rename file examples
- 1) Simple PHP rename file example
- 2) Rename and move the file
- 3) PHP rename multiple files helper function
- Summary
- How to rename a file or directory in PHP
- Syntax
- Parameters
- Example 1: Rename file name
- Example 2: Rename directory name
- Example 3: Use the rename function to move a file
- You may also like.
- Get current page URL in PHP
- Replace image src in HTML using PHP
- How to remove an extension from a filename in PHP
- Insert an array into a MySQL database using PHP
- How to convert PHP array to JavaScript array
- Consume a REST API in PHP
- Leave a Reply Cancel reply
- Search your query
- Recent Posts
- Tags
- Join us
- Top Posts
- Explore the article
- Quick Links
- Privacy Overview
Переименовать или переместить файл или папку
Изменить имя файла или папки можно через функцию rename() .
// переименовать папку «img» в «images» rename('img', 'images'); // переименовать файл «image.jpg» в «picture.jpg» rename('image.jpg', 'picture.jpg');
Если указанного файла не будет, то PHP просто вернёт предупреждение, что указанный файл не найден.
Переместить файл
Перенести файл или папку можно также через функцию rename() .
// перенести «picture.jpg» в папку «images» rename('picture.jpg', 'images/picture.jpg');
Обновлено: 09 августа 2021 | История изменений
Авторизуйтесь, чтобы добавлять комментарии
- Создание файла
- Добавить строку в файл
- Вывести содержимое файла
- Проверить файл на существование
- Изменить строку в файле
- Удалить файл
- Переименовать или переместить файл или папку
- Копировать файл
- Вывести содержимое в папке
- Создать символическую ссылку
- Скачать файл из интернета на сервер
- Соединить текстовые файлы в один файл
- Скачать файл на сервере
- Чтение XML
- Работа с JSON
- Передать в JavaScript данные в формате JSON
- Работа с CSV
- Вывод данных с Excel-файла
- Хеш файла
rename
Пытается переименовать oldname в newname , перенося файл между директориями, если необходимо. Если newname существует, то он будет перезаписан.
Список параметров
Замечание:
Старое имя. Обёртка, используемая в oldname должна совпадать с обёрткой, используемой в newname .
Замечание: Поддержка контекста была добавлена в PHP 5.0.0. Для описания контекстов смотрите раздел Потоки.
Возвращаемые значения
Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.
Список изменений
Версия | Описание |
---|---|
5.3.1 | rename() теперь может переименовывать файлы между дисками в Windows. |
5.0.0 | rename() теперь также может быть использована с некоторыми обёртками URL. Обратитесь к Поддерживаемые протоколы и обработчики (wrappers) для получения списка обёрток, которые поддерживают rename() . |
4.3.3 | rename() теперь может переименовать файлы, находящиеся на другом разделе в ОС, основанных на *nix, подразумевая, что предоставлены соответствующие права на эти файлы. Могут быть сгенерировано предупреждение, если результирующая файловая система не позволяет совершать на файлах системные вызовы chown() или chmod() — например, если результирующей файловой системой является FAT. |
Примеры
Пример #1 Пример использования функции rename()
PHP Rename File
Summary: in this tutorial, you will learn how to rename a file in PHP by using the rename() function.
Introduction to the PHP rename file function
To rename a file to the new one, you use the rename() function:
rename ( string $oldname , string $newname , resource $context = ? ) : bool
Code language: PHP (php)
The rename() function has three parameters:
- $oldname is the name of the file that you want to rename.
- $newname is the new name of the file.
- $context is a valid context resource
The rename() function returns true if the $oldname file is renamed successfully or false otherwise.
If the $oldname file and $newname has a different directory, the rename() function will move the file from the current directory to the new one and rename the file.
Note that in case the $newname file already exists, the rename() function will overwrite it by the $oldname file.
PHP rename file examples
Let’s take some examples of renaming a file in PHP
1) Simple PHP rename file example
The following example uses the rename() function to rename the readme.txt file to readme_v2.txt file in the same directory:
$oldname = 'readme.txt'; $newname = 'readme_v2.txt'; if (rename($oldname, $newname)) < $message = sprintf( 'The file %s was renamed to %s successfully!', $oldname, $newname ); > else < $message = sprintf( 'There was an error renaming file %s', $oldname ); > echo $message;
Code language: HTML, XML (xml)
2) Rename and move the file
The following example uses the rename() function to move the readme.txt to the public directory and rename it to readme_v3.txt :
$oldname = 'readme.txt'; $newname = 'public/readme_v3.txt'; if (rename($oldname, $newname)) < $message = sprintf( 'The file %s was renamed to %s successfully!', $oldname, $newname ); > else < $message = sprintf( 'There was an error renaming file %s', $oldname ); > echo $message;
Code language: HTML, XML (xml)
3) PHP rename multiple files helper function
The following example defines a function that allows you to rename multiple files. The rename_files() function renames the files that match a pattern. It replaces a substring in the filenames with a new string.
function rename_files(string $pattern, string $search, string $replace) : array < $paths = glob($pattern); $results = []; foreach ($paths as $path) < // check if the pathname is a file if (!is_file($path)) < $results[$path] = false; continue; > // get the dir and filename $dirname = dirname($path); $filename = basename($path); // replace $search by $replace in the filename $new_path = $dirname . '/' . str_replace($search, $replace, $filename); // check if the new file exists if (file_exists($new_path)) < $results[$path] = false; continue; > // rename the file $results[$path] = rename($path, $new_path); > return $results; >
Code language: HTML, XML (xml)
- First, get the paths that match a pattern by using the glob() function. The glob() function returns an array of files (or directories) that match a pattern.
- Second, for each path, check if it is a file before renaming.
The following uses the replace_files() function to rename all the *.md files in the pages directory to the *.html files:
rename_files('pages/*.md', '.md', '.html');
Code language: HTML, XML (xml)
Summary
How to rename a file or directory in PHP
In this article, we will explain to you how to rename a file or directory in PHP. It’s a very easy way to rename a file or directory in PHP.
Using the built-in rename() function, we can rename a file or directory. If the new name already exists, then the rename() function will overwrite it. Using this function we can also move a file to a different directory.
Similar article:
This function requires two arguments: the first is the name of the file you want to rename and the second is the new name of the file. This function returns true on success otherwise false.
Syntax
Parameters
- $oldname: It specifies the file or directory name which you want to rename.
- $newname: It specifies the new name of the file or directory.
- $context: This is an optional parameter. It specifies the behaviour of the stream.
Example 1: Rename file name
In the following example, we will see how to rename a file named file.txt to newfile.txt .
Example 2: Rename directory name
Let’s take a next example where we will see how to rename a directory named images to uploads .
Example 3: Use the rename function to move a file
In this last example, we’ll see how to move a file named file.txt to pages directory using rename() function.
Note: If a file or directory does not exist then rename() function will throw a warning so it is a good practise to check if a file exists or not using the file_exists() function before rename the file or directory.
That’s it for today.
Thank you for reading. Happy Coding.
You may also like.
Get current page URL in PHP
Replace image src in HTML using PHP
How to remove an extension from a filename in PHP
Insert an array into a MySQL database using PHP
How to convert PHP array to JavaScript array
Consume a REST API in PHP
Leave a Reply Cancel reply
Search your query
Recent Posts
- Connect to a MySQL Database Using the MySQL Command: A Comprehensive Guide July 16, 2023
- Connecting to SSH using a PEM File July 15, 2023
- How to Add the Body to the Mailto Link July 14, 2023
- How to Add a Subject Line to the Email Link July 13, 2023
- How to Create Mail and Phone Links in HTML July 12, 2023
Tags
Join us
Top Posts
Explore the article
We are not simply proficient at writing blog post, we’re excellent at explaining the way of learning which response to developers.
For any inquiries, contact us at [email protected] .
Quick Links
- We provide the best solution to your problem.
- We give you an example of each article.
- Provide an example source code for you to download.
- We offer live demos where you can play with them.
- Quick answers to your questions via email or comment.
Clue Mediator © 2023. All Rights Reserved.
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.