- How to rename a file in PHP
- Take your skills to the next level ⚡️
- About
- Search
- Tags
- 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
- rename
- Список параметров
- Возвращаемые значения
- Список изменений
- Примеры
- 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.
- Google reCAPTCHA v3 in PHP
- Merge two or more tables in phpMyAdmin
- Check if a file exists in PHP
- Replace image src in HTML using PHP
- Submit a form without page refresh using jQuery, Ajax, PHP and MySQL
- How to generate random password using PHP and MySQL
- Leave a Reply Cancel reply
- Search your query
- Recent Posts
- Tags
- Join us
- Top Posts
- Explore the article
- Quick Links
- Privacy Overview
How to rename a file in PHP
To rename a file in PHP, you need to call the rename() function.
The PHP rename() function allows you to rename a file or a directory by passing the old and new names for that file or directory.
The syntax of rename() is as follows:
- The $from string specifies the file you want to change
- The $to string specifies the new file name
- The $context for a custom context stream. It’s optional and not needed most of the time
For example, the code below will rename index.php to server.php :
The rename() function will move the file between directories when necessary.
Suppose you have the following file structure for your project:
When you rename the index.php file using the following code:
Then the index.php file will be moved from the project folder.
The new file structure will be as shown below:
Without passing the location path, PHP will move the file to the current working directory (where you run the code from)
To avoid getting your file moved by the rename() function, you need to pass the same path in the $from and $to parameters.
The above code will rename the index.php file inside the project folder to server.php without moving it.
And that’s how you rename a file in PHP using the rename() function. Easy, right?
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
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
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()
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.
Google reCAPTCHA v3 in PHP
Merge two or more tables in phpMyAdmin
Check if a file exists in PHP
Replace image src in HTML using PHP
Submit a form without page refresh using jQuery, Ajax, PHP and MySQL
How to generate random password using PHP and MySQL
Leave a Reply Cancel reply
Search your query
Recent Posts
- Create a MySQL Database on Linux via Command Line July 22, 2023
- 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
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.