【问题标题】:How to rename a directory in PHP to a Unique ID? [duplicate]如何将 PHP 中的目录重命名为唯一 ID? [复制]
【发布时间】:2013-12-31 00:30:19
【问题描述】:

我对 PHP 有点熟悉,虽然我正在尝试使用我以前从未真正做过的 PHP 脚本:

$src = "/home/user/public_html/test1";
$dest = "/home/user/public_html/test2";
shell_exec("cp -r $src $dest");
echo "Directory successfully created."; //output when done
rename("$dest","uniqid();");

这个脚本应该复制一个目录的文件,这样新创建的目录就是/home/user/public_html/test2/test1。

但是,因为这个脚本应该是动态使用的,所以我希望 rename 函数将 $dest 重命名为 uniqid();功能。

任何人都可以为我编译一个可以执行此操作的脚本或提供有关如何执行此操作的说明吗?

谢谢。

【问题讨论】:

  • PHP 具有执行此操作的内置函数。无需访问外壳。这是文档中的一个快速搜索;)
  • 您不必复制然后重命名,只需复制并在目标中使用您希望它所在的目录。

标签: php


【解决方案1】:

不确定我是否明白这里的想法,但您应该将这个 rename("$dest","uniqid();"); 更改为 rename($dest,uniqid());。去掉引号和分号。

【讨论】:

    【解决方案2】:

    给你:)

    $info = array();
    $info['src'] = "/home/user/public_html/test1";
    $info['dest'] = "/home/user/public_html/".uniqid();
    
    // another thought for dest name if you want to easily sort it and guarantee unique-ness
    // $info ['dest'] = "/home/user/public_html/".uniqid(time().'.'.microtime(true).'.', true);
    
    // make sure directory doesn't exist or else overwriting will occur
    $info['dir_test'] = is_dir($dest);
    if(!$info['dir_test'])
    {
        $info['copy_result'] = copy($info['src'], $info['dest']);
        if($info['copy_result'])
        {
            $info['text_result'] = 'copy success :)';
        }
        else
        {
            $info['text_result'] = 'copy failed :(';
        }
    }
    else
    {
        $info['text_result'] = 'destination already exists! - '.$destination;
    }
    
    echo '<pre>'.print_r($info, true).'</pre>';
    

    【讨论】:

    • 这段代码不会删除旧目录。
    • @Michael 我是不是误会了什么? This script is supposed to copy the files of a directory
    • 对不起,我的错。错过了那部分。
    • @Michael 看来 OP 可能正在执行某种备份/版本控制程序,因此他们也需要保留旧文件 :)
    • 是的,我被标题弄糊涂了。我假设他想重命名标题中提到的文件夹。然后,如果他使用copy() 函数,他还必须删除旧的。 :)
    猜你喜欢
    • 1970-01-01
    • 2020-01-11
    • 2016-09-21
    • 2015-07-29
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 2018-05-20
    相关资源
    最近更新 更多