使用php重命名文件夹中的所有文件 [英] Using php to rename all files in folder

查看:311
本文介绍了使用php重命名文件夹中的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的php程序员在这里.我一直在尝试通过替换扩展名来重命名文件夹中的所有文件.

我正在使用的代码来自类似的问题的答案这样.

if ($handle = opendir('/public_html/testfolder/')) {
while (false !== ($fileName = readdir($handle))) {
    $newName = str_replace(".php",".html",$fileName);
    rename($fileName, $newName);
}
closedir($handle);

}

运行代码时没有任何错误,但是文件名没有更改.

对为什么这种方法无效的任何见解?我的权限设置应允许.

谢谢.

当检查rename()的返回值时,我得到一个空白页,现在尝试使用glob()进行操作,这可能比opendir更好.

使用下面的第二个代码段,我可以打印$ newfiles的内容.因此该数组存在,但是str_replace + named()代码片段无法更改文件名.

$files = glob('testfolder/*');


foreach($files as $newfiles) 
    {

    //This code doesn't work:

            $change = str_replace('php','html',$newfiles);
    rename($newfiles,$change);

           // But printing $newfiles works fine
           print_r($newfiles);
}

解决方案

以下是简单的解决方案:

PHP代码:

// your folder name, here I am using templates in root
$directory = 'templates/';
foreach (glob($directory."*.html") as $filename) {
    $file = realpath($filename);
    rename($file, str_replace(".html",".php",$file));
}

以上代码将转换 .php

中的所有 .html 文件

new php programmer here. I have been trying to rename all the files in a folder by replacing the extension.

The code I'm using is from the answer to a similar question on SO.

if ($handle = opendir('/public_html/testfolder/')) {
while (false !== ($fileName = readdir($handle))) {
    $newName = str_replace(".php",".html",$fileName);
    rename($fileName, $newName);
}
closedir($handle);

}

I get no errors when running the code, but no changes are made to the filenames.

Any insight on why this isn't working? My permission settings should allow it.

Thanks in advance.

EDIT: I get a blank page when checking the return value of rename(), now trying something with glob() which might be a better option than opendir...?

EDIT 2: With the 2nd code snippet below, I can print the contents of $newfiles. So the array exists, but the str_replace + rename() snippet fails to change the filename.

$files = glob('testfolder/*');


foreach($files as $newfiles) 
    {

    //This code doesn't work:

            $change = str_replace('php','html',$newfiles);
    rename($newfiles,$change);

           // But printing $newfiles works fine
           print_r($newfiles);
}

解决方案

Here is the simple solution:

PHP Code:

// your folder name, here I am using templates in root
$directory = 'templates/';
foreach (glob($directory."*.html") as $filename) {
    $file = realpath($filename);
    rename($file, str_replace(".html",".php",$file));
}

Above code will convert all .html file in .php

这篇关于使用php重命名文件夹中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆