Emptying a file with php [duplicate] - php

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
PHP: Is there a command that can delete the contents of a file without opening it?
How do you empty a .txt file on a server with a php command?

Here's a way to only emptying if it already exists and that doesn't have the problem of using file_exists, as the the file may cease to exist between the file_exists call and the fopen call.
$f = #fopen("filename.txt", "r+");
if ($f !== false) {
ftruncate($f, 0);
fclose($f);
}

Write an empty string as the content of filename.txt:
file_put_contents('filename.txt', '');

$fh = fopen('filename.txt','w'); // Open and truncate the file
fclose($fh);
Or in one line and without storing the (temporary) file handle:
fclose(fopen('filename.txt','w'));
As others have stated, this creates the file in case it doesn't exist.

Just open it for writing:
if (file_exists($path)) { // Make sure we don't create the file
$fp = fopen($path, 'w'); // Sets the file size to zero bytes
fclose($fp);
}

First delete it using unlink() and then just create a new empty file with the same name.

With ftruncate(): http://php.net/ftruncate

you can use the following code
`
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "";
fwrite($fh, $stringData);
fclose($fh);
`
It will just override your file content to blank

Related

how to read a new line from a text file in php? [duplicate]

This question already has answers here:
What is the best way to read last lines (i.e. "tail") from a file using PHP?
(6 answers)
How to read a large file line by line?
(14 answers)
Closed 8 years ago.
I am saving my data in text file line by line through PHP code and which is done successfully.
But when I am retrieving the data from text file I am getting the whole content which I have entered in a file which means whenever I enter a new line in the text file and reads that file I get whole content of the file. So my query is that how it is possible to read only new line when I read the text file.
This what I have tried
$file = $_POST['read_fileid'];
$myFile = $file.".txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
fgets() function can be used to read the file line by line:
$handle = fopen("input.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false)
{
//code to read file`
}
}
else
{
// error : file cannot be opened
}
fclose($handle);

Check if a file is writable before writing to it

I'm trying to create a script which will check if a file is writable before writing to it,
Making sure the script doesn't exit prematurely.
I've gotten this far
$meta =stream_get_meta_data($file);
while(!is_writable($meta['uri'])){
sleep(rand(0,3));
$meta=stream_get_meta_data($file);
echo("sleeping\n");
}
$csv = fopen($file, 'a+')or die("can't open file");
When I test the script with $file open, it blocks on the sleeping part even after $file is closed.
I'm fairly new to PHP, so there might be a processing paradigm that i'm not aware of.
Any help would be very welcome.
EDIT : The reason I entered this into a while loop is to continually check if the file is open or not. Hence it should only exit the while loop once the file is finally writable.
The sleep is simply to replicate a person trying to open the file.
its is_writable ( string $filename )
$filename = 'test.txt';
if (is_writable($meta['uri']) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
is_writable(<your_file>)
This should do the trick?
http://www.php.net/manual/en/function.is-writable.php
--
Also you can use
#fopen(<your_file>, 'a')
If this returns false, file is not writiable
Using touch():
if (touch($file_name) === FALSE) {
throw new Exception('File not writable');
}
You probably should not be using a while loop just to check if the file is writable. Maybe change your code around a bit to something like this:
$meta =stream_get_meta_data($file);
if (is_writable($file)){
sleep(rand(0,3));
$meta=stream_get_meta_data($file);
echo("sleeping\n");
}
$csv = fopen($file, 'a+')or die("can't open file");
However since I do not know what your main goal is you could do it like this:
$meta =stream_get_meta_data($file);
while(!is_writable($file)){
sleep(rand(0,3));
$meta=stream_get_meta_data($file);
echo("sleeping\n");
}
$csv = fopen($file, 'a+')or die("can't open file");

fopen() and save as - php

I have this issue, I would like to create a new file, with another name.
For now I have the file CLPRE.txt opened and saving the changes in the same file, I would like to create a new file from the original one like this
pseudo-code:
$unique= sha1( uniqid(phc) );
$newFile = $unique.CLPRE.txt
The actual code is resumed with this:
$myFile = $loja."/CL.xml";
$fh = fopen($myFile, 'w') or die("can't open");
$pre= file_get_contents('CLPRE.txt');
$writeThis = "some text";
fwrite($fh, $pre.$writeThis);
fclose($fh);
use file_put_contents
This function is identical to calling fopen(), fwrite() and fclose()
successively to write data to a file.
If filename does not exist, the file is created. Otherwise, the
existing file is overwritten, unless the FILE_APPEND flag is set.
Umm you're basically doing it already, you just need to do another call and create it via:
$new = fopen($unique.'CLPRE.txt', 'w') or die("can't open");
then add what you want into it, and close with:
fwrite($new , $pre.$writeThis);
fclose($new );
Reference to fopen() - http://www.decompile.com/cpp/faq/fopen_write_append.htm

How to write into a file in PHP?

I have this script on one free PHP-supporting server:
<html>
<body>
<?php
$file = fopen("lidn.txt","a");
fclose($file);
?>
</body>
</html>
It creates the file lidn.txt, but it's empty.
How can I create a file and write something into it,
for example the line "Cats chase mice"?
You can use a higher-level function like:
file_put_contents($filename, $content);
which is identical to calling fopen(), fwrite(), and fclose() successively to write data to a file.
Docs: file_put_contents
Consider fwrite():
<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase');
fwrite($fp, 'mice');
fclose($fp);
http://php.net/manual/en/function.fwrite.php
$text = "Cats chase mice";
$filename = "somefile.txt";
$fh = fopen($filename, "a");
fwrite($fh, $text);
fclose($fh);
You use fwrite()
It is easy to write file :
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
Here are the steps:
Open the file
Write to the file
Close the file
$select = "data what we trying to store in a file";
$file = fopen("/var/www/htdocs/folder/test.txt", "w");
fwrite($file, $select->__toString());
fclose($file);
I use the following code to write files on my web directory.
write_file.html
<form action="file.php"method="post">
<textarea name="code">Code goes here</textarea>
<input type="submit"value="submit">
</form>
write_file.php
<?php
// strip slashes before putting the form data into target file
$cd = stripslashes($_POST['code']);
// Show the msg, if the code string is empty
if (empty($cd))
echo "Nothing to write";
// if the code string is not empty then open the target file and put form data in it
else
{
$file = fopen("demo.php", "w");
echo fwrite($file, $cd);
// show a success msg
echo "data successfully entered";
fclose($file);
}
?>
This is a working script. be sure to change the url in the form action and the target file in fopen() function if you want to use it on your site.
In order to write to a file in PHP you need to go through the following steps:
Open the file
Write to the file
Close the file
$select = "data what we trying to store in a file";
$file = fopen("/var/www/htdocs/folder/test.txt", "a");
fwrite($file , $select->__toString());
fclose($file );
fwrite() is a smidgen faster and file_put_contents() is just a wrapper around those three methods anyway, so you would lose the overhead.
Article
file_put_contents(file,data,mode,context):
The file_put_contents writes a string to a file.
This function follows these rules when accessing a file.If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename
Create the file if it does not exist then Open the file and Lock the file if LOCK_EX is set and If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content
Write the data into the file and Close the file and release any locks.
This function returns the number of the character written into the file on success, or FALSE on failure.
fwrite(file,string,length):
The fwrite writes to an open file.The function will stop at the end of the file or when it reaches the specified length,
whichever comes first.This function returns the number of bytes written or FALSE on failure.

Using php, how to insert text without overwriting to the beginning of a text file

I have:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
but it overwrites the beginning of the file. How do I make it insert?
I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it?
To insert text without over-writing the beginning of the file, you'll have to open it for appending (a+ rather than r+)
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
If you're trying to write to the start of the file, you'll have to read in the file contents (see file_get_contents) first, then write your new string followed by file contents to the output file.
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
The above approach will work with small files, but you may run into memory limits trying to read a large file in using file_get_conents. In this case, consider using rewind($file), which sets the file position indicator for handle to the beginning of the file stream.
Note when using rewind(), not to open the file with the a (or a+) options, as:
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.
A working example for inserting in the middle of a file stream without overwriting, and without having to load the whole thing into a variable/memory:
function finsert($handle, $string, $bufferSize = 16384) {
$insertionPoint = ftell($handle);
// Create a temp file to stream into
$tempPath = tempnam(sys_get_temp_dir(), "file-chainer");
$lastPartHandle = fopen($tempPath, "w+");
// Read in everything from the insertion point and forward
while (!feof($handle)) {
fwrite($lastPartHandle, fread($handle, $bufferSize), $bufferSize);
}
// Rewind to the insertion point
fseek($handle, $insertionPoint);
// Rewind the temporary stream
rewind($lastPartHandle);
// Write back everything starting with the string to insert
fwrite($handle, $string);
while (!feof($lastPartHandle)) {
fwrite($handle, fread($lastPartHandle, $bufferSize), $bufferSize);
}
// Close the last part handle and delete it
fclose($lastPartHandle);
unlink($tempPath);
// Re-set pointer
fseek($handle, $insertionPoint + strlen($string));
}
$handle = fopen("file.txt", "w+");
fwrite($handle, "foobar");
rewind($handle);
finsert($handle, "baz");
// File stream is now: bazfoobar
Composer lib for it can be found here
You get the same opening the file for appending
<?php
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
If you want to put your text at the beginning of the file, you'd have to read the file contents first like:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
$existingText = file_get_contents($file);
fwrite($file, $existingText . $_POST["lastname"]."\n");
}
fclose($file);
?>

Categories