Ошибка file put contents

I am using this line to obtain and save an image from a URL.

file_put_contents("./images/".$pk.".jpg", file_get_contents($PIC_URL))

I am unsure what the best way to deal with an error is. At the moment it is failing because there is no permission, which will be remedied shortly, but I would like it to be able to deal with situations where PIC_URL is empty or not an image. Should I dead with the error at this level(probably it is better for permission related things) or should I check higher up if PIC_URL is empty, or both?

Which is the best approach?

asked Feb 6, 2009 at 11:26

Joshxtothe4's user avatar

Joshxtothe4Joshxtothe4

4,06110 gold badges53 silver badges83 bronze badges

2

I’m not talented enough to claim this is the best method, but I would just test along the way:

$imageDir = "/path/to/images/dir/";
$imagePath = "$imageDir$pk.jpg";
if (!is_dir($imageDir) or !is_writable($imageDir)) {
    // Error if directory doesn't exist or isn't writable.
} elseif (is_file($imagePath) and !is_writable($imagePath)) {
    // Error if the file exists and isn't writable.
}

$image = file_get_contents(urlencode($PIC_URL));
if (empty($image)) {
    // Error if the image is empty/not accessible.
    exit;
}

file_put_contents($imagePath, $image);

answered Feb 6, 2009 at 11:37

chuckg's user avatar

3

try making a function for this.

<?php
define('OK', 0);
deinfe('URL_EMPTY', 1);
define('WRITING_PROBLEMS',2);
define('OTHER_PROBLEM', 3);


function save_pic($pic_url) {

  $imageDir = '/path/to/images/dir/';

  if (!strlen($pic_url))
    return URL_EMPTY;

  if (!is_dir($imageDir) || !is_writable($imageDir)) {
    return WRITING_PROBLEMS; 
  }

  $image = file_get_contents(urlencode($pic_url));

  $pk = time(); // or whatever you want as key


  $r = file_put_contents($imagePath.$pk.".jpg", $pic_url);

  if ($r)
    return OK;
  else
    return OTHER_PROBLEM;

}
?>

answered Feb 6, 2009 at 11:44

Gabriel Sosa's user avatar

Gabriel SosaGabriel Sosa

7,8974 gold badges38 silver badges48 bronze badges

Both, as far as I am concern. Especially with those dangerous file handling functions, double-checking doesn’t hurt. (Where does $pk come from?)

Generally, check higher up for nicer feedback to the user and check right before you execute for security. Its hard to give decent feedback to the user when only checking at a low level. On the other hand, it is hard to check for all possible errors (like those file system permissions) on a high and generic level.

answered Feb 6, 2009 at 11:43

cg.'s user avatar

cg.cg.

3,6482 gold badges26 silver badges30 bronze badges

Hmm couldn’t you also just do

file_put_contents($file, $str) or die("Unable to write file!");

answered May 13, 2016 at 4:37

Jeff Alan Midler's user avatar

1

MrTweak

php

  • PHP

Всем привет! Я новичок и только изучаю php. e9520f0fe061418298aa227a3f6969c8.PNG Brackets не подсвечивает код, а xampp естественно не обрабатывает. Я и уже копировал из интернета, ничего не получилось)) Подскажите пожалуйста


  • Вопрос задан

  • 537 просмотров


Комментировать


Решения вопроса 1

Pshkll

  • MrTweak

    я переписываю код с интернет уроков, всё точно так же. у блогера работало, у меня нет

  • MrTweak

    я скопировал код с php.net и он тоже не работает

  • Pshkll

    А путь к файлу верный? Пробовали его открывать и считывать данные?

  • MrTweak

    Pshkll: Если filename не существует, файл будет создан. Он не создает, выдает ошибку syntax error, unexpected ‘file_put_contents’ (T_STRING), expecting ‘,’ or ‘;’

  • MrTweak

    Pshkll: кроме этого, мне brackets не подсвечивает эту функцию, хотя с остальными всё нормально. я даже не знаю в чем проблема

  • Pshkll

  • MrTweak

    Pshkll: удивительно, но первый раз перепечатал, потом попробовал с 3 сайтов перекопировал)) пойду sublime ставить))))

  • Pshkll

  • Pshkll

    Neoline: это правила красивого и читабельного кода. Но на вкус и цвет…

  • MrTweak

    Pshkll: Neoline: боже мой)) такая глупая ошибка, я не поставил точку с запятой на предыдущей строке. это всё моя невнимательность. спасибо вам большое, за попытки решить проблему))) и да, brackets так и не подсвечивает код))

  • MrTweak

    Neoline: sublime мне не понравился. у меня есть еще один вопрос, нет желания создавать новый вопрос, я могу написать вам вк?

Пригласить эксперта


Похожие вопросы


  • Показать ещё
    Загружается…

22 сент. 2023, в 14:16

500 руб./за проект

22 сент. 2023, в 13:48

300000 руб./за проект

22 сент. 2023, в 13:33

60000 руб./за проект

Минуточку внимания

When I am trying to do this:

$txt = file_get_contents('http://stats.pingdom.com/file'); 
file_put_contents('/stats/file.html',$txt);

I am getting following error:

Warning: file_put_contents(stats/stats.html) [function.file-put-contents]: failed to open stream: Permission denied in /home/jtf/public_html/index.php on line 2

the folder stats is 777

what am I doing wrong?

thanks

J.K.A.'s user avatar

J.K.A.

7,28225 gold badges94 silver badges163 bronze badges

asked Mar 17, 2012 at 20:01

Chriswede's user avatar

/stats and stats (or the equivalent, ./stats) are not necessarily the same directory (in fact they might refer to the same directory only in theory). Most likely you are currently trying to write to a directory that does not even exist.

So this should work:

file_put_contents('stats/file.html',$txt); // removed "/" prefix

answered Mar 17, 2012 at 20:04

Jon's user avatar

JonJon

429k81 gold badges738 silver badges806 bronze badges

1

Try this:

$txt = file_get_contents('http://stats.pingdom.com/file');
file_put_contents(dirname(__FILE__) . '/stats/file.html', $txt);

answered Mar 17, 2012 at 20:04

Rick Kuipers's user avatar

Rick KuipersRick Kuipers

6,6162 gold badges17 silver badges37 bronze badges

There is no /stats/ folder in the root directory on your server, I believe.

Note the /home/jtf/public_html/ path. You have to use this one to address files in the document root of your web-server.

answered Mar 17, 2012 at 20:05

Your Common Sense's user avatar

Your Common SenseYour Common Sense

157k40 gold badges215 silver badges345 bronze badges

Your path points to / instead to /home/jtf/public_html/
Just use ../

answered Mar 17, 2012 at 20:05

Remc4's user avatar

Remc4Remc4

1,0442 gold badges12 silver badges24 bronze badges

(PHP 5, PHP 7, PHP 8)

file_put_contentsПишет данные в файл

Описание

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

Если filename не существует, файл будет
создан. Иначе, существующий файл будет перезаписан, за исключением
случая, если указан флаг FILE_APPEND.

Список параметров

filename

Путь к записываемому файлу.

data

Записываемые данные. Может быть типа string,
array или ресурсом потока.

Если data является потоковым ресурсом
(stream), оставшийся буфер этого потока будет скопирован
в указанный файл. Это похоже на использование функции stream_copy_to_stream().

Также вы можете передать одномерный массив в качестве параметра
data. Это будет эквивалентно вызову
file_put_contents($filename, implode('', $array)).

flags

Значением параметра flags может быть
любая комбинация следующих флагов, соединённых бинарным
оператором ИЛИ (|).

Доступные флаги

Флаг Описание
FILE_USE_INCLUDE_PATH Ищет filename в подключаемых директориях.
Подробнее смотрите директиву include_path.
FILE_APPEND Если файл filename уже существует, данные
будут дописаны в конец файла вместо того, чтобы его перезаписать.
LOCK_EX Получить эксклюзивную блокировку на файл на время записи. Другими словами,
между вызовами fopen() и fwrite() произойдёт
вызов функции flock(). Это не одно и то же, что вызов
fopen() с флагом «x».
context

Корректный ресурс контекста, созданный с помощью функции
stream_context_create().

Возвращаемые значения

Функция возвращает количество записанных байт в файл, или
false в случае возникновения ошибки.

Внимание

Эта функция может возвращать как логическое значение false, так и значение не типа boolean, которое приводится к false. За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Примеры

Пример #1 Пример простого использования

<?php
$file
= 'people.txt';
// Открываем файл для получения существующего содержимого
$current = file_get_contents($file);
// Добавляем нового человека в файл
$current .= "John Smith\n";
// Пишем содержимое обратно в файл
file_put_contents($file, $current);
?>

Пример #2 Использование флагов

<?php
$file
= 'people.txt';
// Новый человек, которого нужно добавить в файл
$person = "John Smith\n";
// Пишем содержимое в файл,
// используя флаг FILE_APPEND для дописывания содержимого в конец файла
// и флаг LOCK_EX для предотвращения записи данного файла кем-нибудь другим в данное время
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Подсказка

Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen(). Смотрите также список поддерживаемых обёрток URL, их возможности, замечания по использованию и список предопределённых констант в разделе Поддерживаемые протоколы и обёртки.

Смотрите также

  • fopen() — Открывает файл или URL
  • fwrite() — Бинарно-безопасная запись в файл
  • file_get_contents() — Читает содержимое файла в строку
  • stream_context_create() — Создаёт контекст потока

TrentTompkins at gmail dot com

15 years ago

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

1 year ago

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

justin dot carlson at gmail dot com

12 years ago

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 at gmail dot com

4 years ago

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 );
?>

deqode at felosity dot nl

13 years ago

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);

?>

chris at ocportal dot com

10 years ago

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.

Anonymous

6 years ago

Make sure not to corrupt anything in case of failure.

<?phpfunction 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;
}
?>

egingell at sisna dot com

17 years ago

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

?>

aabaev arroba gmail coma com

7 years ago

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);

aidan at php dot net

19 years ago

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

ravianshmsr08 at gmail dot com

12 years ago

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);

?>

vaneatona at gmail dot com

6 years ago

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

gurjindersingh at SPAM dot hotmail dot com

8 years ago

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);
}
// usagefile_force_contents('test1.txt','test1 content'); // test1.txt createdfile_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").
?>

vahkos at mail dot ru

11 years ago

file_put_contents does not issue an error message if file name is incorrect(for example has improper symbols on the end of it /n,/t)

that is why use trim() for file name.

$name=trim($name);

file_put_contents($name,$content);

error at example dot com

12 years ago

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.

wjsams at gmail dot com

14 years ago

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.

Brandon Lockaby

12 years ago

Calling file_put_contents within a destructor will cause the file to be written in SERVER_ROOT...

John Galt

14 years ago

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)."\" />";
?>

caiofior at gmail dot com

11 years ago

I had some troubles using file_put_contents with an absolute but no canonicalized path (eg. w:/htdocs/pri/../test/log.txt): on windows environment php was unable to create the file also using the realpath function .
I had to use fopen and frwite functions to write the data.

Curtis

16 years ago

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.

daniel at garcianoriega dot com

4 years ago

I faced the problem of converting a downloaded csv file that had Windows-1252 encoding, so to convert it to UTF-8 this worked for me:

$from = 'Windows-1252';
$to = 'UTF-8';

$content = file_get_contents($this->path());

file_put_contents($this->path(), mb_convert_encoding($content, $to, $from));

where "$this->path()" has the path of the file... Using this the file is converted from Windows-1252 to UTF-8.

With this you can import it with mysqlimport with no problems.

briethings at gmail dot com

5 years ago

Here is a stupid pitfall I just fell into.
I think it may happen rather frequently, so I report it.

A common situation is that the $filename argument is built from two variables:
file_put_contents($path . $file, $content);

Say that $path = 'path/to' and $file = 'file.txt': you see that $path lacks its ending "/", so the resulting full path is 'path/tofile.txt'.

Then you look at 'path/to' and don't see any 'file.txt', although no warning or notice was thrown!
And may be (like for me :D) it'll take time before you realize that a bad 'tofile.txt' was created in the *parent* directory of the one where you were looking for your file.

kola_lola at hotmail dot com

14 years ago

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;
}
?><?phpif (!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;
}
?><?phpfunction 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;
?>

moura dot kadu at gmail dot com

11 years ago

I made ​​a ftp_put_contents function.

hope you enjoy.

<?phpfunction ftp_put_contents($fpc_path_and_name, $fpc_content) {//Temporary folder in the server
$cfg_temp_folder = str_replace("//", "/", $_SERVER['DOCUMENT_ROOT']."/_temp/");//Link to FTP
$cfg_ftp_server = "ftp://ftp.com";//FTP username
$cfg_user = "user";//FTP password
$cfg_pass = "password";//Document Root of FTP
$cfg_document_root = "DOCUMENT ROOT OF FTP";//Link to the website
$cfg_site_link = "Link to the website";//Check if conteins slash on the path of the file
$cotains_slash = strstr($fpc_path_and_name, "/");//Get filename and paths
if ($cotains_slash) {
$fpc_path_and_name_array = explode("/", $fpc_path_and_name);
$fpc_file_name = end($fpc_path_and_name_array);
}
else {
$fpc_file_name = $fpc_path_and_name;
}
//Create local temp dir
if (!file_exists($cfg_temp_folder)) {
if (!
mkdir($cfg_temp_folder, 0777)) {
echo
"Unable to generate a temporary folder on the local server - $cfg_temp_folder.<br />";
die();
}
}
//Create local file in temp dir
if (!file_put_contents(str_replace("//", "/", $cfg_temp_folder.$fpc_file_name), $fpc_content)) {
echo
"Unable to generate the file in the temporary location - ".str_replace("//", "/", $cfg_temp_folder.$fpc_file_name).".<br />";
die();
}
//Connection to the FTP Server
$fpc_ftp_conn = ftp_connect("$cfg_ftp_server");//Check connection
if (!$fpc_ftp_conn) {
echo
"Could not connect to server <b>$cfg_ftp_server</b>.<br />";
die();
}
else {
// login
// check username and password
if (!ftp_login($fpc_ftp_conn, "$cfg_user", "$cfg_pass")) {
echo
"User or password.<br />";
die();
}
else {
//Document Root
if (!ftp_chdir($fpc_ftp_conn, $cfg_document_root)) {
echo
"Error to set Document Root.<br />";
die();
}
//Check if there are folders to create
if ($cotains_slash) {//Check if have folders and is not just the file name
if (count($fpc_path_and_name_array) > 1) {//Remove last array
$fpc_remove_last_array = array_pop($fpc_path_and_name_array);//Checks if there slashs on the path
if (substr($fpc_path_and_name,0,1) == "/") {
$fpc_remove_first_array = array_shift($fpc_path_and_name_array);
}
//Create each folder on ftp
foreach ($fpc_path_and_name_array as $fpc_ftp_path) {
if (!@
ftp_chdir($fpc_ftp_conn, $fpc_ftp_path)) {
if (!
ftp_mkdir($fpc_ftp_conn, $fpc_ftp_path)) {
echo
"Error creating directory $fpc_ftp_path.<br />";
}
else {
if (!
ftp_chdir($fpc_ftp_conn, $fpc_ftp_path)) {
echo
"Error go to the directory $fpc_ftp_path.<br />";
}
}
}
}
}
else {

}
}

//Check upload file
if (!ftp_put($fpc_ftp_conn, $fpc_file_name, str_replace("//", "/", $cfg_temp_folder.$fpc_file_name), FTP_ASCII)) {
echo
"File upload <b>$fpc_path_and_name</b> failed!<br />";
die();
}
else {
if (!
unlink(str_replace("//", "/", $cfg_temp_folder.$fpc_file_name))) {
echo
"Error deleting temporary file.<br />";
die();
}
else {
echo
"File upload <a href='$cfg_site_link".str_replace("//", "/", "/$fpc_path_and_name")."'><b>$cfg_site_link".str_replace("//", "/", "/$fpc_path_and_name")."</a></b> successfully performed.<br />";
}
}
//Close connection to FTP server
ftp_close($fpc_ftp_conn);
}
}
}
#Sample$content_file = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\">
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<title>Title</title>
</head>
<body>
<p>Test</p>
</body>
</html>"
;ftp_put_contents("test.php", $content_file);
?>

the geek man at hot mail point com

15 years ago

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.

marc at gutt dot it

6 years ago

This php.net example could be confusing:
<?php
file_put_contents
($file, $person, FILE_APPEND | LOCK_EX);
?>

You do not need LOCK_EX if you write only to a file (like log files). Multiple writing processes are already queued. Test it on your own by calling this script 4 times simultaneously:
<?php
function string_rand($len, $split="\n") {
return
substr(chunk_split(bin2hex(openssl_random_pseudo_bytes(ceil($len / 2))), 1023, $split), 0, $len);
}
ini_set('memory_limit', '200M');

if (!

file_put_contents('../cache4/file.txt', string_rand(102400000), FILE_APPEND)) {
exit(
'file_put_contents() error!');
}
clearstatcache();
echo
'filesize: ' . filesize('../cache4/file.txt') . PHP_EOL;$fp = fopen('../cache4/file.txt', 'r');
if (
$fp) {
while ((
$line = fgets($fp)) !== false) {
if (
strlen($line) != 1024) {
exit(
'Line length error!');
}
}
fclose($fp);
}
?>

You will not see an error, the last called script needs the longest time (as it is the last one in the queue) and the final size will be 409600000 bytes as it should be.

vilhar at hotmail dot com

7 years ago

This should also handle $filename from other than root and also $filename without path.

function file_force_contents($filename, $data, $per = 0755, $flags = 0) {
$fn = "";
if(substr($filename, 0, 1) === "/") $fn .= "/";
$parts = explode("/", $filename);
$file = array_pop($parts);

foreach($parts as $part) {
if(!is_dir($fn .= "$part")) mkdir($fn, $per, true);
$fn .= "/";
}

file_put_contents($fn.$file, $data, $flags);
}

michel kollenhoven

10 years ago

egingell at sisna dot com

15 years ago

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);
}
?>

klunker dot roox at gmail dot com

8 years ago

if path to the file not exist function file_put_contents can't create it. This simple function make it on UNIX-based and Windows servers.
<?php
function file_put_contents_force(){
$args = func_get_args();
$path = str_replace(array('/','\\'), DIRECTORY_SEPARATOR, $args[0]);
$parts = explode(DIRECTORY_SEPARATOR, $path);
array_pop($parts);
$directory = '';
foreach(
$parts as $part):
$check_path = $directory.$part;
if(
is_dir($check_path.DIRECTORY_SEPARATOR) === FALSE) {
mkdir($check_path, 0755);
}
$directory = $check_path.DIRECTORY_SEPARATOR;
endforeach;
call_user_func_array('file_put_contents',$args);
}
?>

Nadeem

8 years ago

Log custom or error messages to a file.

<?phpclass Logger{

protected

$file;

protected

$content;

protected

$writeFlag;

protected

$endRow;

public function

__construct($file,$endRow="\n",$writeFlag=FILE_APPEND) { $this->file=$file;$this->writeFlag=$writeFlag;$this->endRow=$endRow;

}

public function

AddRow($content="",$newLines=1){

for (

$m=0;$m<$newLines;$m++)
{
$newRow .= $this->endRow;

}

$this->content .= $content . $newRow;

}

public function

Commit(){

return

file_put_contents($this->file,$this->content,$this->writeFlag);

}

public function

LogError($error,$newLines=1)
{
if (
$error!=""){$this->AddRow($error,$newLines);
echo
$error;

}

}

}

$logFileDirectoryAndName="/yourDirectory/yourFileName.xxx";$logger = new Logger($logFileDirectoryAndName);$logger->AddRow("Your Log Message");#log a system error and echo a message
$logger->LogError(mysql_error($conn));$logger->Commit();
?>

Abe

5 years ago

If you need to read a file, process the contents, and then write the contents back, all inside a lock so that no other process can interfere, then you probably can't use file_put_contents in lock mode.

As a work around, you can consider trying the following code to do a file write (fwrite) inside of a file lock.

Play with the $overwriting= setting to switch from simply appending to completely overwriting.

<?php
// Tested in PHP7.0.18$trackErrors = ini_get('track_errors');
ini_set('track_errors', 1);$filename="c:/temp/test.txt";

if ( !

file_exists($filename) ) {
touch($filename);
}
$mode="r+";
$fh=fopen($filename, $mode);
if ( !
$fh ) {
echo
"<LI style='color:red'>Failed to open $filename in $mode";
die();
}

if (

1==1 ) {
flock($fh, LOCK_EX);

if (

1==1 ) {
if (
filesize($filename) > 0) {
$txt = fread($fh, filesize($filename));
echo
"BEFORE:<OL>$txt</OL>";
}
else {
$txt = "empty";
}
$txt = "<LI>Date is now " . gmdate("Y-m-d H:i:s", time());

echo

"<HR>WRITING:<OL>";
if (
1==1 ) {$overwrite = false;
if (
$overwrite) {
echo
"(Overwrite)<BR><BR>";
ftruncate($fh, 0);
// ftruncate is here as rewind will move the pointer
// to the beginning of the file and allow overwrite,
// but it will not remove existing content that
// extends beyond the length of the new write
rewind($fh);
}
else {
echo
"(Appending)<BR><BR>";
}

if (

fwrite($fh, $txt) == FALSE) {
echo
"<LI style='color:red'>Failed to write to $filename";
die();
}
else {
echo
"$txt";
}
fflush($fh);

}
echo

"</OL>";
}
flock($fh, LOCK_UN);
}
fclose($fh);// -------------------------------------------------------------------echo "<HR>AFTER:<OL>";
if (
1==2 ) {
// I've noticed that this block fails to pick up the newly
// written content when run with fread, but does work with
// the fgets logic below - possibly there is caching going on.
$mode = "r";
$fh2 = fopen($filename, $mode);
$contents = fread($fh2, filesize($filename));
echo
"$contents";
fclose($fh2);
}
else {
$fh3 = fopen($filename, "r");
while (!
feof($fh3)) {
$line = fgets($fh3);
echo
$line;
}
fclose($fh3);
}
echo
"</OL>";

echo

"<HR>Fin";
?>

hilton at allcor dot com dot br

12 years ago

NOTE : file_put_contents create files UTF-8

<?php
$myFile
= 'test.txt';
$myContent = 'I love PHP'; file_put_contents($myFile, utf8_encode($myContent));
?>

jul dot rosset at gmail dot com

2 years ago

This function doesn't return False if all data isn't write, especially when data is a stream resource

You must check yourself using return value.
<?php
$url
= 'https://monsite.fr/image.png';
$size = filesize($url);
$written = file_put_contents('image.png', fopen($url, 'r'));
if (
$size === false || $size != $written) {
die(
'Download failed');
}
?>

clement dot delmas at gmail dot com

13 years ago

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);

?>

josemiguel at likeik dot com

7 years ago

Under PHP7.0, I have seen that using an empty string as $data, the function returns FALSE instead of 0 as it should:

$data = ''
$size = file_put_contents($filename, $data, FILE_APPEND);
if ($size == FALSE)
{
echo "error writing file"
}

Code will give error when $data is an empty string even using == operator.

Hope it helps somebody...

admin at nabito dot net

15 years ago

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);?>

4 ответа

Это может быть проблема разрешения

Является ли каталог /files изменен до 777? иногда php не позволит вам получить доступ к каталогам, если у них недостаточно прав. Однако я не знаю о пустых ошибках.

Попробуйте проверить, есть ли у него достаточно разрешений, если нет, тогда установите его на 777 и попробуйте.

Famver Tags

Поделиться

Используете ли вы полный путь к файловой системе или пытаетесь использовать URI? Я думаю, что эта функция PHP ожидает, что вы укажете путь, поскольку файл найден в файловой системе.

Относительные пути должны быть в порядке, хотя.

Вам может потребоваться убедиться, что файл существует и что его разрешения установлены на 777. Иногда я обнаружил, что этого недостаточно, чтобы иметь права доступа к каталогу, равные 777, но файл также должен существовать.

jmort253

Поделиться

Мы испытали это, требуя обходного пути (независимо от метода, разрешений и всего остального, упомянутого здесь). Когда все остальные исправления не удались, мы обнаружили, что он может быть связан с ограничениями, созданными SELinux.

designgroop

Поделиться

Если вы используете Windows, следующее решение отлично работает для меня на Windows 10 под управлением PHP 5.5.38

Если у вас возникла эта проблема в Windows/IIS, попробуйте следующее:

  1. Перейдите в папку, в которую вы пытаетесь записать, щелкните правой кнопкой мыши и выберите «Свойства».
  2. Выберите вкладку «Безопасность»
  3. Нажмите Редактировать
  4. Нажмите кнопку Добавить
  5. Нажмите Дополнительно
  6. Нажмите Найти сейчас
  7. Из списка User выберите IUSR и нажмите OK
  8. Нажмите OK еще раз.
  9. IUSR будет отображаться в верхней части окна с надписью «Группа имен пользователей»
  10. Выберите IUSR и предоставьте необходимые разрешения в представлении списка «Permissions for BATCH».
  11. Нажмите Применить, и все готово.

Шаги могут немного отличаться для разных версий окон. Это также относится к ASP.NET, хотя я думаю, что добавленные вами пользователи — это пользователи сети (пользователи NETWORK AND ORWORK SERVICE), а также IUSR.

user2288580

Поделиться

Ещё вопросы

  • 1Hibernate встраиваемое отображение списка с идентификатором
  • 1Проблема визуализации простого графического интерфейса в Java
  • 1Добавить String в ArrayList, если только не пустой
  • 0Ошибка «Анализ: неизвестное имя типа» после обновления XCode
  • 0Combobox не применяется в поле выбора
  • 1Обработка файловых операций с сопрограммами
  • 0Создание пакета установщика Windows
  • 0Разве этот код jQuery не должен возвращать все входные данные внутри # product-create-2?
  • 1Как разделить макет на 3 вида
  • 1Лучший способ написать для цикла при возможности доступа к элементам в контейнере Python
  • 1Не удалось загрузить файл или сборку в приложении WP8.1
  • 0Экспорт Excel из таблицы MySQL
  • 1Launcher на операционной системе Android
  • 0Встроенное переполнение: скрыто, только частично работает
  • 1Общий ServiceLocator GetInstance
  • 1Независимая ось для каждого участка в pandas boxplot
  • 1Проблемы новичка с Eclipse и запуска импортированного файла .jar?
  • 1Операции с массивами Python
  • 0Как я могу позиционировать статический div при нажатии кнопки?
  • 0Angularjs контрольный отчет о перерыве
  • 1преобразование значения java двухмерного массива (буквы) в целое число (число)
  • 0UI Grid бесконечная прокрутка для работы с полосой прокрутки браузера
  • 0Объединить массив в установленный массив при случайных индексах в PHP
  • 0Как сохранить возвращаемые значения из вызова .each в массив
  • 0получение ошибок в PHP-кодировании чего-то неопределенного переменной
  • 0PHP поймать должным образом
  • 0Приложение Angular показывает только скорректированный динамический контент после обновления
  • 1Размер бита System.ConsoleColor
  • 0Печать вектора C ++ с добавлением новой строки
  • 1NullPointException и длина массива объектов
  • 1XamDataGrid — добавление столбцов во время выполнения
  • 0Два счетчика в пределах заявления Smartys Foreach
  • 1Получить общее количество часов, минут с релятивделта
  • 0как установить атрибуты JsTree
  • 0Угловой-включить не работает
  • 0SDL2 основная система тиканья (openGL)
  • 0Синглтон без конструктора копирования
  • 0запись имени файла — fwrite необходимо разделить символом «/»
  • 0CSS-стиль не отображается в браузере
  • 0OpenCV QT дисплей видео
  • 1доступ к камере Cordova с удаленного сайта
  • 0Как использовать jQuery «автозаполнение источника» внутри цикла JavaScript для?
  • 1java.lang.NullPointerException — не может найти пустую переменную
  • 1уменьшить значение translate-x
  • 0HTML включен боковое меню мешает междустрочный интервал
  • 0OpenGL шейдер направленного света зеркальное отражение увеличивается с расстоянием
  • 0Аргументы не проходят через мой сервис между контроллерами
  • 1Не удается установить подпакет пространства имен Python в зависимости от другого подпакета
  • 1Java Deep Clone — клонировать каждый элемент в ArrayList, если Cloneable, независимо от типа
  • 0Как объявить класс с 1000000 элементов C ++

Понравилась статья? Поделить с друзьями:
  • Ошибка file has changed while reading
  • Ошибка file efi microsoft boot bcd
  • Ошибка getvolumenameforvolumemountpoint 0x80071126
  • Ошибка file boot bcd 0xc00000e9
  • Ошибка error opening file for writing