为什么iphone不把指纹识别不灵敏了怎么办放在背后logo上

PHP中fwrite与file_put_contents的区别-Php常用代码-Php教程-壹聚教程网PHP中fwrite与file_put_contents的区别
PHP中fwrite与file_put_contents在细节上在区别但在性能上file_put_contents更强大了,我们下面举例来对比一下吧。
相同点:file_put_contents() 函数把一个字符串写入文件中,与依次调用 (),fwrite() 以及 fclose() 功能一样。
不同点:在file_put_contents()函数中使用 FILE_APPEND 可避免删除文件中已有的内容,即实现多次写入同一个文件时的追加功能。
echo file_put_contents(&test.txt&,&Hello World. Testing!&,FILE_APPEND);
file_put_contents是以追加的形式将字符串写入到test.txt中,
fwrtie则是会清除之前的记录,只保留当前写入的内容
$file = fopen(&test.txt&,&w&);
echo fwrite($file,&Hello World. Testing!&);
fclose($file);
file_put_contents代替fwrite优点多多
如下为file_put_contents的实例代码:
$filename = 'file.txt';
$word = &你好!\r\nwebkaka&;& //双引号会换行 单引号不换行
file_put_contents($filename, $word);
同样的功能使用fwrite的实例代码:
$filename = 'file.txt';
$word = &你好!\r\nwebkaka&;& //双引号会换行& 单引号不换行
$fh = fopen($filename, &w&); //w从开头写入 a追加写入
echo fwrite($fh, $word);
fclose($fh);
从以上两个例子看出,其实file_put_contents是fopen、fwrite、fclose三合一的简化写法,这对程序代码的优化是有好处的,一方面在代码量上有所减少,另一方面不会出现fclose漏写的不严密代码,在调试、维护上方便很多。
上述例子里,file_put_contents是从头写入,如果要追加写入,怎么办呢?
在file_put_contents的语法里,有个参数FILE_APPEND,这是追加写入的声明。实例代码如下:
echo file_put_contents('file.txt', &This is another something.&, FILE_APPEND);
FILE_APPEND就是追加写入的声明。在追加写入时,为了避免其他人同时操作,往往需要锁定文件,这时需要加多一个LOCK_EX的声明,写法如下:
echo file_put_contents('file.txt', &This is another something.&, FILE_APPEND|LOCK_EX);
注意,以上代码中echo输出到显示器里的是写入文件字符串的长度。
Warning: fopen(file.txt) [function.fopen]: failed to open stream: Permission denied
当写入文件时,有时会遇到上述问题,这是因为文件没有写权限的原因。为了避免这个错误的出现,在写入文件时需要判断下文件是否可写,这需要用到is_writable()这个函数。实例代码如下:
$filename = 'file.txt';
if (is_writable($filename)) {
echo file_put_contents($filename, &This is another something.&, FILE_APPEND);
&&& echo &文件 $filename 不可写&;
fwrite简单的把数据写到handler里面
file_put_contents可能需要处理contenxt,数据类型为mixed,需要更多处理
虽然看file_put_contents的函数说明:和依次调用 fopen(),fwrite() 以及 fclose() 功能一样。
但是肯定有细微差别的,尤其是在重复写入大量数据的时候,file_put_contents无疑会重复的fopen,fclose .而 fwrite则可以只一次fopen,fwrite即可
写个简单程序测试一下,一个250M文件
$data = str_repeat(&-&,$len);
$start = microtime(true);
$fp = fopen(&/tmp/b&,&w&);
fwrite($fp,$data,$len);
fclose($fp);
$end = microtime(true);
echo &elied time:&.($end-$start).&\n&;
$start = microtime(true);
file_put_contents(&/tmp/a&,$data);
$end = microtime(true);
echo &elipsed time:&.($end-$start).&\n&;
silver@silver-desktop:~/php$ php fwrite_VS_file_put_contents.php
elipsed time:6.3
elipsed time:9.6
silver@silver-desktop:~/php$ php fwrite_VS_file_put_contents.php
elipsed time:6.
elipsed time:9.1
结论:多次执行结果类试,说明fopen,fwrite,fclose方式比直接file_put_contents要快一点!
那么为什么呢? 查看源代码
我用的ubuntu12.04
直接sudo apt-get source php5
解压:silver@silver-desktop:~/php/php5-5.3.3
查找函数fwrite 函数:silver@silver-desktop:~/php/php5-5.3.3$ grep -rn &PHP_FUNCTION(fwrite)& .
./ext/standard/file.c:1233:PHPAPI PHP_FUNCTION(fwrite)
./ext/standard/file.h:43:PHPAPI PHP_FUNCTION(fwrite);
找到对应源码,该函数非常简单:
PHP_FUNCTION(fwrite)
zval *arg1;
char *arg2;
long arg3 = 0;
char *buffer = NULL;
php_stream *
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, &rs|l&, &arg1, &arg2, &arg2len, &arg3) == FAILURE) {
RETURN_FALSE;
if (ZEND_NUM_ARGS() == 2) {
num_bytes = arg2
num_bytes = MAX(0, MIN((int)arg3, arg2len));
if (!num_bytes) {
RETURN_LONG(0);
PHP_STREAM_TO_ZVAL(stream, &arg1);
if (PG(magic_quotes_runtime)) {
buffer = estrndup(arg2, num_bytes);
php_stripslashes(buffer, &num_bytes TSRMLS_CC);
ret = php_stream_write(stream, buffer ? buffer : arg2, num_bytes);
if (buffer) {
efree(buffer);
RETURN_LONG(ret);
file_put_contents
该函数的处理操作就多多了
PHP_FUNCTION(file_put_contents)
php_stream *
int filename_
int numbytes = 0;
long flags = 0;
zval *zcontext = NULL;
php_stream_context *context = NULL;
php_stream *srcstream = NULL;
char mode[3] = &wb&;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, &sz/|lr!&, &filename, &filename_len, &data, &flags, &zcontext) == FAILURE) {
if (Z_TYPE_P(data) == IS_RESOURCE) {
php_stream_from_zval(srcstream, &data);
context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT);
if (flags & PHP_FILE_APPEND) {
mode[0] = &a&;
} else if (flags & LOCK_EX) {
/* check to make sure we are dealing with a regular file */
if (php_memnstr(filename, &://&, sizeof(&://&) & 1, filename + filename_len)) {
if (strncasecmp(filename, &file://&, sizeof(&file://&) & 1)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, &Exclusive locks may only be set for regular files&);
RETURN_FALSE;
mode[0] = &c&;
mode[2] = &\0&;
stream = php_stream_open_wrapper_ex(filename, mode, ((flags & PHP_FILE_USE_INCLUDE_PATH) ? USE_PATH : 0) | ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, context);
if (stream == NULL) {
RETURN_FALSE;
if (flags & LOCK_EX && (!php_stream_supports_lock(stream) || php_stream_lock(stream, LOCK_EX))) {
php_stream_close(stream);
php_error_docref(NULL TSRMLS_CC, E_WARNING, &Exclusive locks are not supported for this stream&);
RETURN_FALSE;
if (mode[0] == &c&) {
php_stream_truncate_set_size(stream, 0);
switch (Z_TYPE_P(data)) {
case IS_RESOURCE: {
if (php_stream_copy_to_stream_ex(srcstream, stream, PHP_STREAM_COPY_ALL, &len) != SUCCESS) {
numbytes = -1;
numbytes =
case IS_NULL:
case IS_LONG:
case IS_DOUBLE:
case IS_BOOL:
case IS_CONSTANT:
convert_to_string_ex(&data);
case IS_STRING:
if (Z_STRLEN_P(data)) {
numbytes = php_stream_write(stream, Z_STRVAL_P(data), Z_STRLEN_P(data));
if (numbytes != Z_STRLEN_P(data)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, &Only %d of %d bytes written, possibly out of free disk space&, numbytes, Z_STRLEN_P(data));
numbytes = -1;
case IS_ARRAY:
if (zend_hash_num_elements(Z_ARRVAL_P(data))) {
int bytes_
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(data), &pos);
while (zend_hash_get_current_data_ex(Z_ARRVAL_P(data), (void **) &tmp, &pos) == SUCCESS) {
if (Z_TYPE_PP(tmp) != IS_STRING) {
SEPARATE_ZVAL(tmp);
convert_to_string(*tmp);
if (Z_STRLEN_PP(tmp)) {
numbytes += Z_STRLEN_PP(tmp);
bytes_written = php_stream_write(stream, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));
if (bytes_written & 0 || bytes_written != Z_STRLEN_PP(tmp)) {
if (bytes_written & 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, &Failed to write %d bytes to %s&, Z_STRLEN_PP(tmp), filename);
php_error_docref(NULL TSRMLS_CC, E_WARNING, &Only %d of %d bytes written, possibly out of free disk space&, bytes_written, Z_STRLEN_PP(tmp));
numbytes = -1;
zend_hash_move_forward_ex(Z_ARRVAL_P(data), &pos);
case IS_OBJECT:
if (Z_OBJ_HT_P(data) != NULL) {
//看看对像怎么保存的:)
if (zend_std_cast_object_tostring(data, &out, IS_STRING TSRMLS_CC) == SUCCESS) {
numbytes = php_stream_write(stream, Z_STRVAL(out), Z_STRLEN(out));
if (numbytes != Z_STRLEN(out)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, &Only %d of %d bytes written, possibly out of free disk space&, numbytes, Z_STRLEN(out));
numbytes = -1;
zval_dtor(&out);
numbytes = -1;
php_stream_close(stream);
if (numbytes & 0) {
RETURN_FALSE;
RETURN_LONG(numbytes);
什么时候用fwrite,file_put_contents ?
1,函数原型已经说明了它们处理的数据类型不一样
2,简单的文件处理,追求速度用fwrite
3,书写简单用file_put_contents & (啥类型的数据都能处理,magic阿。但是要理解类型判断机制,否则保存的数据可能不是你想要的)
上一页: &&&&&下一页:相关内容& & 命令:file_put_contents();& & 命令解析:file_put_contents (PHP 5)& & file_put_contents -- 将一个字符串写入文件& & 说明:& & int file_put_contents ( string filename, string data [, int flags……
声明:该文章系网友上传分享,此内容仅代表网友个人经验或观点,不代表本网站立场和观点;若未进行原创声明,则表明该文章系转载自互联网;若该文章内容涉嫌侵权,请及时向
论文写作技巧
上一篇:下一篇:
相关经验教程Keyboard Shortcuts?
Next menu item
Previous menu item
Previous man page
Next man page
Scroll to bottom
Scroll to top
Goto homepage
Goto search(current page)
Focus search box
Change language:
Brazilian Portuguese
Chinese (Simplified)
file_put_contents
file_put_contents & Write a string to a file
Description
int file_put_contents
( string $filename
[, int $flags = 0
[, resource $context
If filename does not exist, the file is created.
Otherwise, the existing file is overwritten, unless the
FILE_APPEND flag is set.
Parameters
Path to the file where to write the data.
The data to write. Can be either a , an
or a stream resource.
If data is a stream resource, the
remaining buffer of that stream will be copied to the specified file.
This is similar with using .
You can also specify the data parameter as a single
dimension array. This is equivalent to
file_put_contents($filename, implode('', $array)).
The value of flags can be any combination of
the following flags, joined with the binary OR (|)
Available flags
Description
FILE_USE_INCLUDE_PATH
Search for filename in the include directory.
information.
FILE_APPEND
If file filename already exists, append
the data to the file instead of overwriting it.
Acquire an exclusive lock on the file while proceeding to the
writing. In other words, a
call happens
between the
call and the
call. This is not identical to an
call with mode &x&.
A valid context resource created with
Return Values
This function returns the number of bytes that were written to the file, or
FALSE on failure.
WarningThis function may
return Boolean FALSE, but may also return a non-Boolean value which
evaluates to FALSE. Please read the section on
information. Use
for testing the return value of this
Example #1 Simple usage example
&?php$file&=&'people.txt';//&Open&the&file&to&get&existing&content$current&=&file_get_contents($file);//&Append&a&new&person&to&the&file$current&.=&"John&Smith\n";//&Write&the&contents&back&to&the&filefile_put_contents($file,&$current);?&
Example #2 Using flags
&?php$file&=&'people.txt';//&The&new&person&to&add&to&the&file$person&=&"John&Smith\n";//&Write&the&contents&to&the&file,&//&using&the&FILE_APPEND&flag&to&append&the&content&to&the&end&of&the&file//&and&the&LOCK_EX&flag&to&prevent&anyone&else&writing&to&the&file&at&the&same&timefile_put_contents($file,&$person,&FILE_APPEND&|&LOCK_EX);?&
Note: This function is
binary-safe.
TipA URL can be used as a
filename with this function if the
have been enabled.
for more details on how to specify the
filename. See the
for links to information
about what abilities the various wrappers have, notes on their usage,
and information on any predefined variables they may
- Opens file or URL
- Binary-safe file write
- Reads entire file into a string
- Creates a stream context
File put contents fails if you try to put a file in a directory that doesn't exist. This creates the directory.&?php& & 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);& & & & file_put_contents("$dir/$file", $contents);& & }?&
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.437sfopen() 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.
$user = "test";
$pass = "myFTP";
$host = "";
$file = "test.txt";
$hostname = $user . ":" . $pass . "@" . $host . "/" . $file;
$content = "this is just a test.";
$options = array('ftp' =& array('overwrite' =& true));
$stream = stream_context_create($options);
file_put_contents($hostname, $content, 0, $stream);
?&
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:
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
&?php
$host = '*****';
$usr = '*****';
$pwd = '**********';& & & &&
$local_file = './orderXML/order200.xml';
$ftp_path = 'order200.xml';
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");& & &
ftp_pasv($resource, true);
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
ftp_chdir($conn_id, '/public_html/abc/');
$upload = ftp_put($conn_id, $ftp_path, $local_file, FTP_ASCII);
if($upload) { $ftpsucc=1; } else { $ftpsucc=0; }
print (!$upload) ? 'Cannot upload' : 'Upload complete';
print "\n";
ftp_close($conn_id);
?&
Calling file_put_contents within a destructor will cause the file to be written in SERVER_ROOT...
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:&?php$myfile=fopen('test.txt','rt');flock($myfile,LOCK_SH);$read=file_get_contents('test.txt');fclose($myfile);?&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.
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);
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&?phpfunction file_force_contents($filename, $data, $flags = 0){& & if(!is_dir(dirname($filename)))& & & & mkdir(dirname($filename).'/', 0777, TRUE);& & return file_put_contents($filename, $data,$flags);}file_force_contents('test1.txt','test1 content');& file_force_contents('test2/test2.txt','test2 content'); file_force_contents('~/test3/test3.txt','test3 content'); ?&
NOTE : file_put_contents doesn't add a valid BOM while creating the file
$myFile = 'test.txt';
$myContent = 'I love PHP';
file_put_contents($myFile, "\xEF\xBB\xBF".$myContent);
?&
There is a better way. www.php.net/touchSince you're not adding anything to the file,&?phpfunction updateFile($filename) {& & if (!file_exists($filename))& & touch($filename);}?&
I wrote this script implementing the file_put_contents() and file_get_contents() functions to be compatible with both php4.* and php 5.*. It is a PHP Command line interface script which searches and replaces a specific word recursively through all files in the supplied directory hierarchy.Usage from a Linux command line: ./scriptname specifieddirectory searchString replaceString#!/usr/bin/php&?php$argc = $_SERVER['argc'];$argv = $_SERVER['argv'];if($argc != 4){echo "This command replaces a search string with a replacement string\n for the contents of all files in a directory hierachy\n";echo "command usage: $argv[0]& directory searchString replaceString\n";echo "\n";}?&&?php& & & if (!function_exists('file_put_contents')) {& & function file_put_contents($filename, $data) {& & & & $f = @fopen($filename, 'w');& & & & if (!$f) {& & & & & & return false;& & & & } else {& & & & & & $bytes = fwrite($f, $data);& & & & & & fclose($f);& & & & & & return $bytes;& & & & }& & }}function get_file_contents($filename)& & & {& & & if (!function_exists('file_get_contents'))& & & {& & & $fhandle = fopen($filename, "r");& & & $fcontents = fread($fhandle, filesize($filename));& & & fclose($fhandle);& & & }& & & else& & & {& & & $fcontents = file_get_contents($filename);& & & }& & & return $fcontents;& & & }?&&?phpfunction openFileSearchAndReplace($parentDirectory, $searchFor, $replaceWith){if ($handle = opendir("$parentDirectory")) {& & while (false !== ($file = readdir($handle))) {& & & & if (($file != "." && $file != "..") && !is_dir($file)) {& & & & & chdir("$parentDirectory"); $holdcontents = file_get_contents($file);& & & && $holdcontents2 = str_replace($searchFor, $replaceWith, $holdcontents);& & & && file_put_contents($file, $holdcontents2);& & & && }& & & & if(is_dir($file) && ($file != "." && $file != ".."))& & & & {& & & & $holdpwd = getcwd();& & & & $newdir = "$holdpwd"."/$file";& & & & openFileSearchAndReplace($newdir, $searchFor, $replaceWith);& & & & }& & }& & closedir($handle); }}$parentDirectory2 = $argv[1];$searchFor2 = $argv[2];$replaceWith2 = $argv[3];echo "REPLACED\n'$searchFor2' with '$replaceWith2' recursively through directory listed below\nFor all files that current user has write permissions for\nDIRECTORY: '$parentDirectory2'\n";echo "command written by Kolapo Akande :) all rights reserved :)\n"; $holdpwd = getcwd(); chdir($parentDirectory2);openFileSearchAndReplace($parentDirectory2, $searchFor2, $replaceWith2);?&
file_put_contents() strips the last line endingIf you really want an extra line ending at the end of a file when writing with file_put_contents(), you must append an extra PHP_EOL to the end of the line as follows.&?php$a_str = array("these","are","new","lines");$contents = implode(PHP_EOL, $a_str);$contents .= PHP_EOL . PHP_EOL;file_put_contents("newfile.txt", $contents);print("|$contents|");?&You can see that when you print $contents you get two extra line endings, but if you view the file newfile.txt, you only get one.
I made a ftp_put_contents function.hope you enjoy.&?phpfunction ftp_put_contents($fpc_path_and_name, $fpc_content) {& & & & $cfg_temp_folder = str_replace("//", "/", $_SERVER['DOCUMENT_ROOT']."/_temp/");& & & & $cfg_ftp_server = "";& & & & $cfg_user = "user";& & & & $cfg_pass = "password";& & & & $cfg_document_root = "DOCUMENT ROOT OF FTP";& & & & $cfg_site_link = "Link to the website";& & & & $cotains_slash = strstr($fpc_path_and_name, "/");& & & & if ($cotains_slash) {& & & & $fpc_path_and_name_array = explode("/", $fpc_path_and_name);& & & & $fpc_file_name = end($fpc_path_and_name_array);& & }& & else {& & & & $fpc_file_name = $fpc_path_and_name;& & }& & & & if (!file_exists($cfg_temp_folder)) {& & & & if (!mkdir($cfg_temp_folder, 0777)) {& & & & & & echo "Unable to generate a temporary folder on the local server - $cfg_temp_folder.&br /&";& & & & & & die();& & & & }& & }& & & & if (!file_put_contents(str_replace("//", "/", $cfg_temp_folder.$fpc_file_name), $fpc_content)) {& & & & echo "Unable to generate the file in the temporary location - ".str_replace("//", "/", $cfg_temp_folder.$fpc_file_name).".&br /&";& & & & die();& & }& & $fpc_ftp_conn = ftp_connect("$cfg_ftp_server");& & & & if (!$fpc_ftp_conn) {& & & & echo "Could not connect to server &b&$cfg_ftp_server&/b&.&br /&";& & & & die();& & }& & else {& & & & & & & & if (!ftp_login($fpc_ftp_conn, "$cfg_user", "$cfg_pass")) {& & & & & & echo "User or password.&br /&";& & & & & & die();& & & & }& & & & else {& & & & & & & & & & & & if (!ftp_chdir($fpc_ftp_conn, $cfg_document_root)) {& & & & & & & & echo "Error to set Document Root.&br /&";& & & & & & & & die();& & & & & & }& & & & & & & & & & & & & & & & & & if ($cotains_slash) {& & & & & & & & & & & & & & & & if (count($fpc_path_and_name_array) & 1) {& & & & & & & & & & & & & & & & & & & & $fpc_remove_last_array = array_pop($fpc_path_and_name_array);& & & & & & & & & & & & & & & & & & & & if (substr($fpc_path_and_name,0,1) == "/") {& & & & & & & & & & & & $fpc_remove_first_array = array_shift($fpc_path_and_name_array);& & & & & & & & & & }& & & & & & & & & & & & & & & & & & & & foreach ($fpc_path_and_name_array as $fpc_ftp_path) {& & & & & & & & & & & & if (!@ftp_chdir($fpc_ftp_conn, $fpc_ftp_path)) {& & & & & & & & & & & & & & if (!ftp_mkdir($fpc_ftp_conn, $fpc_ftp_path)) {& & & & & & & & & & & & & & & & echo "Error creating directory $fpc_ftp_path.&br /&";& & & & & & & & & & & & & & }& & & & & & & & & & & & & & else {& & & & & & & & & & & & & & & & if (!ftp_chdir($fpc_ftp_conn, $fpc_ftp_path)) {& & & & & & & & & & & & & & & & & & echo "Error go to the directory $fpc_ftp_path.&br /&";& & & & & & & & & & & & & & & & }& & & & & & & & & & & & & & }& & & & & & & & & & & & }& & & & & & & & & & }& & & & & & & & }& & & & & & & & else {& & & & & & & & & & & & & & & & & & }& & & & & & }& & & & & & & & & & & & if (!ftp_put($fpc_ftp_conn, $fpc_file_name, str_replace("//", "/", $cfg_temp_folder.$fpc_file_name), FTP_ASCII)) {& & & & & & & & echo "File upload &b&$fpc_path_and_name&/b& failed!&br /&";& & & & & & & & die();& & & & & & }& & & & & & else {& & & & & & & & if (!unlink(str_replace("//", "/", $cfg_temp_folder.$fpc_file_name))) {& & & & & & & & & & echo "Error deleting temporary file.&br /&";& & & & & & & & & & die();& & & & & & & & }& & & & & & & & else {& & & & & & & & & & echo "File upload &a href='$cfg_site_link".str_replace("//", "/", "/$fpc_path_and_name")."'&&b&$cfg_site_link".str_replace("//", "/", "/$fpc_path_and_name")."&/a&&/b& successfully performed.&br /&";& & & & & & & & }& & & & & & }& & & & & & & & & & & & ftp_close($fpc_ftp_conn);& & & & }& & }}$content_file = "&!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"\"&&html xmlns=\"\"&&head&&meta http-equiv=\"Content-Type\" content=\"text/ charset=utf-8\" /&&title&Title&/title&&/head&&body&&p&Test&/p&&/body&&/html&";ftp_put_contents("test.php", $content_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.
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.
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:&?php $counter = file_get_contents("counter.txt"); $counter++; file_put_contents("counter.txt", $counter); echo $counter;?&Or a graphic hit counter:&?php $counter = file_get_contents("counter.txt"); $counter++; file_put_contents("counter.txt", $counter); for($i = 0; $i & strlen($counter); $i++) echo "&img src=\"counter/".substr($counter, $i, 1).".gif\" alt=\"".substr($counter, $i, 1)."\" /&";?&
I use the following code to create a rudimentary text editor. It's not fancy, but then it doesn't have to be. You could easily add a parameter to sp I have not done so to avoid the potential security headaches.There are still obvious security holes here, but for most applications it should be reasonably safe if implemented for brief periods in a counterintuitive spot. (Nobody says you have to make a PHP f you can tack it on anywhere, so long as it is at the beginning of a file.)&?php$random1 = 'randomly_generated_string';$random2 = 'another_randomly_generated_string';$target_file = 'file_to_edit.php';$this_file = 'the_current_file.php';if ($_REQUEST[$random1] === $random2) {& & if (isset($_POST['content']))& & & & file_put_contents($target_file, get_magic_quotes_qpc() ? stripslashes($_POST['content']) : $_POST['content']);& & & & die('&!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" ""&&html xmlns="" xml:lang="en" lang="en"&& & &head&& & & & &title&Editing...&/title&& & &/head&& & &body&& & & & &form method="post" action="' . $this_file . '" /&& & & & &input type="hidden" name="' . $random1 . '" value="' . $random2 . '" /&& & & & &textarea name="content" rows="50" cols="100"&' . file_get_contents($target_file) . '&/textarea&&br /&& & & & &input type="submit" value="Save Changes" /&& & & & &/form&& & &/body&&/html&');}?&Then simply browse to hxxp:///{$this_file}?{$random1}={$random2}, with the appropriate values substituted for each bracketed variable. Please note that this code assumes the target file to be world writable (-rw-rw-rw- or 666) and will fail to save properly without error if it is not.Once again, this is by no means secure or permanent, but as a quick fix for brief edits to noncritical files it should be sufficient, and its small size is a definite bonus.
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);& & }
Make sure not to corrupt anything in case of failure.&?phpfunction file_put_contents_atomically($filename, $data, $flags = 0, $context = null) {& & if (file_put_contents($filename."~", $data, $flags, $context) === strlen($contents)) {& & & & return rename($filename."~",$filename,$context);& & }& & @unlink($filename."~", $context);& & return FALSE;}?&
I suggest to expand file_force_contents() function of TrentTompkins at gmail dot com by adding verification if patch is like: "../foo/bar/file"if (strpos($dir, "../") === 0)& & $dir = str_replace("..", substr(__DIR__, 0, strrpos(__DIR__, "/")), $dir);
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);&& }
This php.net example could be confusing:&?phpfile_put_contents($file, $person, FILE_APPEND | LOCK_EX);?&You do not need LOCK_EX if you write only to a file (like log files). Multiple writing processes are already queued. Test it on your own by calling this script 4 times simultaneously:&?phpfunction string_rand($len, $split="\n") {& & return substr(chunk_split(bin2hex(openssl_random_pseudo_bytes(ceil($len / 2))), 1023, $split), 0, $len);}ini_set('memory_limit', '200M');if (!file_put_contents('../cache4/file.txt', string_rand(), FILE_APPEND)) {& & exit('file_put_contents() error!');}clearstatcache();echo 'filesize: ' . filesize('../cache4/file.txt') . PHP_EOL;$fp = fopen('../cache4/file.txt', 'r');if ($fp) {& & while (($line = fgets($fp)) !== false) {& & & & if (strlen($line) != 1024) {& & & & & & exit('Line length error!');& & & & }& & }& & fclose($fp);}?&You will not see an error, the last called script needs the longest time (as it is the last one in the queue) and the final size will be
bytes as it should be.
re: moura dot kadu at gmail dot comwhy not ? file_put_contents('',$data);
Log custom or error messages to a file.&?phpclass Logger{& & protected $file;& & & & & & protected $content;& & & & protected $writeFlag;& & & & protected $endRow;& & & & public function __construct($file,$endRow="\n",$writeFlag=FILE_APPEND) { & & & & & & & & $this-&file=$file;& & & & & & & & $this-&writeFlag=$writeFlag;& & & & & & & & $this-&endRow=$endRow;& & & & & & }& & & & & & public function AddRow($content="",$newLines=1){& & & & & & & & for ($m=0;$m&$newLines;$m++)& & & & {& & & & & & & & & & $newRow .= $this-&endRow;& & & & & & & & & & }& & & & & & & & $this-&content .= $content . $newRow;& & & & & & }& & & & & & public function Commit(){& & & & & & & & return file_put_contents($this-&file,$this-&content,$this-&writeFlag);& & & & & & }& & & & public function LogError($error,$newLines=1)& & {& & & & if ($error!=""){& & & & & & & & & & $this-&AddRow($error,$newLines);& & & & & & echo $error;& & & & & & & & & & }& & & & & & & & & & }}$logFileDirectoryAndName="/yourDirectory/yourFileName.xxx";$logger = new Logger($logFileDirectoryAndName);$logger-&AddRow("Your Log Message");$logger-&LogError(mysql_error($conn));$logger-&Commit();?&
As to the previous user note, it would be wise to include that code within a conditional statement, as to prevent re-defining file_put_contents and the FILE_APPEND constant in PHP 5:&?php&& if ( !function_exists('file_put_contents') && !defined('FILE_APPEND') ) {&& ...&& }?&Also, if the file could not be accessed for writing, the function should return boolean false, not 0. An error is different from 0 bytes written, in this case.
if path to the file not exist function file_put_contents can't create it. This simple function make it on UNIX-based and Windows servers.&?php function file_put_contents_force(){& & $args = func_get_args();& & $path = str_replace(array('/','\\'), DIRECTORY_SEPARATOR, $args[0]);& & $parts = explode(DIRECTORY_SEPARATOR, $path);& & array_pop($parts);& & $directory =& '';& & foreach($parts as $part):& & & & $check_path = $directory.$part;& & & & & & if( is_dir($check_path.DIRECTORY_SEPARATOR) === FALSE) {& & & & & & & & mkdir($check_path, 0755);& & & & & & }& & & & & & $directory = $check_path.DIRECTORY_SEPARATOR;& && && & & call_user_func_array('file_put_contents',$args);}?&
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.&?define('FILE_APPEND', 1);function file_put_contents($n, $d, $flag = false) {& & $mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';& & $f = @fopen($n, $mode);& & if ($f === false) {& & & & return 0;& & } else {& & & & if (is_array($d)) $d = implode($d);& & & & $bytes_written = fwrite($f, $d);& & & & fclose($f);& & & & return $bytes_& & }}?&
NOTE : file_put_contents create files UTF-8&?php $myFile = 'test.txt'; $myContent = 'I love PHP'; file_put_contents($myFile, utf8_encode($myContent)); ?&
Under PHP7.0, I have seen that using an empty string as $data, the function returns FALSE instead of 0 as it should:& & & & $data = ''& & & & $size = file_put_contents($filename, $data, FILE_APPEND);& & & & if ($size == FALSE)& & & & {& & & & & & && echo "error writing file"& & & & }Code will give error when $data is an empty string even using == operator.Hope it helps somebody...
This is example, how to save Error Array into simple log file&?php$error[] = 'some error';$error[] = 'some error 2';@file_put_contents('log.txt',date('c')."\n".implode("\n", $error),FILE_APPEND);?&

我要回帖

更多关于 指纹识别不灵敏了怎么办 的文章

 

随机推荐