Error when attempting to rename all the files in a directory (PHP)


I am practicing PHP on my computer using PHPStorm. I have a directory full of images that I placed in my project. These images were pulled off of a web page and all have names such as "attachment_56602224.jpg." I want to rename them to all numbers (like 1.jpg, 2.jpg) just for simplicity. Here's what I have so far:

$i = 1;
if ($handle = opendir('pics')) {
while (false !== ($fileName = readdir($handle))) {
    rename($fileName, $i);

Here is the error I am getting when I run it in my browser:

Warning: rename(.,1): The process cannot access the file because it is being used by another process. (code: 32) in C:\Users\Mike\PhpstormProjects\php\learn.php on line 12

Warning: rename(..,2): Access is denied. (code: 5) in C:\Users\Mike\PhpstormProjects\php\learn.php on line 12

Warning: rename(attachment_56602224.jpg,3): The system cannot find the file specified. (code: 2) in C:\Users\Mike\PhpstormProjects\php\learn.php on line 12

And that last error repeats for every image.




the first thing you should do is checking if the files that you are reading are effectively files and not directories, also you should use the relative path for the source and destination file you are renaming. In that snippet code, you are trying to rename a file in the root directory of your project and not in the "pics" subfolder.

People are also looking for solutions to the problem: php - .htaccess deny from all stops access on website


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.