Creating a folder when I run file_put_contents()

modification of above answer to make it a bit more generic, (automatically detects and creates folder from arbitrary filename on system slashes)

ps previous answer is awesome

/**
 * create file with content, and create folder structure if doesn't exist 
 * @param String $filepath
 * @param String $message
 */
function forceFilePutContents ($filepath, $message){
    try {
        $isInFolder = preg_match("/^(.*)\/([^\/]+)$/", $filepath, $filepathMatches);
        if($isInFolder) {
            $folderName = $filepathMatches[1];
            $fileName = $filepathMatches[2];
            if (!is_dir($folderName)) {
                mkdir($folderName, 0777, true);
            }
        }
        file_put_contents($filepath, $message);
    } catch (Exception $e) {
        echo "ERR: error writing '$message' to '$filepath', ". $e->getMessage();
    }
}

file_put_contents() does not create the directory structure. Only the file.

You will need to add logic to your script to test if the month directory exists. If not, use mkdir() first.

if (!is_dir('upload/promotions/' . $month)) {
  // dir doesn't exist, make it
  mkdir('upload/promotions/' . $month);
}

file_put_contents('upload/promotions/' . $month . '/' . $image, $contents_data);

Update: mkdir() accepts a third parameter of $recursive which will create any missing directory structure. Might be useful if you need to create multiple directories.

Example with recursive and directory permissions set to 777:

mkdir('upload/promotions/' . $month, 0777, true);

Tags:

Php