简体   繁体   中英

Using mkdir(), directory not being created

$ad_title = $_POST['title'];
$ad_content = $_POST['content-ads']; 
$ad_region = $_POST['region']; 

if (!is_dir("uploads/".$ad_region)) {
    // dir doesn't exist, make it
    mkdir("uploads/".$ad_region);
    echo "directory created!";
}
else {
    echo "directory already exist!";
}

I am making a site and I am developing it in localhost for now. My save.php file and the uploads folders where the codes above is saved in the local directory

localhost/system/modules/new/

When I relocated the save.php file and the uploads folder in the directory

localhost/system/

all seems to be working now. But I want it to work in the

localhost/system/modules/new/ 

directory for better organization. Any help on how to make it work?

First thing I'd do is ensure that the paths are where you think they are.

Try this out

$ad_title = $_POST['title'];
$ad_content = $_POST['content-ads']; 
$ad_region = $_POST['region']; 

// Make sure the "uploads" directory is relative to this PHP file
$uploads = __DIR__ . '/uploads';

$path = $uploads . DIRECTORY_SEPARATOR . $ad_region;

// ensure that the path hasn't been tampered with by entering any relative paths
// into $_POST['region']
if (dirname($path) !== $uploads) {
    throw new Exception('Upload path has been unacceptably altered');
}

if (!is_dir($path)) {
    if (!mkdir($path, 0755, true)) {
        // you should probably catch this exception somewhere higher up in your
        // execution stack and log the details. You don't want end users
        // getting information about your filesystem
        throw new Exception(sprintf('Failed to create directory "%s"', $path));
    }

    // Similarly, you should only use this for debugging purposes
    printf('Directory "%s" created', $path);
} else {
    // and this too
    printf('Directory "%s" already exists', $path);
}

you can use relative path ../ such as mkdir("../uploads/".$ad_region)

or use absolution path, such as mkdir("/localhost/system/modules/new/".$ad_region)

ref: http://php.net/manual/en/function.mkdir.php

You can use absolute file paths, like "/var/www/system/modules/new/$ad_region" (unix structure).

Or, for example, if your save.php file is in directory "system" and you want to create the directory in "system/modules/new/" you can do

mkdir("./modules/new/$ad_region");

There is a third parameter for mkdir, recursive, which allows the creation of nested directories. For the second parameter you can simple pass 0, for example

mkdir("./modules/new/$ad_region", 0, true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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