downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

file> <file_get_contents
Last updated: Fri, 20 May 2011

view this page in

file_put_contents

(PHP 5)

file_put_contentsEscribe una cadena a un archivo

Descripción

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

Esta función es idéntica que llamar a fopen(), fwrite() y fclose() sucesivamente para escribir información en un archivo.

Si filename no existe, se crea el archivo. De otro modo, el archivo existente se sobrescribe, a menos que la bandera FILE_APPEND esté establecida.

Parámetros

filename

Ruta del archivo donde se escribe la información

data

La información a escribir. Puede ser tanto un recurso string, como array o stream.

Si data es un recurso stream, el buffer restante de ese flujo será copiado al archivo especificado. Esto es similar a usar stream_copy_to_stream().

También se puede especificar el parámetro data como un array de una sóla dimensión. Esto es equivalente a file_put_contents($nombre_archivo, implode('', $array)).

flags

El valor de flags puede ser cualquier combinación de las siguientes banderas, unidas con el operador binario OR (|).

Banderas disponibles
Bandera Descripción
FILE_USE_INCLUDE_PATH Busca filename en el directorio incluido. Véase include_path para más información.
FILE_APPEND Si el archivo filename ya existe, añade la información al archivo en vez de sobrescribirlo.
LOCK_EX Adquiere un bloqueo exclusivo del archivo mientras se está ejecutando la escritura.

context

Un recurso de contexto válido creado con stream_context_create().

Valores devueltos

Esta función devuelve el número de bytes que fueron escritos en el archivo, o FALSE en caso de error.

Warning

Esta función quizá devuelve Boolean FALSE, pero quizá también devuelve un valor non-Boolean que se evaluará como FALSE, como 0 o "". Por favor lea la sección en Booleans para más información. Use el operador === para testear el valor devuelto por esta función.

Ejemplos

Example #1 Ejemplo sencillo de uso

<?php
$archivo 
'gente.txt';
// Abre el archivo para obtener el contenido existente
$actual file_get_contents($archivo);
// Añade una nueva persona al archivo
$actual .= "John Smith\n";
// Escribe el contenido al archivo
file_put_contents($archivo$actual);
?>

Example #2 Usar banderas

<?php
$archivo 
'gente.txt';
// La nueva persona a añdir al archivo
$persona "John Smith\n";
// Escribir los contenidos en el archivo,
// usando la bandera FILE_APPEND para añadir el contenido al final del archivo
// y la bandera LOCK_EX para evitar que cualquiera escriba en el archivo al mismo tiempo
file_put_contents($archivo$personaFILE_APPEND LOCK_EX);
?>

Historial de cambios

Versión Descripción
5.0.0 Añadido el soporte de contexto
5.1.0 Añadido el soporte para LOCK_EX y la capacidad de pasar un recurso tipo stream al parámetro data

Notas

Note: Esta función es segura binariamente.

Tip

Se puede usar una dirección URL como nombre de archivo con esta función si los fopen wrappers han sido activados. Consulte fopen() para más información de como especificar el nombre de fichero. Consulte Protocolos y Envolturas soportados para ver enlaces con información sobre las diferentes habilidades que los wrappers tienen, notas de uso e información de cualquier variables predefinidas que pueden usarse.

Ver también



file> <file_get_contents
Last updated: Fri, 20 May 2011
 
add a note add a note User Contributed Notes file_put_contents
ravianshmsr08 at gmail dot com 15-Dec-2010 09:39
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);
?>
error at example dot com 11-Dec-2010 08:47
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.
hilton at allcor dot com dot br 04-Nov-2010 12:20
NOTE : file_put_contents create files UTF-8

<?php
$myFile
= 'test.txt';
$myContent = 'I love PHP';

file_put_contents($myFile, utf8_encode($myContent));
?>
clement dot delmas at gmail dot com 17-Sep-2010 01:22
NOTE : file_put_contents doesn't add a valid BOM while creating the file

<?php
$myFile
= 'test.txt';
$myContent = 'I love PHP';

file_put_contents($myFile, "\xEF\xBB\xBF".$myContent);
?>
deqode at felosity dot nl 15-Feb-2010 08:14
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);
?>
John Galt 29-Jul-2009 07:14
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)."\" />";
?>
wjsams at gmail dot com 25-Jun-2009 03:57
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.
kola_lola at hotmail dot com 06-Nov-2008 11:31
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";
exit;
}
?><?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)

     
/* Returns the contents of file name passed

      */
     
{
      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;
      }
?><?php

function openFileSearchAndReplace($parentDirectory, $searchFor, $replaceWith)
{
//echo "debug here- line 1a\n";
//echo "$parentDirectory\n";
//echo "$searchFor\n";
//echo "$replaceWith\n";

if ($handle = opendir("$parentDirectory")) {
    while (
false !== ($file = readdir($handle))) {
        if ((
$file != "." && $file != "..") && !is_dir($file)) {
         
chdir("$parentDirectory"); //to make sure you are always in right directory
         // echo "$file\n";
        
$holdcontents = file_get_contents($file);
        
$holdcontents2 = str_replace($searchFor, $replaceWith, $holdcontents);
        
file_put_contents($file, $holdcontents2);
        
// echo "debug here- line 1\n";
         // echo "$file\n";

       
}
        if(
is_dir($file) && ($file != "." && $file != ".."))
        {
       
$holdpwd = getcwd();
       
//echo "holdpwd = $holdpwd \n";
       
$newdir = "$holdpwd"."/$file";
       
//echo "newdir = $newdir \n";  //for recursive call
       
openFileSearchAndReplace($newdir, $searchFor, $replaceWith);
       
//echo "debug here- line 2\n";
        //echo "$file\n";
       
}
    }
   
closedir($handle);
 }
}

$parentDirectory2 = $argv[1];
$searchFor2 = $argv[2];
$replaceWith2 = $argv[3];

//Please do not edit below to keep the rights to this script
//Free license, if contents below this line is not edited
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();
 
//echo "$holdpwd\n";
chdir($parentDirectory2);
openFileSearchAndReplace($parentDirectory2, $searchFor2, $replaceWith2);
exit;
?>
admin at nabito dot net 04-Aug-2008 08:11
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);

?>
TrentTompkins at gmail dot com 02-Jul-2008 12:25
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);
    }
?>
Anonymous 02-May-2008 06:06
file_put_contents() will cause concurrency problems - that is, it doesn't write files atomically (in a single operation), which sometimes means that one php script will be able to, for example, read a file before another script is done writing that file completely.

The following function was derived from a function in Smarty (http://smarty.php.net) which uses rename() to replace the file - rename() is atomic on Linux.

On Windows, rename() is not currently atomic, but should be in the next release. Until then, this function, if used on Windows, will fall back on unlink() and rename(), which is still not atomic...

<?php

define
("FILE_PUT_CONTENTS_ATOMIC_TEMP", dirname(__FILE__)."/cache");
define("FILE_PUT_CONTENTS_ATOMIC_MODE", 0777);

function
file_put_contents_atomic($filename, $content) {
  
   
$temp = tempnam(FILE_PUT_CONTENTS_ATOMIC_TEMP, 'temp');
    if (!(
$f = @fopen($temp, 'wb'))) {
       
$temp = FILE_PUT_CONTENTS_ATOMIC_TEMP . DIRECTORY_SEPARATOR . uniqid('temp');
        if (!(
$f = @fopen($temp, 'wb'))) {
           
trigger_error("file_put_contents_atomic() : error writing temporary file '$temp'", E_USER_WARNING);
            return
false;
        }
    }
  
   
fwrite($f, $content);
   
fclose($f);
  
    if (!@
rename($temp, $filename)) {
        @
unlink($filename);
        @
rename($temp, $filename);
    }
  
    @
chmod($filename, FILE_PUT_CONTENTS_ATOMIC_MODE);
  
    return
true;
  
}

?>
the geek man at hot mail point com 03-Jan-2008 11:23
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 specify a file to edit; 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 file for that purpose; 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" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" 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://www.example.com/{$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.
egingell at sisna dot com 21-Dec-2007 03:15
There is a better way. www.php.net/touch

Since you're not adding anything to the file,

<?php
function updateFile($filename) {
    if (!
file_exists($filename)) return;
   
touch($filename);
}
?>
me at briandichiara dot com 04-Oct-2007 07:20
I was in need of a function that updated the last modified date in a php file. There may be a better way, but this is how I did it:

<?php
function updateFile($modFile){
    if(!empty(
$modFile)){
        if(
$fo = fopen($modFile, 'r')){
           
$source = '';
            while (!
feof($fo)) {
              
$source .= fgets($fo);
            }
           
file_put_contents($modFile,$source);
           
fclose($fo);
        }
    }
}
?>
Curtis 21-Dec-2006 11:20
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.
egingell at sisna dot com 23-Jul-2006 11:11
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;
    }
}

?>
sendoshin at awswan dot com 06-Mar-2006 07:01
To clear up what was said by pvenegas+php at gmail dot com on 11-Oct-2005 08:13, file_put_contents() will replace the file by default.  Here's the complete set of rules this function follows when accessing a file:

1.  Was FILE_USE_INCUDE_PATH passed in the call?  If so, check the include path for an existing copy of *filename*.

2.  Does the file already exist?  If not, first create it in the current working directory.  Either way, open the file.

3.  Was LOCK_EX passed in the call?  If so, lock the file.

4.  Was the function called with FILE_APPEND?  If not, clear the file's contents.  Otherwise, move to the end of the file.

5.  Write *data* into the file.

6.  Close the file and release any locks.

If you don't want to completely replace the contents of the file you're writing to, be sure to use FILE_APPEND (same as fopen() with 'a') in the *flags*.  If you don't, whatever used to be there will be gone (fopen() with 'w').

Hope that helps someone (and that it makes sense ^^)!

- Sendoshin
aidan at php dot net 21-May-2004 02:11
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

 
show source | credits | stats | sitemap | contact | advertising | mirror sites