2 // $Id: file_put_contents.php,v 1.27 2007/04/17 10:09:56 arpad Exp $
5 if (!defined('FILE_USE_INCLUDE_PATH')) {
6 define('FILE_USE_INCLUDE_PATH', 1);
9 if (!defined('LOCK_EX')) {
13 if (!defined('FILE_APPEND')) {
14 define('FILE_APPEND', 8);
19 * Replace file_put_contents()
23 * @license LGPL - http://www.gnu.org/licenses/lgpl.html
24 * @copyright 2004-2007 Aidan Lister <aidan@php.net>, Arpad Ray <arpad@php.net>
25 * @link http://php.net/function.file_put_contents
26 * @author Aidan Lister <aidan@php.net>
27 * @version $Revision: 1.27 $
28 * @internal resource_context is not supported
30 * @require PHP 4.0.0 (user_error)
32 function php_compat_file_put_contents($filename, $content, $flags = null, $resource_context = null)
34 // If $content is an array, convert it to a string
35 if (is_array($content)) {
36 $content = implode('', $content);
39 // If we don't have a string, throw an error
40 if (!is_scalar($content)) {
41 user_error('file_put_contents() The 2nd parameter should be either a string or an array',
46 // Get the length of data to write
47 $length = strlen($content);
49 // Check what mode we are using
50 $mode = ($flags & FILE_APPEND
) ?
54 // Check if we're using the include path
55 $use_inc_path = ($flags & FILE_USE_INCLUDE_PATH
) ?
59 // Open the file for writing
60 if (($fh = @fopen
($filename, $mode, $use_inc_path)) === false) {
61 user_error('file_put_contents() failed to open stream: Permission denied',
66 // Attempt to get an exclusive lock
67 $use_lock = ($flags & LOCK_EX
) ?
true : false ;
68 if ($use_lock === true) {
69 if (!flock($fh, LOCK_EX
)) {
76 if (($bytes = @fwrite
($fh, $content)) === false) {
77 $errormsg = sprintf('file_put_contents() Failed to write %d bytes to %s',
80 user_error($errormsg, E_USER_WARNING
);
87 // Check all the data was written
88 if ($bytes != $length) {
89 $errormsg = sprintf('file_put_contents() Only %d of %d bytes written, possibly out of free disk space.',
92 user_error($errormsg, E_USER_WARNING
);
102 if (!function_exists('file_put_contents')) {
103 function file_put_contents($filename, $content, $flags = null, $resource_context = null)
105 return php_compat_file_put_contents($filename, $content, $flags, $resource_context);