Php write uploaded file

fwrite

fwrite() writes the contents of data to the file stream pointed to by stream .

Parameters

A file system pointer resource that is typically created using fopen() .

The string that is to be written.

If length is an int , writing will stop after length bytes have been written or the end of data is reached, whichever comes first.

Return Values

fwrite() returns the number of bytes written, or false on failure.

Errors/Exceptions

fwrite() raises E_WARNING on failure.

Changelog

Examples

Example #1 A simple fwrite() example

$filename = ‘test.txt’ ;
$somecontent = «Add this to the file\n» ;

// Let’s make sure the file exists and is writable first.
if ( is_writable ( $filename ))

// In our example we’re opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that’s where $somecontent will go when we fwrite() it.
if (! $fp = fopen ( $filename , ‘a’ )) echo «Cannot open file ( $filename )» ;
exit;
>

// Write $somecontent to our opened file.
if ( fwrite ( $fp , $somecontent ) === FALSE ) echo «Cannot write to file ( $filename )» ;
exit;
>

echo «Success, wrote ( $somecontent ) to file ( $filename )» ;

> else echo «The file $filename is not writable» ;
>
?>

Notes

Note:

Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:

function fwrite_stream ( $fp , $string ) for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) $fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) return $written ;
>
>
return $written ;
>
?>

Note:

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with ‘b’ included in fopen() mode parameter.

Note:

If stream was fopen() ed in append mode, fwrite() s are atomic (unless the size of data exceeds the filesystem’s block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite() ; all of the data will be written without interruption.

Note:

If writing twice to the file pointer, then the data will be appended to the end of the file content:

$fp = fopen ( ‘data.txt’ , ‘w’ );
fwrite ( $fp , ‘1’ );
fwrite ( $fp , ’23’ );
fclose ( $fp );

// the content of ‘data.txt’ is now 123 and not 23!
?>

See Also

  • fread() — Binary-safe file read
  • fopen() — Opens file or URL
  • fsockopen() — Open Internet or Unix domain socket connection
  • popen() — Opens process file pointer
  • file_get_contents() — Reads entire file into a string
  • pack() — Pack data into binary string

User Contributed Notes 33 notes

After having problems with fwrite() returning 0 in cases where one would fully expect a return value of false, I took a look at the source code for php’s fwrite() itself. The function will only return false if you pass in invalid arguments. Any other error, just as a broken pipe or closed connection, will result in a return value of less than strlen($string), in most cases 0.

Therefore, looping with repeated calls to fwrite() until the sum of number of bytes written equals the strlen() of the full value or expecting false on error will result in an infinite loop if the connection is lost.

This means the example fwrite_stream() code from the docs, as well as all the «helper» functions posted by others in the comments are all broken. You *must* check for a return value of 0 and either abort immediately or track a maximum number of retries.

Below is the example from the docs. This code is BAD, as a broken pipe will result in fwrite() infinitely looping with a return value of 0. Since the loop only breaks if fwrite() returns false or successfully writes all bytes, an infinite loop will occur on failure.

// BROKEN function — infinite loop when fwrite() returns 0s
function fwrite_stream ( $fp , $string ) <
for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) <
$fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) <
return $written ;
>
>
return $written ;
>
?>

if you need a function that writes all data, maybe try

/**
* writes all data or throws
*
* @param mixed $handle
* @param string $data
* @throws \RuntimeException when fwrite returned * @return void
*/
/*private static*/ function fwrite_all ( $handle , string $data ): void
$original_len = strlen ( $data );
if ( $original_len > 0 ) $len = $original_len ;
$written_total = 0 ;
for (;;) $written_now = fwrite ( $handle , $data );
if ( $written_now === $len ) return;
>
if ( $written_now < 1 ) throw new \ RuntimeException ( "could only write < $written_total >/ < $original_len >bytes!» );
>
$written_total += $written_now ;
$data = substr ( $data , $written_now );
$len -= $written_now ;
// assert($len > 0);
// assert($len === strlen($data));
>
>
>

$handles can also be used to output in console like below example

fwrite(STDOUT, «Console Output»);

Источник

Запись и чтение файлов в PHP

Примеры сохранения и чтения текстовых данных и массивов в файлы.

Сохранение в файл

Функция file_put_contents() записывает содержимое переменной в файл, если файла не существует. то пытается его создать, если существует то полностью перезапишет его.

File_put_contents:

$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; $filename = __DIR__ . '/file.txt'; file_put_contents($filename, $text);

Fopen / fwrite:

Набор функций fopen, fwrite, fclose предназначены для более гибкой работы с файлами.

  • fopen – открытие или создание файла.
  • fwrite – запись данных.
  • fclose – закрытие файла.
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; $filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'w'); fwrite($fh, $text); fclose($fh);

Возможные режимы fopen():

Mode Описание
r Открывает файл только для чтения, помещает указатель в начало файла.
r+ Открывает файл для чтения и записи, помещает указатель в начало файла.
w Открывает файл только для записи, помещает указатель в начало файла и обрезает файл до нулевой длины. Если файл не существует – пробует его создать.
w+ Открывает файл для чтения и записи, помещает указатель в начало файла и обрезает файл до нулевой длины. Если файл не существует – пытается его создать.
a Открывает файл только для записи, помещает указатель в конец файла. Если файл не существует – пытается его создать.
a+ Открывает файл для чтения и записи, помещает указатель в конец файла. Если файл не существует – пытается его создать.
x Создаёт и открывает только для записи; помещает указатель в начало файла. Если файл уже существует, вызов fopen() закончится неудачей, вернёт false и выдаст ошибку. Если файл не существует, попытается его создать.
x+ Создаёт и открывает для чтения и записи, в остальном имеет то же поведение, что и « x ».
c Открывает файл только для записи. Если файл не существует, то он создаётся. Если же файл существует, то он не обрезается (в отличие от « w »), и вызов к этой функции не вызывает ошибку (также как и в случае с « x »). Указатель на файл будет установлен на начало файла.
c+ Открывает файл для чтения и записи, в остальном имеет то же поведение, что и « c ».

Доступно в место fwrite() используют fputs() , разницы ни какой т.к. эта функция является псевдонимом.

Дописать строку в начало файла

$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; $text = file_get_contents($filename); file_put_contents($filename, $new_str . PHP_EOL . $text);

Дописать строку в конец файла

$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; file_put_contents($filename, PHP_EOL . $new_str, FILE_APPEND);
$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'c'); fseek($fh, 0, SEEK_END); fwrite($fh, PHP_EOL . $new_str); fclose($fh);

Чтение из файла

Чтение всего файла

$filename = __DIR__ . '/file.txt'; $text = file_get_contents($filename); echo $text;
$filename = __DIR__ . '/file.txt'; $text = ''; $fh = fopen($filename, 'r'); while (!feof($fh)) < $line = fgets($fh); $text .= $line . PHP_EOL; >fclose($fh); echo $text;

Чтение файла в массив

Функция file() – читает содержимое файла и помещает его в массив, доступны опции:

  • FILE_IGNORE_NEW_LINES – пропускать новую строку в конце каждого элемента массива.
  • FILE_SKIP_EMPTY_LINES – пропускать пустые строки.
$filename = __DIR__ . '/file.txt'; $array = file($filename); print_r($array);

Чтение файла сразу в браузер

$filename = __DIR__ . '/file.txt'; readfile($filename);

Получить первую строку из файла

$filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'r'); echo fgets($fh); fclose($fh); /* или */ $filename = __DIR__ . '/file.txt'; $array = file($filename); echo $array[0];

Первые три строки из файла:

$filename = __DIR__ . '/file.txt'; $array = file($filename); $first_3 = array_slice($array, 0, 3); print_r($first_3);

Получить последнюю строку из файла

$filename = __DIR__ . '/file.txt'; $array = file($filename); $last = array_slice($array, -1); echo $last[0];

Последние три строки из файла:

$filename = __DIR__ . '/file.txt'; $array = file($filename); $last_3 = array_slice($array, -3); print_r($last_3);

Запись и чтение массивов в файл

Serialize

Не очень удачное хранение данных в сериализованном виде т.к. изменение одного символа может привести к ошибке чтения всех данных в файле. Подробнее в статье «Функция serialize, возможные проблемы»

Запись:

$array = array('foo', 'bar', 'hallo', 'world'); $text = base64_encode(serialize($array)); file_put_contents(__DIR__ . '/array.txt', $text);

Чтение:

$array = unserialize(base64_decode($text)); print_r($array);

JSON

Запись:

$array = array('foo', 'bar', 'hallo', 'world'); $json = json_encode($array, JSON_UNESCAPED_UNICODE); file_put_contents(__DIR__ . '/array.json', $json);

Чтение:

$json = file_get_contents(__DIR__ . '/array.json'); $array = json_decode($json, true); print_r($array);

Источник

Write Post data to file with PHP

I need to post data using the code below, to php file that will save it in a text file. I just don’t know how to create the php file to receive the data below and save it in a text file. as simple as possible.

try < // Add your data ListnameValuePairs = new ArrayList(2); nameValuePairs.add(new BasicNameValuePair("stringData", "12345")); nameValuePairs.add(new BasicNameValuePair("stringData", "AndDev is Cool!")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); String responseText = EntityUtils.toString(response.getEntity()); tv.setText(responseText); > catch (ClientProtocolException e) < // TODO Auto-generated catch block >catch (IOException e) < // TODO Auto-generated catch block >

2 Answers 2

file_put_contents('test.txt', file_get_contents('php://input')); 

If you want to get the value of one particular key and save it, then yes. If you just want to dump the raw POST data (which doesn’t have to be key value pairs — it could be binary data, for example) then the ‘php://input’ stream will read it. The question was vague and asked for «as simple as possible».. well it doesn’t get much simpler.

also, file_put_contents performs the fopen, fwrite and fclose in one hit — easier to use and to read.

add a third parameter FILE_APPEND to file_put_contents to append request data to the file instead of overwriting all the time.

1) In PHP, to get POST data from an incoming request use the $_POST array. The POST array in PHP is associative, which means that each incoming parameter will be a key-value pair. In development it’s helpful to understand what you’re actually getting in $_POST. You can dump the contents using printf() or var_dump() like the following.

2) Choose a useful string-based format for storing the data. PHP has a serialize() function, which you could use to turn the array into a string. It’s also easy to turn the array into a JSON string. I suggest using JSON since it’s natural to use this notation across various languages (whereas using a PHP serialization would somewhat bind you to using PHP in the future). In PHP 5.2.0 and above the json_encode() function is built-in.

$json_string = json_encode($_POST); // For info re: JSON in PHP: // http://php.net/manual/en/function.json-encode.php 

3) Store the string in a file. Try using fopen(), fwrite(), and fclose() to write the json string to a file.

$json_string = json_encode($_POST); $file_handle = fopen('my_filename.json', 'w'); fwrite($file_handle, $json_string); fclose($file_handle); // For info re: writing files in PHP: // http://php.net/manual/en/function.fwrite.php 

You’ll want to come up with a specific location and methodology to the file paths and file names used.

Note: There’s also the possibility of getting the HTTP request’s POST body directly using $HTTP_RAW_POST_DATA. The raw data will be URL-encoded and it will be a string that you can write to a file as described above.

Источник

Читайте также:  Python datetime сложение дат
Оцените статью