【问题标题】:Why is this php mkdir / uniqid not working?为什么这个 php mkdir / uniqid 不起作用?
【发布时间】:2018-06-26 01:41:07
【问题描述】:

我有这段代码应该创建一个随机目录并将上传内容移到那里:

$uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . mkdir( 'assets/post/email_uploads/{uniqid(attachment_)}', 0777 ) . DIRECTORY_SEPARATOR . $_FILES[ 'file' ][ 'name' ];

路径assets/post/email_uploads/ 已经存在,所以随机文件夹应该进入email_uploads。我面临的问题是在DIRECTORY_SEPARATORs 之间放置什么并让一切正常。

当我尝试mkdir( 'assets/post/email_uploads/{uniqid(attachment_)}', 0777 )

mkdir( 'assets/post/email_uploads/'.uniqid(attachment_), 0777 ) - 未创建文件夹,上传放在根目录。

当我尝试时

$attchmentPath = 'assets/post/email_uploads/';
$uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $attchmentPath.mkdir( uniqid(attachment_), 0777 ) . DIRECTORY_SEPARATOR . $_FILES[ 'file' ][ 'name' ];

$attchmentPath = 'assets/post/email_uploads/';
$randomDir = mkdir( uniqid(attachment_), 0777 );
$newPath = $attchmentPath.$randomDir;
$uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $newPath . DIRECTORY_SEPARATOR . $_FILES[ 'file' ][ 'name' ];

文件夹是在根目录下创建的,而不是所需的路径,文件根本没有上传。

【问题讨论】:

  • echo 'assets/post/email_uploads/{uniqid(attachment_)}'; - 现在这告诉你什么……?
  • 单引号还是双引号??函数调用需要在调用之前进行转义,如果要解析变量,则应该在双引号内 - 在单引号内,你看到的就是你得到的
  • @CBroe 当我回显它按原样输出时 - assets/post/email_uploads/{uniqid(attachment_)} 但是当我回显 'assets/post/email_uploads/'.uniqid(attachment_) 它输出所需的路径但仍然无法正常工作
  • @RamRaider 我刚刚用双引号尝试过 - 没有成功

标签: php random file-upload mkdir


【解决方案1】:

也许是这样的? uniqid 的内容应该被引用(除非它是一个常量)并且对uniqid 的函数调用需要从单引号字符串中转义

$dir=mkdir( __DIR__ . '/assets/post/email_uploads/'.uniqid('attachment_'), 0777 );
$name=$_FILES['file']['name'];
$uploadPath = $dir . DIRECTORY_SEPARATOR . $name;

您可以尝试使用递归函数来确保目录路径存在

function createpath( $path=NULL, $perm=0644 ) {
    if( !file_exists( $path ) ) {
        createpath( dirname( $path ) );
        mkdir( $path, $perm, TRUE );
        clearstatcache();
    }
    return $path;
}

$targetpath=__DIR__ . '/assets/post/email_uploads/'.uniqid( 'attachment_' );
$path=createpath( $targetpath );
echo $path;

【讨论】:

  • 我刚试过这个 - uniqid 文件夹没有被创建,文件被上传到根目录之外
  • 如果你回显 __DIR__ . '/assets/post/email_uploads/'.uniqid('attachment_') 会产生什么结果?
  • F:\Projects\xxxxxx\yyyyyy\src/assets/post/email_uploads/attachment_5a5f195cdd9c1
  • 你有对该文件夹路径的写权限吗?
  • 上传的文件位于F:,但未创建随机文件夹
【解决方案2】:

我通过简单地添加一个参数来解决这个问题 - TRUE in mkdir 我遗漏了。所以功能代码是 - mkdir($path, 0777, TRUE) 其中$path 是要创建的目录的路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 2010-10-20
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多