(PHP 5)
file_put_contents — Write a string to a file
This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
If filename does not exist, the file is created.
Otherwise, the existing file is overwritten, unless the
FILE_APPEND flag is set.
filenamePath to the file where to write the data.
dataThe data to write. Can be either a string, an array 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 stream_copy_to_stream().
You can also specify the data parameter as a single
dimension array. This is equivalent to
file_put_contents($filename, implode('', $array)).
flags
The value of flags can be any combination of
the following flags, joined with the binary OR (|)
operator.
| Flag | Description |
|---|---|
FILE_USE_INCLUDE_PATH
|
Search for filename in the include directory.
See include_path for more
information.
|
FILE_APPEND
|
If file filename already exists, append
the data to the file instead of overwriting it.
|
LOCK_EX
|
Acquire an exclusive lock on the file while proceeding to the writing. |
contextA valid context resource created with stream_context_create().
This function returns the number of bytes that were written to the file, or
FALSE on failure.
Questa funzione può
restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato
come FALSE. Fare riferimento alla sezione Booleans per maggiori
informazioni. Usare l'operatore ===
per controllare il valore restituito da questa
funzione.
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 file
file_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 time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>
| Versione | Descrizione |
|---|---|
| 5.1.0 |
Added support for LOCK_EX and the ability to pass
a stream resource to the data parameter
|
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Vedere fopen() per maggiori informazioni su come specificare i nomi di file. Vedere Supported Protocols and Wrappers per i link verso le informazioni sulle capacità dei vari wrapper, note sul loro uso, informazioni sulle variabili predefinite che forniscono.