PHP How to generate new file txt per day with data - php

I've created data collection for a specific txt file. I need the script to separate records per days.
For example: today is 100 data and i need have a log16Jan.txt file, tomorrow we have 52 data and i need have a log17Jan.txt file?
How i can do that?
<?php
$name = $_POST['name'];
$tekst = "Name: $namee \r\n";
$uchwyt = fopen("log.txt", "a");
fwrite($uchwyt, $tekst);
fclose($uchwyt);
header("Location: http://#/complete.html");
?>

You can get the date using the date() function and add it to the file name, like this:
$name = $_POST['name'];
$tekst = "Name: $name \r\n";
// Adding today's date to the log file
$uchwyt = fopen("log".date("dM").".txt", "a");
fwrite($uchwyt, $tekst);
fclose($uchwyt);
header("Location: http://#/complete.html");

You could use the date() function.
And since you are creating log files you should consider using a log file name that will sort natively in date order in a directory listing. This will make it easier to find a specific log file in a large listing of files. It will also give you more log file cleanup/removal options.
For example:
// 2018-01-16-log.txt
$logFilename = date("Y-m-d") . "-log.txt";
$uchwyt = fopen($logFilename, "a");
UPDATE: per your request about adding a line number before each log line, there are many ways to do this and some depend on your server environment (Linux/Windows). You could read each line from the log and keep a counter. Or you could use a server utility, like Linux wc (Word Count). Here's one way to do it:
<?php
// 2018-01-16-log.txt
$logFilename = date("Y-m-d") . ".log";
echo "Log file = $logFilename\n";
if (! file_exists($logFilename)) {
$count = 0;
} else {
// use Linux wc utility
$count = system("wc -l < $logFilename");
$count = trim($count);
}
echo "Lines = '$count'\n";
$name = $_POST['name'];
if (! $name) {
$name = "NONE";
}
$tekst = "$count. Name: $name \n";
$uchwyt = fopen($logFilename, "a");
fwrite($uchwyt, $tekst);
fclose($uchwyt);
?>

Related

How to display a different message read from a file every day of the week in php?

I have a php function that reads a line (random message) from a file and displays it on my web page. It displays a new message every time I click refresh, but I want it to display the message for a day (it should change at midnight). Is it possible to do it with another function, implying my database? Or with a JS function?
EDIT
This is the function (not my code):
function loadMessagesFromFile()
{
$path = ROOT_PATH. '/messages.txt';
$file = fopen($path,"r");
$messages = array();
while($data = fgets($file))
{
$messages[] = $data;
}
fclose($file);
return $messages;
}
This is how I use it to display the message:
$messages_from_file = loadMessagesFromFile();
$key = array_rand($messages_from_file);
$full_text = $messages_from_file[$key];
LATER EDIT
I found the answer here: <https://stackoverflow.com/questions/6815614/generating-word-of-the-day-via-php-random-number#:~:text=Just%20set%20the%20current%20date,same%20number%20for%20one%20Day.>
You have multiple possibilities:
Create a file with only one line every day taken from the other file
Create a cron who will be executed ad midnight who will get a random message and set it in database or cache.
If you want a different message per people but persist one day, you can use the local storage of the visitor to store the message with the current date and if the date stored is different from the current date, you change it.
get total lines from your file
Use a database or file and store a random number daily.
Use that number to read a random message from the file.
Use cron to update random numbers at midnight in your database or file.
So, for 24 hours the same message will be displayed.
function getRandomNo(): int {
$path = ROOT_PATH. '/randomno.txt';
$file = fopen($path,"r");
$data = fread($file,100);
fclose($file);
if($data) {
$parts = explode('=',$data);
if($parts[0] != date("Y-m-d")) {
$randomNo = rand(0,100);
overWrite($randomNo);
} else {
$randomNo = $parts[1];
}
} else {
$randomNo = rand(0,100);
overWrite($randomNo);
}
return $randomNo;
}
function overWrite(int $randomNo): void {
$path = ROOT_PATH. '/randomno.txt';
$file = fopen($path,"w+");
$data = date("Y-m-d").'='.$randomNo;
fwrite($file, $data);
fclose($file);
}
$messages_from_file = loadMessagesFromFile();
$key = getRandomNo();
$full_text = $messages_from_file[$key];

Chat message displays in opposite order

I am developing a website where users can type message in a div.
This is the format of the message which will be saved in the file post_archieve.php.
The problem is that the most recent message is on the bottom, and the oldest message is on the top of the div which is the opposite of what I intended.
How can I get the messages to appear in the correct order?
$handle = fopen("post_archieve.php", "a") or die("error"); //deschid cu a ca sa pastreze continutul
$mesaj = $_POST['message'];
$timestamp = time()+ 60*60;
$Time = gmdate("d-m-Y H:i:s", $timestamp);
$postare = '<p class="paragraf">'.$Time."<br>".$username."\r\n"." : ".$mesaj.'</p>';
fwrite($handle, $postare);
fclose($handle);
Append mode adds what you write to the end of the file. If you want to insert at the beginning, you need to read the entire file into a variable, concatenate that to the new data, and rewrite the file.
$mesaj = $_POST['message'];
$timestamp = time()+ 60*60;
$Time = gmdate("d-m-Y H:i:s", $timestamp);
$postare = '<p class="paragraf">'.$Time."<br>".$username."\r\n"." : ".$mesaj.'</p>';
$contents = file_get_contents("post_archieve.php");
$contents = $postare . $contents;
file_put_contents("post_archieve.php", $contents);
Note also that your code is wide open to Cross-Site Scripting attacks. You should encode the message with:
$mesaj = htmlspecialchars($_POST['message']);

Contact form with unique file name

I want to create php file for my contact form but whenever they submit I want a different file name.txt.
This is the code. Whenever someone else submits I lose the old one.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST ['message'];
$file = fopen('contactform.txt', "w+");
$content = $name. PHP_EOL .$email. PHP_EOL .$message;
header('Location: http://localhost:8080/site-edits/contact.php');
fwrite($file , $content);
fclose($file);
?>
Like Barry said, you could append a timestamp to your name.
PHP also has a function tempnam available that generates a unique filename:
$file = fopen(tempnam(".", "contactform.txt"), "w+");
One thing you can do is add the current date to the file name:
$file = fopen('contactform-'.date('YmdHis').'.txt', "w");
Alternatively, you can append to the file instead of writing over it.
$file = fopen('contactform.txt', "a");
$content = $name. PHP_EOL .$email. PHP_EOL .$message .PHP_EOL.PHP_EOL;
Most people use a database (for example MySQL) for this. I'd suggest learning about how to use databases when you get the time.
You can either create new file with different name any time user submits the form or append text in existed file usin 'a' rather 'w+'
Like:
$file = fopen('contactform.txt', 'a');
For more go to php file handling

How do i split a 6 gb CSV file into chunks using php

I'm a beginner level developer learning php.The task that i need to do is upload a 6gb CSV file which contains data, into the data base.I need to access the data i.e reading the file through controller.php file and then splitting that huge CSV file into 10,000 row output CSV files and writing data into those output CSV files. I have been through this task a week already and dint figure it out yet.Would you guys please help me in solving this issue.
<?php
namespace App\Http\Controllers;
use Illuminate\Queue\SerializesModels;
use App\User;
use DateTime;
use Illuminate\Http\Request;
use Storage;
use Validator;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Queue;
use App\model;
class Name extends Controller
{
public function Post(Request $request)
{
if($request->hasfile('upload')){
ini_set('auto_detect_line_endings', TRUE);
$main_input = $request->file('upload');
$main_output = 'output';
$filesize = 10000;
$input = fopen($main_input,'r');
$rowcount = 0;
$filecount = 1;
$output = '';
// echo "here1";
while(!feof($input)){
if(($rowcount % $filesize) == 0){
if($rowcount>0) {
fclose($output);
}
$output = fopen(storage_path(). "/tmp/".$main_output.$filecount++ . '.csv','w');
}
$data = fgetcsv($input);
print_r($data);
if($data) {
fputcsv($output, $data);
}
$rowcount++;
}
fclose($output);
}
}
}
Maybe it's because you are creating a new $output file handler for each iteration.
I've made some adjustments, so that we only create a file when the rowCount = 0 and close it when the fileSize is reached. Also the rowCount has to be reset to 0 each time we close the file.
public function Post(Request $request)
{
if($request->hasfile('upload')){
ini_set('auto_detect_line_endings', TRUE);
$main_input = $request->file('upload');
$main_output = 'output';
$filesize = 10000;
$input = fopen($main_input,'r');
$rowcount = 0;
$filecount = 1;
$output = '';
// echo "here1";
while(!feof($input)){
if ($rowCount == 0) {
$output = fopen('php://output', storage_path(). "/tmp/".$main_output.$filecount++ . '.csv','w');
}
if(($rowcount % $filesize) == 0){
if($rowcount>0) {
fclose($output);
$rowCount = 0;
continue;
}
}
$data = fgetcsv($input);
print_r($data);
if($data) {
fputcsv($output, $data);
}
$rowcount++;
}
fclose($output);
}
}
Here is working example of splitting CSV file by the amount of lines (defined by$numberOfLines). Just set your path in $filePath and run the script in shell for example:
php -f convert.php
script code:
convert.php
<?php
$filePath = 'data.csv';
$numberOfLines = 10000;
$file = new SplFileObject($filePath);
//get header of the csv
$header = $file->fgets();
$outputBuffer = '';
$outputFileNamePrefix = 'datasplit-';
$readLinesCount = 1;
$readlLinesTotalCount = 1;
$suffix=0;
$outputBuffer .= $header;
while ($currentLine = $file->fgets()) {
$outputBuffer .= $currentLine;
$readLinesCount++;
$readlLinesTotalCount++;
if ($readLinesCount >= $numberOfLines) {
$outputFilename = $outputFileNamePrefix . $suffix . '.csv';
file_put_contents($outputFilename, $outputBuffer);
echo 'Wrote ' . $readLinesCount . ' lines to: ' . $outputFilename . PHP_EOL;
$outputBuffer = $header;
$readLinesCount = 0;
$suffix++;
}
}
//write remainings of output buffer if it is not empty
if ($outputBuffer !== $header) {
$outputFilename = $outputFileNamePrefix . $suffix . '.csv';
file_put_contents($outputFilename, $outputBuffer);
echo 'Wrote (last time)' . $readLinesCount . ' lines to: ' . $outputFilename . PHP_EOL;
$outputBuffer = '';
$readLinesCount = 0;
}
you will not be able to convert such amount of data in one php execution if it is run form web because of the maximum execution time of php scripts that is usually between 30-60sec and there is a reason for that - don't event try to extend it to some huge number. If you want your script to run even for hours you need to call it from command line, but you also can call it similar way from another script (for example the controller you have)
You do that this way:
exec('php -f convert.php');
and that's it.
The controller you have will not be able to tell if the whole data was converted because before that happens it will be terminated. What you can do is to write your own code in convert.php that updates some field in database and other controller in your application can read that and print to the user the progress of the runnig convert.php.
The other approach is to crate job/jobs that you can put in the queue and can be run by job manager process with workers that can take care for the conversion but I think that would be an overkill for your need.
Keep in mind that if you split something and on different location join you may have problem of getting something wrong in that process the method that would assure you that you split, transferred, joined your data successfully is to calculate HASH ie SHA-1 of the whole 6GB file before split, send that HASH to destination where all small parts of data needs to be combined, combine them into one 6GB file, calculate HASH of that file and compare with the one that was send. Keep in mind that each of small parts of your data after splitting has their own header to be CSV file easy to interpret (import), where in the original file you have only one header row.

tracking user logins per day

hey guys i'm running a script on my site:
as a user logs into my website i write this days date into a text file so i can know at witch days the user was active on my website.
the thing is, if a user lets say didn't log out from the site for 2 days or more how can i check if he was on the site on those days? can some one give me a good suggestion?
here is the code i'm running as part of my login, just before i register the session: (by the way ill be glad to hear if there's a better way to do it?)
$log_file_name = "logfile.txt";
$log_file_path = "log_files/$id/$log_file_name";
if(file_exists($log_file_path)){
$not = "";
$todaydate = date('d,m,Y');
$today = "$todaydate;";
$strlength = strlen($today);
$file_contents = file_get_contents($log_file_path);
$file_contents_arry = explode(";",$file_contents);
if(!in_array($todaydate,$file_contents_arry)){
$append = fopen($log_file_path, 'a');
$write = fwrite($append,$today); //writes our string to our file.
$close = fclose($append); //closes our file
}
else if(in_array($todaytodaydate,$file_contents_arry)){}
}
else{
mkdir("log_files/$id", 0700);
$todaydate = date('d,m,Y');
$today = "$todaydate;";
$strlength = strlen($today);
$create = fopen($log_file_path, "w");
$write = fwrite($create, $today, $strlength); //writes our string to our file.
$close = fclose($create); //closes our file
}
This isn't something for a text-file to handle (as you will end up with hundreds of text-files), This should be handled with a database, and a set of Update Queries.

Categories