PHP.mk документација

file_put_contents

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.file-put-contents.php PHP.net прокси Преводот е вчитан
Оригинал на PHP.net
Патека function.file-put-contents.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + преведен приказ Кодовите, табелите и белешките остануваат читливи во истиот тек.
file_put_contents

Референца за `function.file-put-contents.php` со подобрена типографија и навигација.

function.file-put-contents.php

file_put_contents

класата mysqli_driver

file_put_contentsЗапиши податоци во датотека

= NULL

file_put_contents(
         string $filename,
         mixed $data,
         int $flags = 0,
         ?resource $context = null
): int|false

Оваа функција е идентична со повикување fopen(), fwrite() and fclose() последователно за запишување податоци во датотека.

Враќа filename не постои, датотеката се создава. Инаку, постоечката датотека се презапишува, освен ако FILE_APPEND знамето е поставено.

Параметри

filename

Патека до датотеката каде што ќе се запишуваат податоците.

data

Податоците за запишување. Може да биде или string, еден array или stream resource.

Враќа data е stream ресурс, преостанатиот бафер од тој поток ќе биде копиран во наведената датотека. Ова е слично со користење stream_copy_to_stream().

Можете исто така да го специфицирате data параметарот како еднодимензионален низ. Ова е еквивалентно со file_put_contents($filename, implode('', $array)).

flags

Вредноста на flags може да биде која било комбинација од следниве знамиња, споени со бинарниот ИЛИ (|) оператор.

Достапни знамиња
Знаменце = NULL
FILE_USE_INCLUDE_PATH Пребарај за filename во директориумот за вклучување. Види include_path Користење на PHP од командната линија
FILE_APPEND Ако датотеката filename веќе постои, додај ги податоците на крајот од датотеката наместо да ја презапишеш.
LOCK_EX Обезбеди ексклузивно заклучување на датотеката додека се продолжува со запишувањето. Со други зборови, а flock() повикот се случува помеѓу fopen() повик и fwrite() повик. Ова не е идентично со fopen() повик со режим "x".
context

Валиден ресурс за контекст креиран со stream_context_create().

Вратени вредности

Оваа функција враќа број на бајти што беа запишани во датотеката, или false при неуспех.

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Функцијата враќа прочитани податоци или falseОваа функција може да врати Буловска вредност false, но исто така може да врати и вредност што не е Буловска, а која се проценува како Булови . Ве молиме прочитајте го делот за за повеќе информации. Користете го операторот ===

Примери

Пример #1 Пример за едноставна употреба

<?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 file
file_put_contents($file, $current);
?>

Пример #2 Користење знаменца

<?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 time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>

Белешки

Забелешка: Пример #4 Користење на контексти на потоци

Совети

URL може да се користи како име на датотека со оваа функција ако fopen обвивки се овозможени. Погледнете fopen() за повеќе детали за тоа како да го специфицирате името на датотеката. Погледнете го Поддржани протоколи и обвивки за линкови до информации за тоа какви способности имаат разните обвивки, белешки за нивната употреба и информации за сите предодредени променливи што може да ги обезбедат.

Види Исто така

Белешки од корисници 18 белешки

TrentTompkins на gmail точка com
пред 17 години
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);
    }
?>
justin dot carlson на gmail точка com
пред 14 години
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
maksam07 на gmail точка com
пред 7 години
A slightly simplified version of the method: http://php.net/manual/ru/function.file-put-contents.php#84180

<?php 
function file_force_contents( $fullPath, $contents, $flags = 0 ){
    $parts = explode( '/', $fullPath );
    array_pop( $parts );
    $dir = implode( '/', $parts );
    
    if( !is_dir( $dir ) )
        mkdir( $dir, 0777, true );
    
    file_put_contents( $fullPath, $contents, $flags );
}

file_force_contents( ROOT.'/newpath/file.txt', 'message', LOCK_EX );
?>
крис @ ocportal . ком
12 години пред
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.
deqode на felosity точка nl
пред 16 години
Please note that when saving using an FTP host, an additional stream context must be passed through telling PHP to overwrite the file.

<?php
 /* set the FTP hostname */
 $user = "test";
 $pass = "myFTP";
 $host = "example.com";
 $file = "test.txt";
 $hostname = $user . ":" . $pass . "@" . $host . "/" . $file;

 /* the file content */
 $content = "this is just a test.";
 
 /* create a stream context telling PHP to overwrite the file */
 $options = array('ftp' => array('overwrite' => true));
 $stream = stream_context_create($options);
 
 /* and finally, put the contents */
 file_put_contents($hostname, $content, 0, $stream);
?>
egingell на sisna точка com
19 години пред
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_written;
    }
}

?>
aidan на php точка net
21 години пред
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
vaneatona на gmail точка com
пред 9 години
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);
    }
Анонимен
пред 9 години
Make sure not to corrupt anything in case of failure.

<?php

function 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;
}

?>
ravianshmsr08 на gmail точка com
пред 15 години
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");
// perform file upload
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; }
// check upload status:
print (!$upload) ? 'Cannot upload' : 'Upload complete';
print "\n";
// close the FTP stream
ftp_close($conn_id);
?>
Брендон Локаби
пред 14 години
Calling file_put_contents within a destructor will cause the file to be written in SERVER_ROOT...
Анонимен
3 години пред
A more simplified version of the method that creates subdirectories:

function path_put_contents($filePath, $contents, $flags = 0) {

    if (! is_dir($dir = implode('/', explode('/', $filePath, -1))))
        mkdir($dir, 0777, true);
    file_put_contents($filePath, $contents, $flags);
}
error на example точка com
пред 15 години
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.
Џон Галт
пред 16 години
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)."\" />";
?>
gurjindersingh на SPAM точка hotmail точка com
пред 11 години
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
<?php
/**
 * @param string $filename <p>file name including folder. 
 * example :: /path/to/file/filename.ext or filename.ext</p>
 * @param string $data <p> The data to write.
 * </p>
 * @param int $flags same flags used for file_put_contents.
 * more info: http://php.net/manual/en/function.file-put-contents.php
 * @return bool <b>TRUE</b> file created succesfully <br> <b>FALSE</b> failed to create file.
 */
function file_force_contents($filename, $data, $flags = 0){
    if(!is_dir(dirname($filename)))
        mkdir(dirname($filename).'/', 0777, TRUE);
    return file_put_contents($filename, $data,$flags);
}
// usage

file_force_contents('test1.txt','test1 content');  // test1.txt created

file_force_contents('test2/test2.txt','test2 content'); 
// test2/test2.txt created "test2" folder.  

file_force_contents('~/test3/test3.txt','test3 content'); 
// /path/to/user/directory/test3/test3.txt created "test3" folder in user directory (check on linux "ll ~/ | grep test3").  
?>
aabaev @ gmail точка com
пред 9 години
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);
wjsams на gmail точка com
пред 16 години
file_put_contents() strips the last line ending

If 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.
curda222 на gmail точка com
пред 2 години
An improved and enraptured code from TrentTompkins at gmail dot com  

Note: Added error response 
Note: Added directory detection
Note: Added root detection
Note: Added permissions when creating folder

function file_force_contents($dir, $contents, $flags = 0){
    if (strpos($dir, "../") === 0){
        $dir = str_replace("..", substr(__DIR__, 0, strrpos(__DIR__, "/")), $dir);
    }
    $parts = explode('/', $dir);
    if(is_array($parts)){
        $file = array_pop($parts);
        $dir = '';
        foreach($parts as $part)
            if(!is_dir($dir .= "/$part")){
                mkdir($dir, 0777, true);
            }
            if(file_put_contents("$dir/$file", $contents, $flags) === false ){
            return false;
        }
    }else{
        if(file_put_contents("$dir", $contents, $flags) === false ){
            return false;
        } 
    }
}

-Oliver Leuyim Angel
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.