Skip to content

Instantly share code, notes, and snippets.

@ofca-snippets
Created September 15, 2012 23:07
Show Gist options
  • Save ofca-snippets/3730268 to your computer and use it in GitHub Desktop.
Save ofca-snippets/3730268 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
@hi2rashid
Copy link

permission 777 leaves the directory vulnerable to world

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment