php: create directory on form submit?

10,482

Solution 1

It might be a good idea to make sure that the directory you are handling is indeed a directory. This code works... edit as you please.

define("PATH", "/home/born05/htdocs/swish_s/Swish");

$test = "set";
$_POST["dirname"] = "test";


if (isset($test)) {
  //get value of inputfield
  $dir = $_POST['dirname'];
  //set the target path ??

$targetfilename = PATH . '/' . $dir;

if (!is_file($dir) && !is_dir($dir)) {
    mkdir($dir); //create the directory
    chmod($targetfilename, 0777); //make it writable
}
else
{
    echo "{$dir} exists and is a valid dir";
}

Good luck!

Edited: comment was a good hint ;)

Solution 2

You have to use

!is_dir($dir)

instead of

!file_exists($dir)

it's not a file, it's a directory!

Good luck!

Solution 3

You can use is_dir().

Share:
10,482
matt
Author by

matt

Updated on June 21, 2022

Comments

  • matt
    matt about 2 years

    I am wondering what I am doing wrong. I'm inside of PATH and I want to create a folder inside of PATH. I want to check if the folder already exists and, if not, create one. Getting the name of the folder from an input field with name of "dirname".

    if (isset($_POST['createDir'])) {
        //get value of inputfield
        $dir = $_POST['dirname'];
        //set the target path ??
        $targetfilename = PATH . '/' . $dir;
        if (!file_exists($dir)) {
            mkdir($dir); //create the directory
            chmod($targetfilename, 0777); //make it writable
        }
    }