百科狗-知识改变命运!
--

file_put_contents() - 将一个字符串写入文件 - php 文件目录函数

梵高1年前 (2023-11-21)阅读数 21#技术干货
文章标签函数

file_put_contents()

(PHP 5, PHP 7)

将一个字符串写入文件

说明

file_put_contents(string $filename,mixed $data[,int $flags= 0[,resource $context]]): int

和依次调用fopen(),fwrite()以及fclose()功能一样。

If$filenamedoes not exist, the file is created. Otherwise, the existing file is overwritten, unless theFILE_APPENDflag is set.

参数

$filename

要被写入数据的文件名。

$data

要写入的数据。类型可以是string,array或者是stream资源(如上面所说的那样)。

file_put_contents() - 将一个字符串写入文件 - php 文件目录函数

如果$data指定为 stream 资源,这里 stream 中所保存的缓存数据将被写入到指定文件中,这种用法就相似于使用stream_copy_to_stream()函数。

参数$data可以是数组(但不能为多维数组),这就相当于file_put_contents($filename, join('',$array))

$flags

$flags的值可以是以下 flag 使用 OR (|)运算符进行的组合。

Available flags
Flag描述
FILE_USE_INCLUDE_PATH在 include 目录里搜索$filename。更多信息可参见include_path。
FILE_APPEND如果文件$filename已经存在,追加数据而不是覆盖。
LOCK_EX在写入时获得一个独占锁。
$context

一个 context 资源。

返回值

该函数将返回写入到文件内数据的字节数,失败时返回FALSE

Warning

此函数可能返回布尔值FALSE,但也可能返回等同于FALSE的非布尔值。请阅读布尔类型章节以获取更多信息。应使用===运算符来测试此函数的返回值。

范例

Simple usage example

Using flags

更新日志

版本说明
5.0.0Added context support
5.1.0添加了对LOCK_EX的支持和$data参数处理 stream 资源的功能。

注释

Note:此函数可安全用于二进制对象。

Tip

如已启用fopen 包装器,在此函数中, URL 可作为文件名。关于如何指定文件名详见fopen()。各种wapper 的不同功能请参见支持的协议和封装协议,注意其用法及其可提供的预定义变量。

参见

  • fopen() 打开文件或者 URL
  • fwrite() 写入文件(可安全用于二进制文件)
  • file_get_contents() 将整个文件读入一个字符串
  • stream_context_create() 创建资源流上下文
File put contents fails if you try to put a file in a directory that doesn't exist. This creates the directory. 
A slightly simplified version of the method: http://php.net/manual/ru/function.file-put-contents.php#84180 
It should be obvious that this should only be used if you're making one write, if you are writing multiple times to the same file you should handle it yourself with fopen and fwrite, the fclose when you are done writing.
Benchmark below:
file_put_contents() for 1,000,000 writes - average of 3 benchmarks:
 real 0m3.932s
 user 0m2.487s
 sys 0m1.437s
fopen() fwrite() for 1,000,000 writes, fclose() - average of 3 benchmarks:
 real 0m2.265s
 user 0m1.819s
 sys 0m0.445s
Please note that when saving using an FTP host, an additional stream context must be passed through telling PHP to overwrite the file. 
It's worth noting that you must make sure to use the correct path when working with this function. I was using it to help with logging in an error handler and sometimes it would work - while other times it wouldn't. In the end it was because sometimes it was called from different paths resulting in a failure to write to the log file.
__DIR__ is your friend.
Make sure not to corrupt anything in case of failure. 
This functionality is now implemented in the PEAR package PHP_Compat.
More information about using this function without upgrading your version of PHP can be found on the below link:
http://pear.php.net/package/PHP_Compat
It's important to understand that LOCK_EX will not prevent reading the file unless you also explicitly acquire a read lock (shared locked) with the PHP 'flock' function.
i.e. in concurrent scenarios file_get_contents may return empty if you don't wrap it like this:

If you have code that does a file_get_contents on a file, changes the string, then re-saves using file_put_contents, you better be sure to do this correctly or your file will randomly wipe itself out.
Calling file_put_contents within a destructor will cause the file to be written in SERVER_ROOT...
In reply to the previous note:
If you want to emulate this function in PHP4, you need to return the bytes written as well as support for arrays, flags.
I can only figure out the FILE_APPEND flag and array support. If I could figure out "resource context" and the other flags, I would include those too. 
file_put_contents does not issue an error message if file name is incorrect(for example has improper symbols on the end of it /n,/t)
that is why use trim() for file name.
$name=trim($name);
file_put_contents($name,$content);
I'm updating a function that was posted, as it would fail if there was no directory. It also returns the final value so you can determine if the actual file was written.
  public static function file_force_contents($dir, $contents){
    $parts = explode('/', $dir);
    $file = array_pop($parts);
    $dir = '';
    foreach($parts as $part) {
      if (! is_dir($dir .= "{$part}/")) mkdir($dir);
    }
    return file_put_contents("{$dir}{$file}", $contents);
  }
File put contents fails if you try to put a file in a directory that doesn't exist. This function creates the directory.
 
i have updated code of "TrentTompkins at gmail dot com". thanks 
I had some troubles using file_put_contents with an absolute but no canonicalized path (eg. w:/htdocs/pri/../test/log.txt): on windows environment php was unable to create the file also using the realpath function .
I had to use fopen and frwite functions to write the data.
This should also handle $filename from other than root and also $filename without path. 
function file_force_contents($filename, $data, $per = 0755, $flags = 0) {
    $fn = "";
  if(substr($filename, 0, 1) === "/") $fn .= "/";
  $parts = explode("/", $filename);
    $file = array_pop($parts);
   
    foreach($parts as $part) {
      if(!is_dir($fn .= "$part")) mkdir($fn, $per, true);
    $fn .= "/";
  }
    file_put_contents($fn.$file, $data, $flags);  
}
To upload file from your localhost to any FTP server.
pease note 'ftp_chdir' has been used instead of putting direct remote file path....in ftp_put ...remoth file should be only file name 
I faced the problem of converting a downloaded csv file that had Windows-1252 encoding, so to convert it to UTF-8 this worked for me:
$from = 'Windows-1252';
$to = 'UTF-8';
$content = file_get_contents($this->path());
file_put_contents($this->path(), mb_convert_encoding($content, $to, $from));
where "$this->path()" has the path of the file... Using this the file is converted from Windows-1252 to UTF-8.
With this you can import it with mysqlimport with no problems.
I use file_put_contents() as a method of very simple hit counters. These are two different examples of extremely simple hit counters, put on one line of code, each.
Keep in mind that they're not all that efficient. You must have a file called counter.txt with the initial value of 0.
For a text hit counter:

Or a graphic hit counter:

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)