|
|
 |
fwrite (PHP 3, PHP 4, PHP 5) fwrite -- Escritura sobre archivos, segura con material
binario Descripciónint fwrite ( resource gestor, string cadena [, int longitud] )
fwrite() escribe los contenidos de
cadena a la secuencia de archivo apuntada
por gestor. Si el argumento
longitud es entregado, la escritura se
detendrá después de que
longitud bytes hayan sido escritos, o al
alcanzar el final de cadena, aquello que
ocurra primero.
fwrite() devuelve el número de bytes
escritos, o FALSE en caso de fallo.
Note que si se utiliza el argumento
longitud, entonces la opción de
configuración magic_quotes_runtime
será ignorada y no se eliminarán caracteres de
barra desde la cadena.
Nota:
En los sistemas que diferencian entre archivos binarios y de
texto (es decir, Windows) el archivo debe ser abierto incluyendo
el valor 'b' en el parámetro de modo de
fopen().
Ejemplo 1. Un ejemplo sencillo de
fwrite() |
<?php
$nombre_archivo = 'prueba.txt';
$contenido = "Agregar esto al archivo\n";
if (is_writable($nombre_archivo)) {
if (!$gestor = fopen($nombre_archivo, 'a')) {
echo "No se puede abrir el archivo ($nombre_archivo)";
exit;
}
if (fwrite($gestor, $contenido) === FALSE) {
echo "No se puede escribir al archivo ($nombre_archivo)";
exit;
}
echo "Éxito, se escribió ($contenido) al archivo ($nombre_archivo)";
fclose($gestor);
} else {
echo "No se puede escribir sobre el archivo $nombre_archivo";
}
?>
|
|
Vea también fread(),
fopen(), fsockopen(),
popen(), y
file_put_contents().
santibari at yahoo dot com
18-Mar-2006 11:49
To write a specific byte into a file (let's,say 0000 0001), use the function chr().
<?php
fputs($fp,chr(0x01),1);
?>
bahatest at ifrance doc com
23-Jul-2005 02:40
[Editor's Note: No, you only need to use this if you want a BOM (Byte order mark) added to the document - most people do not.]
if you have to write a file in UTF-8 format, you have to add an header to the file like this :
<?php
$f=fopen("test.txt", "wb");
$text=utf8_encode("éaè!");
$text="\xEF\xBB\xBF".$text;
fputs($f, $text);
fclose($f);
?>
james at nicolson dot biz
06-Jul-2005 08:09
I could'nt quite get MKP Dev hit counter to work.... this is how I modified it
<?
function hitcount()
{
$file = "counter.txt";
if ( !file_exists($file)){
touch ($file);
$handle = fopen ($file, 'r+'); $count = 0;
}
else{
$handle = fopen ($file, 'r+'); $count = fread ($handle, filesize ($file));
settype ($count,"integer");
}
rewind ($handle); fwrite ($handle, ++$count); fclose ($handle); return $count;
}
?>
albert;cutthis; at ;coznospam;ribox dot nl
07-Jun-2005 09:02
To write 'true binary' files combine with pack() :
$a = 65530;
$fp = fopen('test.dat', 'w');
fwrite($fp, pack('L', $a));
fclose($fp);
MKP Dev
12-May-2005 05:25
bluevd at gmail dot com mentioned a hit counter. In his/her implementation, the file is first opened, read, closed, then opened +truncated, then written, and closed again. An alternative to this is:
<?php
$file = 'counter.txt or whatever';
$handle = fopen ($file, 'r+'); $count = int (fread ($handle, filesize ($file)));
echo "Number of hits $count";
rewind ($handle); fwrite ($handle, ++$count); fclose ($handle); ?>
Will at EnigmaChannel dot com
25-Mar-2005 06:24
Using fwrite to write to a file in your include folder...
PHP does not recognise the permissions setting for the file until you restart the server... this script works fine. (still have to create the blank text file first though...it is not created automatically) On OS X Server..
Using the 1 in fopen tells php to look for the file in your include folder. Change your include folder by altering include_path in php.ini
On OS X Server, php.ini is in private/etc/php.ini.default
copy the file and call it php.ini
the default include path is usr/lib/php
(All these folders are hidden - use TinkerTool to reveal them)
<?php
$file = fopen('textfile.txt', 'a', 1);
$text="\n Your text to write \n ".date('d')."-".date('m')."-".date('Y')."\n\n";
fwrite($file, $text);
fclose($file);
?>
goodwork at myrealbox dot com
17-Feb-2005 12:15
difficulty appending to file in SAFE MODE ON
if you are getting resource errors etc try this...
$textline="whatever string you submitted or created";
$filename="afilename.log"; // or whatever your path and filename
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)"; // or handle your error
exit; }
$textline.="\n"; // dont forget that period
// now write content to our opened file.
IF (fwrite($handle,$textline) === FALSE)
{echo "Cannot write to file ($filename)";// or handle your error
exit;}
echo "Success, wrote ($textline) to file ($filename)";
fclose($handle);
sheyh
09-Feb-2005 09:55
if you want to create quickly and without fopen use system, exec
system('echo "blahblah" > /path/file');
kzevian at cybercable dot net dot mx
03-Feb-2005 11:27
I needed to append, but I needed to write on the file's beginning, and after some hours of effort this worked for me:
$file = "file.txt";
if (!file_exists("file.txt")) touch("file.txt");
$fh = fopen("file.txt", "r");
$fcontent = fread($fh, filesize("file.txt"));
$towrite = "$newcontent $fcontent";
$fh22 = fopen('file.txt', 'w+');
fwrite($fh2, $towrite);
fclose($fh);
fclose($fh2);
bluevd at gmail dot com
22-Dec-2004 09:56
Watch out for mistakes in writting a simple code for a hit counter:
<?php
$cont=fopen('cont.txt','r');
$incr=fgets($cont);
$incr++;
fclose($cont);
$cont=fopen('cont.txt','a');
fwrite($cont,$incr);
fclose($cont);
?>
Why? notice the second fopen -> $cont=fopen('cont.txt','a');
it opens the file in writting mode (a). And when it ads the incremented
value ( $incr ) it ads it ALONG the old value... so opening the counter
page about 5 times will make your hits number look like this
012131214121312151.21312141213E+ .... you get the piont.
nasty, isn't it? REMEMBER to open the file with the 'w' mode (truncate
the file to 0). Doing this will clear the file content and it will make sure that
your counter works nice. This is the final code
<?php
$cont=fopen('cont.txt','r');
$incr=fgets($cont);
$incr++;
fclose($cont);
$cont=fopen('cont.txt','w');
fwrite($cont,$incr);
fclose($cont);
?>
Notice that this work fine =)
XU (alias Iscu Andrei)
chill at cuna dot org
26-Oct-2004 03:32
In PHP 4.3.7 fwrite returns 0 rather than false on failure.
The following example will output "SUCCESS: 0 bytes written" for existing file test.txt:
$fp = fopen("test.txt", "rw");
if (($bytes_written = fwrite($fp, "This is a test")) === false) {
echo "Unable to write to test.txt\n\n";
} else {
echo "SUCCESS: $bytes_written bytes written\n\n";
}
php at biggerthanthebeatles dot com
21-Aug-2003 03:04
Hope this helps other newbies.
If you are writing data to a txt file on a windows system and need a line break. use \r\n . This will write hex OD OA.
i.e.
$batch_data= "some data... \r\n";
fwrite($fbatch,$batch_data);
The is the equivalent of opening a txt file in notepad pressing enter and the end of the line and saving it.
Andi
17-Jul-2003 02:32
[Ed. Note:
The runtime configuration setting auto_detect_line_endings should solve this problem when set to On.]
I figured out problems when writing to a file using \r as linebreak, after that file() wasn't able to read the data from that file.
Using \n solved the problem.
chedong at hotmail dot com
20-Jun-2003 02:36
the fwrite output striped the slashes if without length argument given, example:
<?php
$str = "c:\\01.txt";
$out = fopen("out.txt", "w");
fwrite($out, $str);
fclose($out);
?>
the out.txt will be:
c:^@1.txt
the '\\0' without escape will be '\0' ==> 0x00.
the correct one is change fwrite to:
fwrite($out, $str, strlen($str));
Jake Roberts
04-Jun-2003 11:35
Use caution when using:
$content = fread($fh, filesize($fh)) or die "Error Reading";
This will cause an error if the file you are reading is zero length.
Intead use:
if ( false === fread($fh, filesize($fh)) ) die "Error Reading";
Thus it will be successful on reading zero bytes but detect and error returned as FALSE.
Chris Blown
19-May-2003 03:12
Don't forget to check fwrite returns for errors! Just because you successfully opened a file for write, doesn't always mean you can write to it.
On some systems this can occur if the filesystem is full, you can still open the file and create the filesystem inode, but the fwrite will fail, resulting in a zero byte file.
seeker at seek dot planet
09-Feb-2003 10:33
[[Editors note: There is no "prepend" mode, you must essentially rewrite the entire file after prepending contents to a string. Perhaps you will use file(), modify, implode(), then fopen()/fwrite() it back]]
To put strings into the front of the file, you need to set place the pointer at the top of the file when openning the file with fopen(), see fopen() for more info.
| |
|
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|