PHP mkdir() 函数 - 如果文件夹存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11454917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:33:30  来源:igfitidea点击:

PHP mkdir() Function - If Folder Exists

phpforms

提问by ItsJoeTurner

Possible Duplicate:
PHP uploading script - create folder automatically

可能重复:
PHP 上传脚本 - 自动创建文件夹

I have a PHP Script that creates a folder based on a form. I'm wondering if there is a way to NOt create and replace that folder if it already exists?

我有一个基于表单创建文件夹的 PHP 脚本。我想知道是否有办法不创建和替换该文件夹(如果该文件夹已存在)?

<?php 
mkdir("QuickLinks/$_POST[contractno]");
?>

回答by Zbigniew

You can use is_dir:

您可以使用is_dir

<?php 
$path = "QuickLinks/$_POST[contractno]";
if(!is_dir($path)){
  mkdir($path);
}
?>

回答by Jon

In general:

一般来说:

$dirname = "whatever";
if (!is_dir($dirname)) {
    mkdir($dirname);
}

In particular: be very carefulwhen doing filesystem (or any other type of sensitive) operations that involve user input! The current example (create a directory) doesn't leave much of an open attack surface, but validating the input can never hurt.

特别是:在进行涉及用户输入的文件系统(或任何其他类型的敏感)操作时要非常小心!当前示例(创建目录)没有留下太多开放的攻击面,但验证输入永远不会受到伤害。

回答by Federkun

Use is_dirto check if folder exists

使用is_dir检查文件夹是否存在

$dir = "/my/path/to/dir";
if (!is_dir($dir)) {
    if (false === @mkdir($dir, 0777, true)) {
        throw new \RuntimeException(sprintf('Unable to create the %s directory', $dir));
    }
}

Attention to the uncontrolled input, it is very dangerous!

注意不受控制的输入,非常危险!

回答by cek-cek

You can try:

你可以试试:

<?php 
    if (!is_dir("QuickLinks/$_POST[contractno]"))
        mkdir("QuickLinks/$_POST[contractno]");
?>

回答by oktopus

Use the is_dir-function of PHP to check if there is already a directory and call the mkdir-function only if there isn't one.

使用 PHP 的 is_dir-function 来检查是否已经存在目录,如果没有则调用 mkdir-function。

回答by Damien Locque

回答by Benoit

Do some validation rules (regexp) here before using POST variable to create the directory !

在使用 POST 变量创建目录之前,请在此处执行一些验证规则(regexp)!

if(!file_exists("QuickLinks/$_POST[contractno]"))
    mkdir("QuickLinks/$_POST[contractno]");