Factor out includes to a "common.php" file, just to tidy up index.php
[htmlpurifier/darkodev.git] / maintenance / compat-function-file-put-contents.php
blobbf8effc9ac73ad0dfdb5ae23c317938b28ab85ac
1 <?php
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')) {
10 define('LOCK_EX', 2);
13 if (!defined('FILE_APPEND')) {
14 define('FILE_APPEND', 8);
18 /**
19 * Replace file_put_contents()
21 * @category PHP
22 * @package PHP_Compat
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
29 * @since PHP 5
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',
42 E_USER_WARNING);
43 return false;
46 // Get the length of data to write
47 $length = strlen($content);
49 // Check what mode we are using
50 $mode = ($flags & FILE_APPEND) ?
51 'a' :
52 'wb';
54 // Check if we're using the include path
55 $use_inc_path = ($flags & FILE_USE_INCLUDE_PATH) ?
56 true :
57 false;
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',
62 E_USER_WARNING);
63 return false;
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)) {
70 return false;
74 // Write to the file
75 $bytes = 0;
76 if (($bytes = @fwrite($fh, $content)) === false) {
77 $errormsg = sprintf('file_put_contents() Failed to write %d bytes to %s',
78 $length,
79 $filename);
80 user_error($errormsg, E_USER_WARNING);
81 return false;
84 // Close the handle
85 @fclose($fh);
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.',
90 $bytes,
91 $length);
92 user_error($errormsg, E_USER_WARNING);
93 return false;
96 // Return length
97 return $bytes;
101 // Define
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);