Skip to content

Instantly share code, notes, and snippets.

@alexey-kar
Forked from ofca-snippets/file_force_contents.php
Created November 19, 2020 10:00
Show Gist options
  • Save alexey-kar/22919b6e82a4db6483087ff88b9de19f to your computer and use it in GitHub Desktop.
Save alexey-kar/22919b6e82a4db6483087ff88b9de19f to your computer and use it in GitHub Desktop.
Extended version of php function "file_put_contents"
/**
* Extended version of function file_put_contents.
*
* This function will create all dirs in the path to the file,
* if they does not exists.
*
* @param string path to file
* @param string file content
* @param int flag taken by file_put_contents function
* @return bool false on failure, true on success
*/
function file_force_contents($file_path, $content, $flag = LOCK_EX)
{
// It's relative path, so we must change it to absolute
if ($file_path[0] != '/')
{
$file_path = DOCROOT.$file_path;
}
$dirname = pathinfo($file_path, PATHINFO_DIRNAME);
// Create directories if not exists
if ( ! file_exists($dirname))
{
// Create dirs
mkdir($dirname, 0777, TRUE);
// Set permissions (must be manually set to fix umask issues)
chmod($dirname, 0777);
}
// Create file
return (bool) file_put_contents($file_path, $content, $flag);
} // eo file_force_contents
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment