Show selected text file in html page after submit button press - php

Good Day Everyone
Ok, so I have done as much as I understand and need some direction and help. Currently i'm very new to html/php so please bear with me. The plan is to list the text files from a Dir in a dropdown list, this I have done, now I would like to display the text file in the same page in a table upon submit button press. This is what I have so far, any input welcome as I am still learning!
The bash script is just a grep function to grab specific lines from the original file and copy it to /tmp.
Thanks Again
<html>
<head>
<title>Data Request</title>
</head>
<body>
<h1 align="center">Dispatch Report</h1>
<h2 align="center">Wrong Arrives Report</h2>
<table align="center" border="2">
<tr>
<td>Select Shift<br>
<form name="shiftfrm" id="shiftfrm">
<select name="shiftlist" id="shiftlist">
<option value="" selected="selected">--------</option>
<?php
$dir = opendir ("/var/www/files/");
while (false !== ($file = readdir($dir))) {
if (strpos($file, '.txt',1)) {
echo '<option value="' . $file . '">' . $file . '</option>';
}
}
?>
</select>
<input type="submit" id="submit" value="Submit"/>
<?php
if( ($handle = fopen( '/tmp/sh130418n.txt', 'r' )) !== false )
{
$output = '<table align="center" width="" border="2">';
while( ($data = fgetcsv( $handle )) !== false )
{
$output .= '<tr>';
foreach( $data as $value )
{
$output .= sprintf( '<td>%s</td>', $value );
}
fclose( $handle );
$output .= '</table>';
}
echo $output;
?>
</td></tr>
</table>
<?php
$output = exec('/var/www/cgi-bin/manualexceptget.sh');
echo "<pre>$output</pre>";
?>
</body>
</html>

assume <form method="post" action="">. Augment your file reading code:
if(!empty($_POST['shiftlist'])) {
$file = 'files/'.$_POST['shiftlist'];
if(file_exists($file)) {
if( ($handle = fopen( $file, 'r' )) !== false )
{
$output = '<table align="center" width="" border="2">';
while( ($data = fgetcsv( $handle )) !== false )
{
$output .= '<tr>';
foreach( $data as $value )
{
$output .= '<td>'.$value.'</td>';
}
$output .= '</table>';
}
echo $output;
fclose( $handle );
}
}
}
Edit: Fixed the isset() issue stated below. Changed some code, $handle was closed before reading was finished.
Edit2: I just put this in editor and saw many html tags, that were not placed properly (e.g. form not closed). Working sample at pastebin (tested on xampp)

Try Like this for (.txt) files..
<html>
<head>
<title>Data Request</title>
</head>
<body>
<h1 align="center">Dispatch Report</h1>
<h2 align="center">Wrong Arrives Report</h2>
<table align="center" border="2">
<tr>
<td>Select Shift<br />
<form name="shiftfrm" id="shiftfrm" method="POST">
<select name="shiftlist" id="shiftlist">
<option value="" selected="selected">--------</option>
<?php
$dir = opendir("files/");
while (false !== ($file = readdir($dir)))
{
if (strpos($file, '.txt', 1))
{
echo '<option value="' . $file . '">' . $file . '</option>';
}
}
?>
</select>
<input type="submit" name="submit" id="submit" value="Submit"/>
<br />
<?php
if (isset($_POST['submit']) && isset($_POST['shiftlist']))
{
if ($handle = file_get_contents('files/' . $_POST['shiftlist']))
{
$output = '<table align="center" width="" border="2">';
$output .= '<tr><td>';
echo $handle;
$output .= '</tr></td>';
$output .= '</table>';
} else
{
echo "No Content";
}
} else
{
echo "Please select the file";
}
?>
</td>
</tr>
</table>
</body>
</html>

Related

Need to scan a directory and delete only specific type of file

I need to have a php script that allows me to scan a directory and then, delete the files from it, my code works just fine, it lists all I need but, my problem is that I need to delete only a specific file from that directory and this script scans everything, in this case i am trying to delete only the .sql files created. However this script lists all types of files.
I leave my code below:
<?php
$fid= $_POST['fid'];
if (("submit")&&($fid != "")) {
foreach($fid as $rfn) {
$remove = "$dire/$rfn";
unlink($remove);
}
}
$handle=opendir($dire);
while (($file = readdir($handle))!== false){
if ($file != "." && $file != "..") {
$size = filesize("$dire/$file");
$list .= '<table class="table table-bordered table-dark table-hover" cellspacing="0" width="100%">';
$list .= '<tbody>';
$list .= '<tr style="text-transform:uppercase;">';
$list .= '<td><small>'.$file.'</small></td>';
$list .= '<td align="center"><small><input type="checkbox" class="form-control" name="fid[]" value="'.$file.'"></small></td>';
$list .= '</tr>';
$list .= '</tbody>';
$list .= '</table>';
}
}
closedir($handle);
echo $list;
?>
As you can see, this code works just fine, not pretty I know but I need to have a way to show only my SQL files and not the other types of files.
If you just want to check the file extension before deletion:
<?php
foreach ($fids as $fid) {
if (pathinfo($dire . '/' . $fid)['extension'] == 'sql') {
unlink($dire . '/' . $fid);
}
}
?>
Otherwise, you can scan your directory for only .sql with GLOB()
<?php
$dire = 'my_dir';
if (!empty($_POST['fid'])) {
$fids = $_POST['fid'];
foreach ($fids as $fid) {
unlink($dire . '/' . $fid);
}
}
?>
http://php.net/manual/en/function.glob.php
<?php
$files = GLOB($dire . '/*{.sql}', GLOB_BRACE);
?>
<?php if ($files): ?>
<?php foreach($files as $file): ?>
<table class="table table-bordered table-dark table-hover" cellspacing="0" width="100%">
<tbody>
<tr style="text-transform:uppercase;">
<td><small><?= basename($file); ?></small></td>
<td align="center"><small><input type="checkbox" class="form-control" name="fid[]" value="<?= basename($file); ?>"></small></td>
</tr>
</tbody>
</table>
<?php endforeach; ?>
<?php endif; ?>
I came across PHP's RecursiveDirectoryIterator some time ago. This built-in class will let you iterator through a directory and it's subdirectories and perform any action you want on the files in it.
Take a look at the example below on how to implement this:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// The directory to remove files from
$directory = $_POST['directory'];
// The extension se are looking for
$extension = $_POST['extension'];
// Construct the iterator
$it = new RecursiveDirectoryIterator($directory);
// Loop through files
foreach(new RecursiveIteratorIterator($it) as $file) {
if ($file->getExtension() == $extension) {
echo 'Removing ' . $file . "\n";
unlink($file);
}
}
}
Implementation
You can replace your code with the following script. Note that I have used the DirectoryIterator in this case because you only want to iterate through a single directory.
<?php
/**
* Directory overview
*/
// The directory to remove files from
$directory = '/path/to/directory';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach ($_POST['fid'] as $filePath) {
unlink $filePath;
}
}
?>
<table class="table table-bordered table-dark table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th>File</th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach (new DirectoryIterator($directory) as $file): ?>
<?php if ($file->isDot() || !$file->isFile()) continue; ?>
} <tr style="text-transform:uppercase;">
<td><small><?= $file; ?></small></td>
<td align="center"><small><input type="checkbox" class="form-control" name="fid[]" value="<?= $file->getPathName(); ?>"></small></td>
</tr>
</tbody>
</table>
Resources
DirectoryIterator - Manual

Problems with using PHP to display CSV file as HTML table

I'm trying to display a two column, four row CSV file in an HTML table. I have the code below, but it only displays the first row and I don't understand why.
<html>
<head>
<title>test</title>
</head>
<body>
<table border=1>
<?PHP
$file_handle = fopen("oee1.csv", "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></tr>';
}
fclose($file_handle);
?>
</table>
</body>
</html>
The csv file looks like:
test1, 1
test2, 2
test3, 3
test4, 4
You were not iterating through every line.
Try something like this:
<!DOCTYPE html>
<html>
<head>
<title>+test</title>
</head>
<body>
<?php
if (($file_handle = fopen("data.csv", "r")) !== false) {
$str = '';
$str .= '<table>';
while (($data = fgetcsv($file_handle, 1024, ",")) !== false) {
$str .= '<tr>';
foreach ($data as $key => &$value) {
$str .= "<td>$value</td>";
}
$str .= '</tr>';
}
fclose($file_handle);
$str .= '</table>';
echo $str;
}
?>
</body>
</html>
output:
<table>
<tbody>
<tr>
<td>test1</td>
<td>1</td>
</tr>
<tr>
<td>test2</td>
<td>2</td>
</tr>
<tr>
<td>test3</td>
<td>3</td>
</tr>
<tr>
<td>test4</td>
<td>4</td>
</tr>
</tbody>
</table>
PS: make sure you have priviledges and your csv is in the smae directory as your php file.
Reference : fgetcsv
try adding a call to fgets($file_handle); in each iteration of the loop, you have to advance the file handle pointer somehow.

Fire Query on CSV data

I have a public google spreadsheet.I got the CSV data as an array from the remote URL.Then I displayed the information as an HTML list, referencing the appropriate array items.
Now I want to fire an php select query on it such that only the gossip of a particular actor is displayed.How to do it ?
(I want to use a variable $Name.wen I supply Name.I should get the gossip of that Actor.)
my excel sheet contains following columns
> 1.Sr No.
> 2.Name
> 3.Gossip
This is the code of my php page that retrieves the data as a list :
$lines = file('https://docs.google.com/spreadsheet/pub?key=0AgzUC4MxdChJdFIyMHFUZ21PS053b3Z1OHFnbHJwYVE&single=true&gid=0&output=csv');
$headers = array_shift($lines);
foreach ($lines as $line)
{
$ldata = explode(',', trim($line));
if ($ldata[0] == '') break;
echo '<li>Sr No. <strong>' . $ldata[0] . '</strong></li><li>Name <strong>' . $ldata[1] . '</strong></li><li>Gossip <strong>' . $ldata[2] . '</strong></li>';
}
Give this a shot:
<?php
// get the CSV data as an array from the remote URL
define('GOOGLE_DOC','https://docs.google.com/spreadsheet/pub?key=0AgzUC4MxdChJdFIyMHFUZ21PS053b3Z1OHFnbHJwYVE&single=true&gid=0&output=csv');
if(isset($_GET['filterColumn'])){define('FILTER_COLUMN',$_GET['filterColumn']);}
if(isset($_GET['filterValue'])){define('FILTER_VALUE',$_GET['filterValue']);}
function readCSVIntoArray($fileName)
{
$rows=array();
if (($handle = fopen($fileName, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE){$rows[]=$data;}
fclose($handle);
}
$h=array_shift($rows);
return array($h,$rows);
}
list($head,$rows)=readCSVIntoArray(GOOGLE_DOC);
header('Content-Type: text/html; charset=utf-8');
?><!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Ultimater's Example</title>
<style type="text/css">
html,body
{
margin:0;
padding:0;
font-family:'Source Sans Pro',sans-serif;
font-size: 13px;
color:black;
background:#e2e2ec;
line-height:15px;
}
table{border-collapse:collapse;}
table thead tr th{font-weight:bold;padding:2px;margin:1px;border:1px solid black;background-color:blue;color:white;}
table tbody tr td{margin:1px;padding:2px;border:1px solid black;}
</style>
</head>
<body>
<div>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
<select name="filterColumn">
<?php foreach($head as $i=>$h){echo sprintf('<option value="%s">%s</option>',$i,htmlentities($h));} ?>
</select>
<input type="text" name="filterValue" place-holder="filter" value="" />
<input type="submit" value="Filter" />
</form>
</div>
<hr />
<?php
echo '<table>';
echo '<thead><tr><th>'.implode('</th><th>',$head).'</th></tr></thead>';
echo '<tbody>';
foreach($rows as $row)
{
if(defined('FILTER_COLUMN')&&defined('FILTER_VALUE'))
{
if(strpos($row[FILTER_COLUMN],FILTER_VALUE)===false)continue;
}
echo '<tr><td>'.implode('</td><td>',$row).'</td></tr>';
}
echo '</tbody>';
echo '</table>';
?>
</body>
</html>
Simply do not display a line if name is not like required:
<?php
// get the CSV data as an array from the remote URL
$lines = file('https://docs.google.com/spreadsheet/pub?key=0AgzUC4MxdChJdFIyMHFUZ21PS053b3Z1OHFnbHJwYVE&single=true&gid=0&output=csv');
// get rid of header row
$headers = array_shift($lines);
// Loop through data- therer is only one line hear
foreach ($lines as $line) {
$ldata = explode(',', trim($line)); // split row to its own array of elements
if ($ldata[0] == '') break; // an empty line means we are done, so exit the foreach loop
if($ldata[1] == $var_with_required_name) {
// now we can just output the information as an HTML list, referencing the appropriate array items
echo '<li>Sr No. <strong>' . $ldata[0] . '</strong></li><li>Name <strong>' . $ldata[1] . '</strong></li><li>Gossip <strong>' . $ldata[2] . '</strong></li>';
}
}
?>

Setting the form action to a jquery tab

I have installed a jquery UI tabs system on my web page , but the I have had a series of problems , one of them being: I can make a form request to my PhP at the same page and then process the result on it self.
In other words: I want to set the action of the form in question to the the same tab, loaded from another file via ajax, that contains the form in the first place, so it can read and display a table with the search results.
Here are some codes, hope it helps.
The index (continas the #tabs div):
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="iso-8859-1" />
<link type="text/css" href="css/smoothness/jquery-ui-1.8.21.custom.css" rel="Stylesheet" />
<link rel="stylesheet" type="text/css" href="css.css"></link>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript" src="maskMoney.js"></script>
<title>Financeiro</title>
</head>
<body>
<script>
$(function() {
$( "#tabs" ).tabs({
ajaxOptions: {
error: function( xhr, status, index, anchor ) {
$( anchor.hash ).html(
"A tab não pode ser carregada ou está sob manutenção, desculpe o transtorno." );
}
}
});
});
</script>
<div>
<div id="tabs">
<ul>
<li>Buscar saída</li>
<li>Criar saída</li>
</ul>
</div>
</div>
<script type="text/javascript" src="create.js"></script>
</body>
</html>
And here it is one of the forms I place under a tab (the financeiro_ver.php file):
<?php
include 'all.php';
if (isset($_POST['efetuar'])) {
$saida = new Saida();
if (isset($_POST['situacao'])) {
$saida->situacao = $_POST['situacao'];
} else {
$saida->situacao = 'npago';
}
$sql = "UPDATE financeiro SET situacao = '".$saida->situacao."' WHERE id = '".$_POST['saidaId']."'";
mysql_query($sql);
}
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['ID_FUNCIONARIO'] = 46;
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="iso-8859-1" />
<link type="text/css" href="css/smoothness/jquery-ui-1.8.21.custom.css" rel="Stylesheet" />
<link rel="stylesheet" type="text/css" href="css.css"></link>
<title>Financeiro</title>
</head>
<body>
<form id="form0" name="form0" method="post" action="financeiro_ver.php"> <!--action="http://sim.medgoldman.com.br/financeiro/financeiro_ver.php" style="background-color:#EEEEEE"> -->
<table border="0" align="center" cellpadding="10" cellspacing="0">
<tr>
<td align="center">GRUPO:
<select name="categoria" id="produto">
<option value="adm">Despesas Administrativas</option>
<option value="imp">Importações</option>
<option value="ban">Bancos</option>
<option value="matriz">Despesas Matriz</option>
<option value="outros">Outros</option>
</select></td>
<td align="center">PERÍODO:
<td>de: <input name="data1" id="data1" value=""></input></td>
<td>até: <input name="data2" id="data2" value=""></input></td>
</select></td>
<td align="center"><input name="buscar" type="submit" id="buscar" value=" Buscar " /></td>
</tr>
</table>
</form>
<?php
if ($_SESSION['ID_FUNCIONARIO'] == '19') {
echo '<form name="form2" method="post" <!--action="http://sim.medgoldman.com.br/financeiro/financeiro_ver.php" --> style="background-color:#EEEEEE">';
}
?>
<table class ="viewTable" align="center">
<?php
if (isset($session->message)) {
$mens ="<th>" . $session->message . "</th>";
echo utf8_encode($mens);
}
if (isset($_POST['buscar'])) {
$query = "SELECT * FROM financeiro " .
"WHERE categoria = '" . $_POST['categoria'] .
"' AND data >= '" . $_POST['data1'] .
"' AND data <= '" . $_POST['data2'] . "'";
if (mysql_query($query, $database->connection)) {
$categoriaSel = mysql_query($query, $database->connection);
$output = '<tr><th colspan="3">Categoria ';
if ($_POST['categoria'] === 'adm') {
$output .= "Despesas administrativas";
} elseif ($_POST['categoria'] === 'imp') {
$output .= "Importações";
} elseif ($_POST['categoria'] === 'ban') {
$output .= "Bancos";
} elseif ($_POST['categoria'] === 'outros') {
$output .= "Outros";
} elseif ($_POST['categoria'] === 'matriz') {
$output .= "Despesas Matriz";
}
$output .= "</th>";
$output .= "<tr><th>Data</th><th>Descrição</th><th>Valor</th></tr>";
$valorSomaUS = 0;
$valorSomaRS = 0;
while ($saidasSel = mysql_fetch_array($categoriaSel)) {
$valorDisplay = number_format($saidasSel['valor'], '2', ',', '.');
$output .= "<tr";
if ($saidasSel['situacao'] === 'pago') {
$output .= ' class="pago"';
} else if ($saidasSel['situacao'] === 'npago') {
$output .= ' class="npago"';
}
$output .= ">";
$output .= "<td class=\"datout\">" . $saidasSel['data'] . "</td>";
$output .= "<td class=\"desout\">" . $saidasSel['descricao'] . "</td>";
if ($saidasSel['cambio'] === "us") {
$output .= "<td class=\"valout\"> U$ " . $valorDisplay . "</td>";
$valorSomaUS += $saidasSel['valor'];
} else {
$output .= "<td class=\"valout\"> R$ " . $valorDisplay . "</td>";
$valorSomaRS += $saidasSel['valor'];
}
//VERIFICA USUARIO PARA ADICIONAR PAGO/NPAGO:
if ($_SESSION['ID_FUNCIONARIO'] == '19') {
$output .= '<td><input name="situacao" type="checkbox" value="pago"';
if ($saidasSel['situacao'] === 'pago') {
$output .= ' checked';
}
$output .=">Pago</input></td>";
}
//VERIFICA USUARIO PARA VER PAGO/NPAGO:
if ($_SESSION['ID_FUNCIONARIO'] == '46') {
if ($saidasSel['situacao'] === 'pago') {
$output .= '<td>pago</td>';
} else {
$output .= '<td>não pago</td>';
}
}
if ($_SESSION['ID_FUNCIONARIO'] == '30' && $saidasSel['categoria'] === "imp") {
if ($saidasSel['situacao'] === 'pago') {
$output .= '<td>pago</td>';
} else {
$output .= '<td>não pago</td>';
}
}
//VERIFICA USUARIO PARA ADICIONAR DELETAR:
if (($_SESSION['ID_FUNCIONARIO'] == '46') && ($saidasSel['categoria'] === 'adm' || $saidasSel['categoria'] === 'outros' || $saidasSel['categoria'] === 'matriz')) {
$output .= "<td><button class=\"deletar\" href=\"financeiro_deletar.php?id=" . $saidasSel['id'] . "\">Deletar</button>";
} elseif (( $_SESSION['ID_FUNCIONARIO'] == '30' || $_SESSION['ID_FUNCIONARIO'] == '46' ) && $saidasSel['categoria'] === 'imp') {
$output .= "<td><button class=\"deletar\" href=\"financeiro_deletar.php?id=" . $saidasSel['id'] . "\">Deletar</button></td>";
}
$output .="</tr>";
//SOMA DOS VALORES DO PERIODO:
$valorSomaUS = number_format($valorSomaUS, '2', ',', '.');
$valorSomaRS = number_format($valorSomaRS, '2', ',', '.');
$output .= "<tr> <td class=\"valsoma\" colspan=\"3\"> Soma do período = R$ " . $valorSomaRS . " e U$ " . $valorSomaUS . "</td></tr>";
if ($_SESSION['ID_FUNCIONARIO'] == '19') {
$output .= '<tr><td><input id="efetuar" type="submit" value=" Efetuar " name="efetuar"></input></td><td><input type="hidden" value="' . $saidasSel['id'] . '" name="saidaId"></input></td></tr>';
}
}
echo utf8_encode($output);
} else {
$session->message("Nenhuma saída para este período.");
}
}
?>
</table>
<?php
if ($_SESSION['ID_FUNCIONARIO'] == '19') {
echo '</form>';
}
?>
</body>
</html>
http://jsfiddle.net/mZLDk/
$(document).ready(function() {
// Tab initialization
// This is setup for two tab groups and is not needed
$('#tabs, #fragment-1').tabs({
select: function(event, ui){
var tabNumber = ui.index;
var tabName = $(ui.tab).text();
//Here I setup an event for each change this changes some inner html
//of a tag but can be applied in your situation
if(tabNumber = 1 ) {
document.getElementById('fragment-1a').innerHTML = "changed";
} else {
}
//This was just some debuging code for me
console.log('Tab number ' + tabNumber + ' - ' + tabName + ' - clicked');
}
});
});
You would replace the line
document.getElementById('fragment-1a').innerHTML = "changed";
with
document.forms[0].action = "An Action";
Im really excited as this is my first working answer for some one on this site so please tell me if it works
THE BIG LONG STORY OF HOW A COMPLETE JAVASCRIPT NOOB FOUND YOUR ANSWER
As an idea you could try making it so the tabs event changes the setting IE this
jQuery - trapping tab select event
but how does that apply to you well I found something else here
http://www.tek-tips.com/viewthread.cfm?qid=1235640
this talks about chagines a form action based uppon an event which you can change onlcick.
But now an example that brings the two together
http://jsfiddle.net/mZLDk/

images with radio buttons (no database) in php

I'm trying to create a simple dynamic gallery with a radio button under each image to allow the user to select an image and submit the form. I'm not concerned with processing the form yet, I'd just like to figure out how to dynamically generate the form. Currently I'm creating the gallery with this;
<?php
$images = "image_gallery/";
$big = "big/";
$cols = 2;
if ($handle = opendir($images)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && $file != rtrim($big,"/")) {
$files[] = $file;
}
}
closedir($handle);
}
$colCtr = 0;
echo '<table width="100%" cellspacing="3"><tr>';
foreach($files as $file)
{
if($colCtr %$cols == 0)
echo '</tr><tr><td colspan="2"><hr /></td></tr><tr>';
echo '<td align="center"><img src="' . $images . $file . '" /></td>';
$colCtr++;
}
echo '</table>' . "\r\n";
?>
It seems as though I should create the radio buttons inside of the foreach loop, but I'm not sure exactly where, or how.
I appreciate any help.
in your foreach loop:
foreach($files as $file){
if($colCtr %$cols == 0)
echo '</tr><tr><td colspan="2"><hr /></td></tr><tr>';
echo '<td align="center"><img src="' . $images . $file . '" /><input type="radio" name="should be common if to choose one between mutiples" value="the value you want to send via form" /></td>';
$colCtr++;
}
echo '</table>' . "\r\n";

Categories