PHP automatically creates directories and saves file functions

Source: Internet
Author: User

PHP Save the file, you can also automatically create a directory based on the file path, the code is as follows (note: PHP to version 5 or more):

<?php
/**
* Save File
*
* @param string $fileName file name (including relative paths)
* @param string $text file contents
* @return Boolean
*/
function SaveFile ($fileName, $text) {
if (! $fileName | |! $text)
return false;
if (MakeDir (DirName ($fileName)) {
if ($fp = fopen ($fileName, "w")) {
if (@fwrite ($FP, $text)) {
Fclose ($FP);
return true;
} else {
Fclose ($FP);
return false;
}
}
}
return false;
}
/**
* Create a directory continuously
*
* $dir Directory string @param string
* @param int $mode permission number
* @return Boolean
*/
function MakeDir ($dir, $mode =0755) {
/*function MakeDir ($dir, $mode = "0777") {In addition, 0777 cannot add single and double quotes.
After the addition, "0400" = 600 permissions, the department thought it would be like this, I also think not to pass * *
if (!dir) return false;
if (!file_exists ($dir)) {
return mkdir ($dir, $mode, true);
} else {
return true;
}
}
?>
Here is the test content and call the above function
<?php
$content = ' Here is the test content ';
if (SaveFile (' Dir/test.txt ', $content)) {
Echo ' Write success ';
}else{
Echo ' Write Failed ';
}
?>

Note: MakeDir is a directory creation function, and we are using recursive creation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.