简体   繁体   English

重命名文件夹中的所有文件

[英]rename all the files in a folder

i have been trying to rename all the files (images) in a folder on my website but it does not work.我一直试图重命名我网站上一个文件夹中的所有文件(图像),但它不起作用。 the files are not renamed.文件未重命名。

i have an input field for 'name' i want to use that name, add a uniqid and rename all the files.我有一个“名称”的输入字段,我想使用该名称,添加一个 uniqid 并重命名所有文件。 here's the code that i am using:这是我正在使用的代码:

<?php
if(isset($_POST['submit2'])){
$name = $_POST['name'];
$directory = glob("../basic_images/*.*");
{
if ($file != "." && $file != "..") {

    $newName = uniqid().$name;

    rename($directory.$file, $directory.$newName);
}}}
?>

besides, do i really need to _Post the $name variable?此外,我真的需要_Post $name 变量吗?

PS i want to rename all the files and then copy them to another folder. PS我想重命名所有文件,然后将它们复制到另一个文件夹。

You don't need to POST name您不需要发布name

glob is return you every files in folder with path // example /basic_images/test.jpg glob返回文件夹中的每个文件,路径为 // 示例 /basic_images/test.jpg

then you just do foreach to loop over files, and update its name.然后您只需执行foreach来循环文件,并更新其名称。

$path = "../basic_images/";
$directory = glob($path,"*.*");
foreach($directory as $file){
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    $newName = uniqid().$ext;
    rename($file, $path.$newName);
} 

read more about glob : http://php.net/manual/en/function.glob.php阅读有关glob更多信息: http : //php.net/manual/en/function.glob.php

so, i finally solved the problem.所以,我终于解决了这个问题。 now, instead of renaming the original files and then copying them to another folder, i just create new copies of the files with new names.现在,我不再重命名原始文件然后将它们复制到另一个文件夹,而是使用新名称创建文件的新副本。

This is the code final code that works for me:这是对我有用的代码最终代码:

if(isset($_POST['submit'])){

$path = "../posts_images/";
$files = glob("../basic_images/*.*");
foreach($files as $file){
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    $name = $_POST['new_name'];
    $pic = uniqid().$name;
    $newName = $pic.'.'.$ext;
    copy($file, $path.$newName);

}}

it is important to use $pic.'.'.$ext because without it the new files don't have any extension.使用$pic.'.'.$ext很重要,因为没有它,新文件没有任何扩展名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM