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.
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);
}
I am trying to create a cron job in php that deletes disabled users found in a csv file and logs the deleted users to a txt file. Everything works except only the last user in the csv file is deleted. Here is what I have so far:
class purgeInactive extends JApplicationCli
{
public function doExecute()
{
$file = '../tmp/purge_user.csv';
$contents = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$csvRows = array_map('str_getcsv', $contents);
$log = ('../log/purged_users.txt');
$today = date('F j, Y, g:ia');
$row = 1;
if (($handle = fopen("../tmp/purge_user.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
file_put_contents($log, PHP_EOL . 'Removed Disabled User(s): ' . $data[$c] . PHP_EOL . '-' . $today . PHP_EOL, FILE_APPEND);
$disUsers = implode(',', $data);
echo ', ' . $disUsers ; // to test $disUsers output
} // end for statement
} // end while statment
} // end if statement
fclose($handle);
$db = JFactory::getDbo();
$user = JFactory::getUser();
$query = $db->getQuery(true);
$userArray = var_export($disUsers,true);
echo PHP_EOL.'This is to test the output of $userArray'.$userArray;
$query
->select($db->quoteName(array('id')))
->from($db->quoteName('#__users'))
//->delete ($db->quoteName('#__users'))
//->where(array($db->quoteName('username') . ' IN(' . $userArray) . ')');
->where(array($db->quoteName('username') . ' = ' . $userArray));
//->where($deleteReq);
$db->setQuery($query);
//$result = $db->execute();
$result = $db->query();
}
}
JApplicationCli::getInstance('purgeInactive')->execute();
Any suggestions on how to run each user in the csv file individually? I am about brain dead on this as I have been working on it too long.
Note: I am running Joomla that uses ldap and I use echo for $userArray to check results.
I think instead of ...
->where(array($db->quoteName('username') . ' = ' . $userArray));
You just want
->where(array($db->quoteName('username') . ' IN(' . $userArray) . ')');
That's assuming you want to delete all the rows whose usernames are in $userArray.
If the values in $userArray aren't necessarily SQL-safe, you might also want to do this first:
$userArray = array_map('mysql_real_escape_string', $userArray);
Each row of your csv is iterating this line: $disUsers = implode(',', $data);
This means that all usernames in that row will be saved to $disUsers, then the next iteration will overwrite the old data with the new row's usernames -- this is why only the final row of data is making it down to your delete query.
$data[$c] is what should be pushed into a $disUsers array like this: $disUsers[] = $data[$c];
In your query, you'll need to quote-wrap each array value; this will do that job:
->where($db->qn('username') . ' IN (' . implode(',', array_map(function($username)use($db) {return $db->q($username);}, $disUsers)) . ')')
Here is a post of mine where I discuss writing Joomla queries with IN: https://joomla.stackexchange.com/a/22898/12352
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};
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 am very new to PHP and am trying to create a basic form. This form has a drop-down list whereby the product is displayed. What I would like for it to do is to display the price, and the city that this product is from.
I have a text file which acts as the data source, and is formatted in this way:
product | price | city
Code:
<?php
$file = 'Product1.txt';
$handle = #fopen($file, 'r');
if ($handle) {
while (!feof($handle)) {
$line = fgets($handle, 4096);
$item = explode('|', $line);
echo '<option value="' . $item[0] . '">' . $item[0]. ' '.$item[1]. ' '.$item[2].'</option>' . "\n";
}
fclose($handle);
}
?>
Overall, when I populate my dropdown list, it works fine, and I've extended the page with the hopes of getting more. However, when I try to echo $item[1] or $item[2] at the end of the page, I get nothing.
Can someone show me what I am missing? I've tried looking for tutorials on this matter but to no avail. Thank you.
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $_POST['D1'];
echo "<br>";
echo $quantity;
?>
You are not getting anything because $item not in scope
put $itemData = array(); at the top after $handle
$file = 'Product1.txt';
$handle = #fopen($file, 'r');
$itemData = array();
if ($handle) {
while (!feof($handle)) {
$itemData[] = explode('|', $line);
$line = fgets($handle, 4096);
$item = explode('|', $line);
echo '<option value="' . $item[0] . '">' . $item[0]. ' '.$item[1]. ' '.$item[2].'</option>' . "\n";
}
fclose($handle);
}
its should work
$data = explode(" | ", file_get_contents("data.txt"));