Hello stackoverflow I was wondering if it is possible to get a simple pagination thingy with this little script? is it possible to get an example? this script takes all csv files in a folder and shows it on a webpage. The only problem is if the csv has 2000 records each csv then the page crashes. can I like show each csv file on a seperate page?
<?php
$arrFiles = glob("../Csv_folder/EMCY_GEN/*.csv");
$arrSortedFiles = array();
foreach($arrFiles as $strFileName) {
$arrSortedFiles[$strFileName] = filemtime($strFileName);
}
arsort($arrSortedFiles);
foreach(array_keys($arrSortedFiles) as $strFileName)
{
$file_handle = fopen($strFileName, "r");
echo "<th><font size='3pt'>".date ("F d Y H:i:s.", filemtime($strFileName))."</td></tr></font></th>";
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
echo '<tr><td>' . $line_of_text[0] . '</td><td>' . $line_of_text[1] . '</td><td>' . $line_of_text[2] . '</td><td>' . $line_of_text[3] . '</td><td>' . $line_of_text[4] . '</td></tr>' ;
}
fclose($file_handle);
}
?>
You want to not have a loop printing out the contents of each CSV. Have an index page that displays the files then link to another page that dynamically loads the CSV.
$arrFiles = glob("../Csv_folder/EMCY_GEN/*.csv");
$leg = count($arrFiles);
while($num < $leg){echo $arrFiles[$num]; $num = $num + 1};
Related
I have the following attempt at my function, but it's just printing out everything in the contacts.txt file on one line...
function contactsTable(){
$file = fopen("contacts.txt", "r") or die("Unable to open file!");
echo "<tr><th>";
while (!feof($file)){
echo "<tr><th>";
$data = fgets($file);
echo "<tr><td>" . str_replace(',','</td><td>',$data) . '</td></tr>';
}
echo "<tr><th>";
echo '</table>';
fclose($file);
}
contacts.txt example like this;
Row 1 is headers ---> [value1, value2, value3, value4]
Row 2 is data ---> [value5, value6, value7, value8]
Is it possible to change my function so that Row 1 is using <th> tags so they are formatted as headers and the rest of the rows go into <td> tags for table data? I've tried to amend the logic but can't seem to get it.
TIA
Here is your contactsTable() function that prints the first contacts.txt line as table header and some basic HTML formatting for easy reading/debugging.
function contactsTable() {
$file = fopen('contacts.txt', 'r') or die('Unable to open file!');
$row = 0;
echo '<table>' . PHP_EOL;
while (!feof($file)) {
$row++;
$data = fgets($file);
if ($row === 1) {
echo '<tr>' . PHP_EOL;
echo '<th>' . str_replace(',', '</th><th>', $data) . '</th>' . PHP_EOL;
echo '</tr>' . PHP_EOL;
} else {
echo '<tr>' . PHP_EOL;
echo '<td>' . str_replace(',', '</td><td>', $data) . '</td>' . PHP_EOL;
echo '</tr>' . PHP_EOL;
}
}
echo '</table>' . PHP_EOL;
fclose($file);
}
can I echo the date or date modified? on top of every csv file? I had an idea on how to do that but that didn't work out.
<?php
$arrFiles = glob("../Csv_folder/*.csv");
$arrSortedFiles = array();
foreach($arrFiles as $strFileName) {
$arrSortedFiles[$strFileName] = filemtime($strFileName);
}
arsort($arrSortedFiles);
foreach(array_keys($arrSortedFiles) as $strFileName)
{
$file_handle = fopen($strFileName, "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
echo '<tr><td>' . $line_of_text[0] . '</td><td>' . $line_of_text[1] . '</td><td>' . $line_of_text[2] . '</td><td>' . $line_of_text[3] . '</td><td>' . $line_of_text[4] . '</td></tr>';
}
fclose($file_handle);
}
?>
Use filemtime
Returns the time the file was last modified, or FALSE on failure. The time is returned as a Unix timestamp, which is suitable for the date() function.
Just before you start echoing out your file, you can do
echo "Time: " . date ("F d Y H:i:s.", filemtime($strFileName));
And add a line break or a table row etc. as required.
Edit
Replace your echo with this one
echo '<tr><td>' . $line_of_text[0] . '</td><td>' . $line_of_text[1] . '</td><td>' . $line_of_text[2] . '</td><td>' . $line_of_text[3] . '</td><td>' . $line_of_text[4] . '</td><td>Time: '.date ("F d Y H:i:s.", filemtime($strFileName)).'</td></tr>';
Edit 2
Replace your loop with this
foreach(array_keys($arrSortedFiles) as $strFileName)
{
$file_handle = fopen($strFileName, "r");
echo "<tr><td colspan='5'></td><td>".date ("F d Y H:i:s.", filemtime($strFileName))."</td></tr>";
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
echo '<tr><td>' . $line_of_text[0] . '</td><td>' . $line_of_text[1] . '</td><td>' . $line_of_text[2] . '</td><td>' . $line_of_text[3] . '</td><td>' . $line_of_text[4] . '</td></tr>';
}
fclose($file_handle);
}
As it stands I am having real trouble figuring out just how to get the functions delete, move/copy, rename into an array via click of an image or text, and then making the function correspond to the correct row in the table and the correct file on the row in the array.
This is a very hard question to word to be honest but the array currently populates a table with files in a folder, file name, size and date modified, I'm trying to add in small images on each row for delete file, rename file ect. so that these images are linked with functions so when pressed it will delete the corresponding file or rename it if that makes sense. anyway the array code is below, and I understand if its difficult to answer just figured I would ask.
Also $cellOptions is the cell im trying to populate it currently just gives me back the logged in user
http://pastebin.com/dkeUAk50
function listFiles($dir)
{
$output = ''; $outRows = ''; $files = array();
if (is_dir($dir)) {
if ($dirHandle = opendir($dir)) {
$files = array_diff(scandir($dir), array('.', '..', '.htaccess'));
$totalSize = (int) 0;
foreach($files as $file) {
$fileTime = #date("d-M-Y", filectime($dir . '/' . $file)) . ' ' . #date("h:i", filemtime($dir . '/' . $file));
$totalSize += filesize($dir . '/' . $file);
$fileSize = #byte_convert(filesize($dir . '/' . $file));
$cellLink = '<td class="list_files_table_file_link">' . $file . '</td>';
$cellTime = '<td>' . $fileTime . '</td>';
$cellOptions = '<td>'. $_SESSION['Username'] .'<td>';
$cellSize = '<td>' . $fileSize . '</td>';
$outRows .= '<tr>' . "\n " . $cellLink . "\n " . $cellTime . "\n " . $cellSize . "\n" . $cellOptions . '</tr>' . "\n";
}
closedir($dirHandle);
}
}
$output = '<table class="list_files_table" width="100%" align="center" cellpadding="3" cellspacing="1" border="0">' . "\n";
$output .= '<thead><tr><td><b>Name</b></td><td><b>Date Modified</b></td><td><b>Size</b></td></tr></thead>' . "\n";
$output .= '<tfoot><tr><td colspan="2">' . count($files) . ' files.</td><td>' . #byte_convert($totalSize) . '</td></tr></tfoot>' . "\n";
$output .= '<tbody>' . "\n";
$output .= $outRows;
$output .= '</body>' . "\n";
$output .= '</table>';
return $output;
}
function byte_convert($bytes)
{
$symbol = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$exp = (int) 0;
$converted_value = (int) 0;
if ($bytes > 0) {
$exp = floor(log($bytes)/log(1024));
$converted_value = ($bytes/pow(1024,floor($exp)));
}
return sprintf('%.2f ' . $symbol[$exp], $converted_value);
}
session_start();
echo listFiles($_SESSION['UserFolder']);
Add an element that contains the following in your loop:
A form that submits to the same page with a method of POST
An hidden input element that contains the filename
A submit button to submit the form.
This is what it would look like:
$cellSize = '<td>' . $fileSize . '</td>';
$deleteCell = '<td><form action="/" method="POST"><input type="hidden" value="'.$file.'" ame="fileToDelete"/><input type="submit" value="Delete" name="deleteButton"/></form></td>';
Create a function to delete:
function deleteFile($dir, $fileToDelete){
if (is_dir($dir)) {
if ($dirHandle = opendir($dir)) {
$files = array_diff(scandir($dir), array('.', '..', '.htaccess'));
if($files){
foreach($files as $file){
if($file === $fileToDelete) {
unlink($fileToDelete);
$output = 'Successfully deleted file: '.$fileToDelete;
}
}
}
}
}
return $output;
}
Check if a form was submitted, and if so, delete the file in question:
if(isset($_POST)){
echo deleteFile($_SESSION['UserFolder'], $_POST['fileToDelete']);
}
I use php in order to save all informations concerning my user (where do they navigated and at which time).
So I use the following code for saving informations:
<?php
function iif($condition, $true, $false ) {
return ($condition ? $true : $false);
}
$ipaddress = $_SESSION['login'];
$page = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['PHP_SELF']}";
$page .= iif(!empty($_SERVER['QUERY_STRING']), "?{$_SERVER['QUERY_STRING']}", "");
$referrer = $monUrl = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$datetime = mktime();
$useragent = $_SERVER['HTTP_USER_AGENT'];
$remotehost = #getHostByAddr($ipaddress);
// Create log line
$logline = $ipaddress . '|' . $referrer . '|' . $datetime . '|' . $useragent . '|' . $remotehost . '|' . $page . "\n";
// Write to log file:
$logfile = 'logfile.txt';
$path='log/'.$_SESSION['login'].'/'.$logfile;
if(!file_exists($path)) {
mkdir('log');
mkdir('log/'.$_SESSION['login']);
$f = fopen('log/'.$_SESSION['login'].'/'.$logfile, "x+");
// fermeture
fclose($f);
}
// Open the log file in "Append" mode
if (!$handle = fopen($path, 'a+')) {
die("Failed to open log file");
}
// Write $logline to our logfile.
if (fwrite($handle, $logline) === FALSE) {
die("Failed to write to log file");
}
fclose($handle);
?>
And I use the following code below to display it:
<?php
$path= 'log/'.$data['login'].'/logfile.txt';
$logfile = $path;
if (file_exists($logfile)) {
$handle = fopen($logfile, "r");
$log = fread($handle, filesize($logfile));
fclose($handle);
} else {
die ("Le fichier de Log n'existe pas!");
}
// Seperate each logline
$log = explode("\n", trim($log));
//After that it may be useful to get each part of each logline in a separate variable. This can be done //by looping through each logline, and using explode again:
// Seperate each part in each logline
for ($i = 0; $i < count($log); $i++) {
$log[$i] = trim($log[$i]);
$log[$i] = explode('|', $log[$i]);
}
// Show a table of the logfile
echo '<table id="box-table-a">';
echo '<th scope="col">Agent</th>';
echo '<th scope="col">Referrer</th>';
echo '<th scope="col">Date</th>';
echo '<th scope="col">Useragent</th>';
echo '<th scope="col">Remote Host</th>';
foreach ($log as $logline) {
echo '<tr>';
echo '<td><a href="index.php?p=voir_fiche_employee&id='.$_GET['id'].'"/>' . $logline['0'] . '</a></td>';
echo '<td><a href="'.urldecode($logline['1']).'"/>'. urldecode($logline['1']) . '</a></td>';
echo '<td>' . date('d-m-Y h:i:s', $logline['2']) . '</td>';
echo '<td>' . $logline['3'] . '</td>';
echo '<td>' . $logline['4'] . '</td>';
echo '</tr>';
}
echo '</table>';
?>
The trouble I met is that I really do not know how to sort informations from this file.
In fact on the top of the page I have a form in order to choose between the dates. I wsould like to display all informations from this logfile between those dates but I really do not know how to do.
At the beginning I was planning to save all in the databse, but somebody told me that it would have been too much for the databse, so I decided to save all in a txt on the server.
Does anyone know if it is possible to sort informations from txt file?
By default I would like to display informations of the logfile for the date of the day, and If I want I can choose an other dates or an interval of dates.
If possible to store data into a database. It is easy to sort in database. Reading data into a text file is more time consuming and difficult to sort.
I have a CSV file that contains four data fields:
date;place;time;event
First one is date, as you can see.
I need to read CSV line by line, compare DATE with current date and output ten lines starting from the line with current date.
I tried this code:
<?php
date_default_timezone_set("Europe/Zagreb");
$today = date('Ymd');
$file_handle = fopen("data.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024,";");
if ($line_of_text[0] >= $today) echo $line_of_text[0] . "-" . $line_of_text[1]. "-" . $line_of_text[2] . "-" . $line_of_text[3] . "<BR>";
}
fclose($file_handle);
?>
But I can't break that after 10 lines. I used YYYYMMDD date format in CSV and code so basically I work with numbers, not dates.
Try this:
date_default_timezone_set("Europe/Zagreb");
$today = date('Ymd');
$file_handle = fopen("data.csv", "r");
$counter = 0;
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024,";");
if ($line_of_text[0] >= $today) {
echo $line_of_text[0] . "-" . $line_of_text[1]. "-"
. $line_of_text[2] . "-" . $line_of_text[3] . "<br />";
$counter++;
}
if ($counter == 10) break;
}
fclose($file_handle);
if condition should be fixed by adding strtotime before you can compare:
if (strtotime($line_of_text[0]) >= strtorime($today))
Your corrected piece of code will be:
$counter = 0;
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024,";");
if (strtotime($line_of_text[0]) >= strtotime($today)) {
echo $line_of_text[0] . "-" . $line_of_text[1]. "-" . $line_of_text[2]
. "-" . $line_of_text[3] . "<BR>";
$counter++;
}
if ($counter == 10) break;
}