PHP mkdir不再起作用了

So I have this code, at first mkdir was working fine until I wanted to tweak it a bit with $category and $random, even now if I reverse it it doesn't work maybe you can help me? Also how to generate $random code with checking if it already exists and do loop until it finds free one?

<?php

require_once('admin/connection.php');

$email=$_POST['email'];
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$description=$_POST['description'];
$category=$_POST['category'];
$fileToUpload=$_POST['fileToUpload'];



  if(isset($_POST['submit'])){
    $numbers = range(6, 1);
            $random = '';
            shuffle($numbers);
            foreach ($numbers as $number) {
                $random.= $number;
            }

if ("SELECT `application_ID` FROM `applications` WHERE `application_ID` = '".$random."'") {
            $numbers = range(6, 1);
            $random = '';
            shuffle($numbers);
            foreach ($numbers as $number) {
                $random.= $number;
            }
}


if (!file_exists("uploads/$category/$random")) {
    mkdir("uploads/$category/$random", 0777, true);
}
$target_dir = "uploads/$category/$random";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
//// Allow certain file formats
//if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
//&& $imageFileType != "gif" ) {
//    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
//    $uploadOk = 0;
//}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
$filename=basename( $_FILES['fileToUpload']['name']);




        // taking information from inputs and adding it to database tables.
        $query = "INSERT INTO applications VALUES ($random, '$email', '$first_name', '$last_name', '$description', '$category', NOW());";
       if ($conn->query($query) === TRUE) {
        $query2 = "INSERT INTO `uploads` (`application_ID`, `file`) VALUES ($random, '$filename');";
       if ($conn->query($query2) === TRUE) {
            echo "Good luck! <a href='index.php'>Home page</a>";
        } else {
            echo "Error: " . $query2 . "<br>" . $conn->error;
        } 
            echo "<br>Order detail success ";
        } else {
            echo "Error: " . $query . "<br>" . $conn->error;
        }     
        }

?>

<h3>Upload your application</h3>


<form method="post" enctype="multipart/form-data">
<input type="email" name="email" placeholder="Email" required><br>
<input type="text" name="first_name" placeholder="First name" required><br>
<input type="text" name="last_name" placeholder="Last name" required><br>
<input type="textarea" name="description" placeholder="Description" required><br>
<select name="category">
  <option value="front-end">Front-end developer</option>
  <option value="back-end">Back-end developer</option>
  <option value="design">Designer</option>
</select><br>
<input type="file" name="fileToUpload" placeholder="CV"><br>

<button type="submit" name="submit">Submit</button>
</form>

While I can't speak for exactly why mkdir isn't functioning in this scenario, you need to make a few changes in how you develop.

First off, use absolute URLs. It adds a bit of overhead in your initial development, but it is undoubtedly worth it. For example:

If you have an uploads directory in the same directory as your script, you could do something like this define('UPLOADS_DIR', realpath('uploads'));

Then, for your Category path: define('CAT_PATH', realpath(UPLOADS_DIR . "/" . $category));

And continue on that trend until your directories are all correctly mapped.

Next, throw this in the top of your script:

error_reporting(E_ALL);

Why do this?

Because you will get a false response upon trying to set the realpath if that path cannot be found. This means you will error out when trying to create a directory, instead of actually creating a directory somewhere else. With proper procedure (like making sure those constants aren't FALSE), you will know before trying to actually make the directory. That, and you will know beyond doubt that your paths are correct. That's invaluable information for any developer!

Get into the habit of developing with constants/variables that are mapped to real paths. The last thing you want is either typos or other human error causing errors inside your scripts. You set the path once and you never have to worry about errors again. Re-use the constant over and over, and rest assured your path is correct.

Error Reporting helps you to debug all the issues you're facing. Your goal when something doesn't work should be finding out what the cause is. There is nothing in programming that simply "does not work", rather, things just don't work yet. It is up to you to dig into the error(s) and find the solution(s).

Now - as for your problem

if (!file_exists("uploads/$category/$random")) {
    mkdir("uploads/$category/$random", 0777, true);
}

The code above has a few inherent problems. First, you're not checking if uploads/$category exists independently of $random. I'd personally change it to something like this:

if (!file_exists("uploads/$category")) {
    mkdir("uploads/$category", 0777, true);
}

if (!file_exists("uploads/$category/$random")) {
    mkdir("uploads/$category/$random", 0777, true);
}

Now that's if I wanted to make a really quick fix. Alternatively, I'd loop through each directory and make absolutely sure every directory in an entire path existed if I were using random paths, but that's just me. The above may work just fine for your needs.

You need some debugging - it seems like you're not utilizing stops inside a good IDE. If that's the case, just throw some debug information in that you can later discard/comment:

if (!file_exists("uploads/$category")) {
    mkdir("uploads/$category", 0777, true);
} else {
    echo "{$category} exists...<br>";
}

if (!file_exists("uploads/$category/$random")) {
    mkdir("uploads/$category/$random", 0777, true);
} else {
    echo "{$category}/{$random} exists...<br>";
}

The curly brackets are not necessary inside the echo as you probably already know, however, I'm in the habit.

Run the code. What happens? If it says both paths exist, and you are not seeing them, you've got errors in your paths/code. Try something like this to verify that you are actually creating the directories where you think you are:

if (!file_exists("uploads/$category")) {
    mkdir("uploads/$category", 0777, true);
} else {
    echo realpath("uploads/$category") . " exists...<br>";
}

if (!file_exists("uploads/$category/$random")) {
    mkdir("uploads/$category/$random", 0777, true);
} else {
    echo realpath("uploads/$category/$random") . " exists...<br>";
}

And thus, this is why you create realpath based constants. It alleviates the need for the above code, and completely puts your mind at ease when trying to debug things like a mkdir not functioning as expected.

Your goal with debugging this mkdir issue is very clear:

  1. Verify that the paths it's looking for/creating are exactly what you're thinking.
  2. Verify that, with the above correct, mkdir really isn't making the directories.
  3. Make sure error reporting is enabled so that if/when mkdir fails, you know why.
  4. Resolve the issue preventing mkdir from functioning as expected.

I can confidently assure you that there is no issue with mkdir as a PHP function. Something is preventing it from working - it is not broken. You must be in that mentality to really debug it.

That's all I can really think of on this, and I can't really understand your second question. Revisit your question to elaborate and I'll take a crack at answering the second question.

Best of luck to you!