Clear fwrite log files in php - php

Is there a way I can have 5 logs files cleared on a frontend, without emptying the file data manually or deleting them?
I want to add a button or such on a page that will empty them if possible.

You can not clear a file on your server on frontend. You can push a button on frontend and call a backend script.
w+ : Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
$handle = fopen ("/path/to/file.txt", "w+");
fclose($handle);

clearlogs.php
<?php
$logfiles = array(
"1-LOG.txt",
"2-LOG.txt",
"3-LOG.txt",
"4-LOG.txt",
"5-LOG.txt",
);
foreach ($logfiles as $logfile){
$clearlogs = #fopen("$logfile","r+");
#ftruncate($clearlogs, 0);
}
header("Location:logs.php");
?>
logs.php
<form action="clearlogs.php" method="POST">
LOGS <input type="submit" value="Clear Logs" />
</form>

Related

php - add to end of a string and save to txt file

OK guys, this is my first post. I have searched all over and spent countless hours and I am still stuck so I asking for help with this relatively easy PHP module.
basically in a nutshell, what I want to do is upload a text file into an uploads directory, and have PHP process the file and perform a string function that will add HTML BREAK TAGS to the end of each line and then save this output to file. I have learned how to echo the formatted text into the browser and it appears the way it should as formatted html, but it doesn't work to write back to the file.
here is the code;
<?php
$form = <<<EOD
<form enctype="multipart/form-data" action="" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000000" />
Choose an file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
EOD;
echo $form;
$target_path = "uploads/"; //SETS THE UPLOAD DIRECTORY
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); // GETS FILEPATH OF UPLOAD FOR OPENING/PROCESSING
$uploadfile = basename($_FILES['uploadedfile']['name']); //GETS FILENAME OF THE UPLOADED FILE IN CASE ITS NEEDED.
//PROCESSING - MOVES TMP FILE INTO TARGET DIRECTORY. NEED STRING FUNCTIONS APPLIED TO ADD <BR/> AT END OF EACH LINE.
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
$file = fopen($target_path, "r");
while(!feof($file))
{
$line = fgets($file); //READS EACH LINE
// STRING PROCESSING PART -- SHOULD I USE str_replace, substr_replace, nl2br, or str_pad ??
..........CODE GOES HERE............PLEASE HELP ME CHOOSE THE RIGHT CODING HERE...THANKS!!! SORRY FOR THE PSEUDOCODE!
/* EXAMPLE SCRIPT:
$line2 = str_replace("\n", "<br />\n", $line);
// THIS WORKS -- GREAT FOR OUTPUTTING FORMATTED HTML INTO BROWSER
echo $line2;
// FOR NICE VIEWING BUT STILL CANNOT GET FORMATTED
// HTML TO SAVE TO FILE USING FWRITE() ...
*/
fwrite($file, $newstr);
} //CLOSES WHILE
fclose($file); //CLOSES FILE HANDLE
} //CLOSES IF
?>
too many late nights, open windows, and troubleshooting steps to make my brain want to explode! When I know one of you guys can knock this out in 2 minutes!!!
I notice I keep getting this error log:
PHP Warning: Module 'mailparse' already loaded in Unknown on line 0
There are a couple of problems with what you're doing currently. First, you've opened the file for reading only, but even if you change that, you won't be able to just replace a line with a longer line in the same file. In order for your current approach to work, you'll need to open a second file for writing, and add the modified lines into the second file as you go. But as long as the files aren't very large, you should be able to create the modified file more simply:
file_put_contents($output_file, nl2br(file_get_contents($input_file)));
Incidentally, the mailparse warning does not appear to be related to the code you've posted here.

edit my centos 6 network config file using PHP code but after network restart i get an error

I am using a simple file operation on the PHP in order to edit the config file for network interface on CentOS 6.7(/etc/sysconfig/network-scripts/ifcfg-eth0
), after change in any value and save into the config file and try to restart the network interface i get this error:
does not seem to be present, delaying initialization.
[FAILED]
my PHP code is this:
<?php
// configuration
$file = '/etc/sysconfig/network-scripts/ifcfg-eth0';
// check if form has been submitted
if (isset($_POST['text']))
{
// save the text contents
file_put_contents($file, $_POST['text']);
// redirect to form again
header('Location: network.php');
exit();
}
// read the textfile
$text = file_get_contents($file);
?>
<!-- HTML form -->
<form action="" method="post">
<textarea style="width:50%; height:50%;" name="text"><?php echo htmlspecialchars($text) ?></textarea>
<input type="submit" />
<input type="reset" />
</form>
i need manually called the network script by command setup and do a modification in the device setting and save then i will be able to restart the network interface. appreciate if anyone help me why this issue happen while if i open the config file and edit it manually it wouldn't cause this issue.
It's most likely that the user name the server runs as (by default apache on most Red Hat-based distributions) doesn't have permission to write to/etc/sysconfig/network-scripts/ifcfg-eth0.
You should check the return values of:
file_put_contents($file, $_POST['text']);
From http://php.net/manual/en/function.file-put-contents.php
This function returns the number of bytes that were written to the file, or FALSE on failure.
I presume this script will only be run by your or trusted colleagues given that there's no validation of the user input. Indentation would also make the PHP code more readable.

Form empty itself without doing anything

Earlier today I asked a question about what I was doing wrong, I got this working but now I'm running into another problem with this script.
Previously
The code gave a warning(), that's fixed now. You can read the post Here
What's the problem?
The code automatically empty itself. When you refresh the page where the script is the text file is empty. I have no idea why...
This is the code
<?php
$fn = "file.txt";
$file = fopen($fn, "w+");
$size = filesize($fn);
if($_POST['addition']) fwrite($file, $_POST['addition']);
fclose($file);
?>
<form action="<?=$PHP_SELF?>" method="post">
<input type="text" name="addition" value="<?php echo file_get_contents('file.txt');?>"/>
<input type="submit"/>
</form>
I use this script to display a youtube video on my website, so I got to update it often.
You can find a working example of the script with this link: http://beta.martijnmelchers.nl/private/Test/test.php
What have i tried?
I didn't try many because I couldn't find a solution for this on the internet and also not in the code.
Please help me again! Thanks in advance!
According to the manual with the w+ option:
Open for reading and writing; place the file pointer at the beginning
of the file and truncate the file to zero length. If the file does not
exist, attempt to create it.
It looks like you want to replace all contents when a post is made, so the easiest solution is to put all file-handling calls in the POST condition:
// To avoid warnings, this is better.
// You can add your original condition after it if you need it.
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$file = fopen($fn, "w+");
// not sure why you need this...
// $size = filesize($fn);
fwrite($file, $_POST['addition']);
fclose($file);
}

Text input to file upload

I have a form:
<form method="POST" action="">
<textarea id="input_text" name="input_text"></textarea>
<input type="submit" name="decrypt" value="sm">
</form>
now I submit it, php is try to write $_POST['input_text'] to a file then do another action, after complete action, php 'll delete the file created.
<?php
$Path = dirname(__FILE__).'/temp/';
$File_NAME = time().'.txt';
$input_text = stripslashes($_POST['input_text']);
$fp=fopen($Path.$File_NAME,'w');
fwrite($fp,$input_text);
fclose($fp);
//do some curl action with the file, then delete the file
if(file_exists($Path.$File_NAME))
unlink($Path.$File_NAME);
but if the text too strong, user submit the form, then they abort the page, so the file doesn't delete.
I want to direct change the $_POST['input_text'] to type='file', but user also can use it such as a textarea. so php don't need to delete the file because it is a tmp file.
As per your Edit to the question, the possible solution is to first check the $_POST['input_text'] for length before even opening the file. If the text is too long, show an error message.
I don't think that file is even required in that case.
OLD ANSWER:
Fetching the $_POST['input_text], you can :
$txt = $_POST['input_text'];
$file = fopen("file.txt", "w+"); //w+ indicates read + write
fwrite($file,$txt); //to ride the 'input_txt'
Then perform the actions you want and finally delete the file if required using:
fclose($file);
delete("file.txt");
But make sure to grant the PHP page the permissions to Read/Write first.

Open a file in a new browser window after having written it (with fopen)

I'm writing a simple order system where several numbers (filled in inside a form) are written to another .php file (may be .html also), using the fopen function. This works fine, but after writing to the file, I want the browser to actually open that written file, preferably in a new browser window. This way my client can use this to print, use as an invoice, etc.
Now I'm still a rookie on php grounds and am not experienced with the use of fopen. But everywhere I look for tutorials etc., it's said that fopen opens (or writes of course) a file, but it doesn't for as far as I've experienced. It just seems to allow access to the specified file to write and read, rather to actually display the newly written page.
To avoid any confusion: I do NOT want to open links like other questions here on SO state.
My code:
<form action="" method="post">
<input type="text" id="amountTuna" name="numberTuna" value="0"/>
<input type="text" id="amountCheese" name="numberCheese" value="0"/>
<input name="send" id="send" type="submit" value="Post order" />
</form>
<?php
if (array_key_exists('send', $_POST)) {
$order = "order.php";
$fh = fopen($order, 'w') or die("can't open file");//file handler
fwrite($fh, "Tuna sandwiches: " . stripslashes($_POST['numberTuna']));
fwrite($fh, "Cheese sandwiches: " . stripslashes($_POST['numberCheese']));
$fh = fopen($factuur, 'r');
$fileip = fread($fh, filesize($factuur));
fclose($fh);
}
?>
Trying different fopen parameters such as 'w','r','r+' etc doesn't seem to make any difference. Removing fclose($fh) doesn't seem to make any difference either.
Use JS script to open new window. For example right after fclose($fh):
echo "<script>window.open($order, '_blank'); window.focus();</script>";
Storing things in a database would likely be a lot easier.
That said, using fopen is to open the file itself, opening the written file in a new browser window will require some client-side scripting (i.e. Javascript) to load the newly created file.
Google Javascript window.open().
Tom
Since you just want to write to a printable page .. have you tried file_put_contents
Example
if (isset($_POST['send'])) {
$file = "test.html";
$data = "Tuna sandwiches: " . stripslashes($_POST['numberTuna']) . "<br>";
$data .= "Cheese sandwiches: " . stripslashes($_POST['numberCheese']) . "<br>";
touch($file);
file_put_contents($file, $data);
}

Categories