I was asked to do this by my college staffs so kindly help me out with this! I have a php file with a text box and login id is supposed to be entered in it and login button is to be pressed. Once this button is pressed, the login id and timestamp is stored in a txt file. Next time the same login id is used then the timestamp is to be overwritten. I have done this part successfully. Now, i wanna display the timestamp before overwritting it. This is something similar to last seen of whatsapp. How can i display it?
This is my code:
<html>
<head><title>Login Portal</title></head>
<body><center>
<h1>TPF EMPLOYEE LOGIN</h1><hr><br><br>
<?php
session_start();
if(isset($_POST['submit']))
{
$myfile = file_get_contents('data.txt');
$_SESSION['name']=$_POST['id'];
date_default_timezone_set('Asia/Calcutta');
$date = date('Y-m-d H:i:s');
$txt=$_SESSION['name'].",".$date.",\n";
$name = $_SESSION['name'];
if(preg_match("/$name/", $myfile))
{
$results = preg_replace("/$name.*\,/", $txt, $myfile);
file_put_contents('data.txt', $results);
}
else
{
file_put_contents('data.txt', $txt, FILE_APPEND);
}
}
else
{
echo "<form name='login' method='post'>";
echo "Enter your login id : <input type='text' name='id' id='id' /><br><br>";
echo "<input type='submit' name='submit' value='Login' />";
echo "</form>";
}
?>
</center>
</body>
</html>
This is the contents of my txt file:
a,2014-10-05 19:00:40,
b,2014-10-05 19:00:31,
Using the comma after the name as an identifier how do i display the previous timestamp before overwritting it?
Change:
if(preg_match("/$name/", $myfile))
{
to include $matches and alter the regexp, then work with $matches array:
if(preg_match("/$name\,(.*),/", $myfile, $matches))
{
echo 'Previous Login: ' . $matches[1];
Example: http://ideone.com/1diNNd
Hints: use a db, ensure $name is unique...
Related
First, forgive me if this is an overly pedantic question. I have searched trying to find answers but perhaps I'm using the wrong search terms.
Trying to use an INI file for a simple PHP application, where there is an admin page to allow application options to be easily changed. I'm able to read in the ini file with no issue, problem I'm coming across is on the write - if any boolean values are false, they won't get put into the _POST and as such don't get written back into the ini file. Here's my sample:
settings.ini file:
[Site options]
bRequireLegal['Require NDA before badge print'] = true ;
bCollectVehicleInfo['Collect vehicle information'] = false;
bShowAdditionalMessageBeforeBadgePrint['Show badge printing message'] = true;
[Company info]
companyname['Company Name'] = 'The Company, Inc.' ;
Code to read in the ini file (settings.php):
$filepath = 'settings.ini'; //location of settings file
$settings = parse_ini_file($filepath, true, $scanner_mode = INI_SCANNER_TYPED);
//pull everything in ini file in as variable
foreach($settings as $section=>$options){
foreach($options as $option=>$values){
foreach($values as $descriptor=>$value){
if(is_bool($value) === true) {
${htmlspecialchars($option)} = +$value;
}
else ${htmlspecialchars($option)} = $value;
}
}
}
And finally, the options setting page:
<?php
include 'settings.php';
//after the form submit
if($_POST){
$data = $_POST;
update_ini_file($data, $filepath);
}
function update_ini_file($data, $filepath) {
$content = "";
//parse the ini file to get the sections
foreach($data as $section=>$options){
//append the section
$content .= "[".$section."]\r\n";
//append the values
foreach($options as $option=>$values){
$content .= $option;
foreach($values as $descriptor=>$value){
$content .= "['".$descriptor."'] = '".$value."';\r\n";
}
}
$content .= "\r\n";
}
if (!$handle = fopen($filepath, 'w')) {
return false;
}
$success = fwrite($handle, $content);
fclose($handle);
return $success;
}
?>
<html>
<body>
<?php
?>
<div class="container-fluid">
<form action="" method="post">
<?php
foreach($settings as $section=>$options){
echo "<h3>$section</h3>";
//keep the section as hidden text so we can update once the form submitted
echo "<input type='hidden' value='$section' name='$section' />";
//print all other values as input fields, so can edit.
foreach($options as $option=>$values){
foreach($values as $descriptor=>$value){
if(is_bool($value) === true) {
echo "<p>".$descriptor.": <input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
} else
echo "<p>".$descriptor.": <input type='text' name='{$section}[$option][$descriptor]' value='$value' />"."</p>";
}
}
echo "<br>";
}
?>
<input type="submit" value="Update INI" />
</form>
</div>
</body>
</html>
Any help would be greatly appreciated!
In your update_ini_file() function, replace this:
$content .= "['".$descriptor."'] = '".$value."';\r\n";
with
$content .= "['".$descriptor."'] = '".($value ? 'true' : 'false')."';\r\n";
This will cause it to write the strings 'true' and 'false' instead of literal Boolean values. See How to Convert Boolean to String
Edit to add:
I think you're generating your checkboxes incorrectly:
<input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." />
This will cause the 'true' boxes to be checked, but they will still lack a value (and thus will not be transmitted to the server when the form is submitted). You should change that code to:
<input type='checkbox' name='{$section}[$option][$descriptor]' value='1'".(($value===true)?" checked":"")." />
In other words, all checkboxes should have a value of '1', but the way the browser works, only those which are checked will be submitted.
Edit to add:
Checkboxes that are not checked will not get submitted. That explains why you are not seeing any output for values that are 'false': they simply don't get submitted. When you loop through $data (which comes from $_POST), it is missing those unchecked (and thus 'false') checkboxes.
Using a solution found here: POST unchecked HTML checkboxes
Change this:
echo "<p>".$descriptor.": <input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
to this, which includes a hidden field that has the value '0', which will get submitted even if the corresponding checkbox is unchecked:
echo "<p>".$descriptor.": <input type='hidden' name='{$section}[$option][$descriptor]' value='0'><input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
However, this has its own set of potential problems, specifically when a checkbox is checked, you will send two identically named fields: one with a '0' value and the other with a '1' value. This is explained in the link above, and is left as an exercise for you to solve (or ask for further details on) if my answer doesn't work.
I'm using this code to update a given file;
<?php
if($_POST['submit']){
$open = fopen("textfile.php","w+");
$text = $_POST['update'];
fwrite($open, $text);
fclose($open);
echo "File updated.<br />";
echo "File:<br />";
$file = file("textfile.php");
foreach($file as $text) {
echo $text."<br />";
}
}else{
$file = file("textfile.php");
echo "<form action=\"".$PHP_SELF."\" method=\"post\">";
echo "<textarea Name=\"update\" cols=\"50\" rows=\"10\">";
foreach($file as $text) {
echo $text;
}
echo "</textarea>";
echo "<input name=\"submit\" type=\"submit\" value=\"Update\" />\n
</form>";
}
?>
But somehow its showing this error:
Although the file does updated with this code when I submit my text and no error or submission, however the error its showing on the screenshot bugs me, so any way I could remove those errors?
Thanks!
Change line 2 to this:
if(isset($_POST['submit'])){
Change line 15 to this:
echo "<form action=\"".$_SERVER['PHP_SELF']."\" method=\"post\">";
Assuming that your submit button is named submit checking for $_POST['submit'] is unreliable (as not all browsers POST the submit button), you should check for another field name that is posted OR better yet, change to if($_SERVER['REQUEST_METHOD'] == 'POST'){.
Also, $PHP_SELF is assuming you have register globals on (which shouldn't be), you should use $_SERVER['PHP_SELF'] instead.
Joe has it. You want isset(). # (error suppression) is the coward's way out. Be a man and use isset() ;-)
I'm in the process of creating a prototype e-commerce website, I'm having problems saving the visitor name to my flat file database "purchases".
<body>
<h1>Confirm Selection</h1>
<form action="write.php" method="post">
<table>
<tr><th></th><th></th><th></th><th>Price</th></tr>
<?php
$visitor = $_POST['visitor'];
echo "<p>".'Hello '."<b>".$visitor."</b> ".'please confirm your purchase(s) below.'."</p>";
?>
</table>
The confirm file above creates a variable called $visitor which is whatever the user entered as his/her name in the previous form, I then want to take this variable and once the user has confirmed their selection pass it to the "write.php" file to be processed and written to the purchases file.
Part of my "write.php" file is below.
<?php
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
}
$now = date(' d/m/y H:i:s ');
foreach ($_POST as $varname => $varvalue) {
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname) {
$myFile = "purchases.txt";
$fh = fopen($myFile, 'a') or die("can't open file\n");
$content = $now . "|" . $partno . "|" . $name . "|" . $price . "\n";
if (!(fwrite($fh, $content))) {
echo "<p>ERROR: Cannot Write ($myFile)\n</p>";
exit;
} else {
echo "<p>Transaction Completed!</p>";
fclose($fh);
}
}
}
}
?>
If purchase page submit goes to write.php, a hidden variable might work:
<form action="write.php" method="post">
<table>
<tr><th></th><th></th><th></th><th>Price</th></tr>
<?php
$visitor = $_POST['visitor'];
echo "<p>".'Hello '."<b>".$visitor."</b> ".'please confirm your purchase(s) below.'."</p>";
?>
<input type="hidden" name="visitor" value="<?=$visitor?>"/> <!-- added line to send visitor -->
</table>
so in your write.php:
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
}
$visitor = $_REQUEST['visitor']; // added line, now you have visitor
$now = date(' d/m/y H:i:s ');
PS: you might need htmlentities function since the user can enter funny characters for visitor:
<input type="hidden" name="visitor" value="<?=htmlentities($visitor)?>">
I have a folder where I keep my images, named img/. I have a table with all of my images:
<table border="3">
<tr>
<td>
<?php
$files = glob("img/*");
foreach ($files as $file) {
echo "<div class='divimages'>";
echo '<img src="'.$file.'"/>';
echo "<input type='submit' value='Delete image'/><br>";
echo "</div>";
}
?>
</td>
</tr>
</table>
How can I delete the image associated to the button with the value:"Delete image".
There are a few routes. One, the most simple, would involve making that into a form; when it submits you react to POST data and delete the image using unlink
DISCLAIMER: This is not secure. An attacker could use this code to delete any file on your server. You must expand on this demonstration code to add some measure of security, otherwise you can expect bad things.
Each image's display markup would contain a form something like this:
echo '<form method="post">';
echo '<input type="hidden" value="'.$file.'" name="delete_file" />';
echo '<input type="submit" value="Delete image" />';
echo '</form>';
...and at at the top of that same PHP file:
if (array_key_exists('delete_file', $_POST)) {
$filename = $_POST['delete_file'];
if (file_exists($filename)) {
unlink($filename);
echo 'File '.$filename.' has been deleted';
} else {
echo 'Could not delete '.$filename.', file does not exist';
}
}
// existing code continues below...
You can elaborate on this by using javascript: instead of submitting the form, you could send an AJAX request. The server-side code would look rather similar to this.
Documentation and Related Reading
unlink - http://php.net/manual/en/function.unlink.php
$_POST - http://php.net/manual/en/reserved.variables.post.php
file_exists - http://php.net/manual/en/function.file-exists.php
array_key_exists - http://php.net/manual/en/function.array-key-exists.php
"Using PHP With HTML Forms" - http://www.tizag.com/phpT/forms.php
You can delete files in PHP using the unlink() function.
unlink('path/to/file.jpg');
First Check that is image exists? if yes then simply Call unlink(your file path) function to remove you file otherwise show message to the user.
if (file_exists($filePath))
{
unlink($filePath);
echo "File Successfully Delete.";
}
else
{
echo "File does not exists";
}
For deleting use http://www.php.net/manual/en/function.unlink.php
Hope you'll can to write logic?
You can try this code. This is Simple PHP Image Deleting code from the server.
<form method="post">
<input type="text" name="photoname"> // You can type your image name here...
<input type="submit" name="submit" value="Delete">
</form>
<?php
if (isset($_POST['submit']))
{
$photoname = $_POST['photoname'];
if (!unlink($photoname))
{
echo ("Error deleting $photoname");
}
else
{
echo ("Deleted $photoname");
}
}
?>
<?php
require 'database.php';
$id = $_GET['id'];
$image = "SELECT * FROM slider WHERE id = '$id'";
$query = mysqli_query($connect, $image);
$after = mysqli_fetch_assoc($query);
if ($after['image'] != 'default.png') {
unlink('../slider/'.$after['image']);
}
$delete = "DELETE FROM slider WHERE id = $id";
$query = mysqli_query($connect, $delete);
if ($query) {
header('location: slider.php');
}
?>
<?php
$path = 'img/imageName.jpg';
if (is_file($path)) {
unlink($path);
} else {
die('your image not found');
}
I have the following HTML form:
<form action='delete.php' method='POST'>
<table>
<div class = '.table'>
<?php
$dir = '../uploads/store/';
$newdir = ereg_replace('\.','',$dir);
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (!preg_match('/^(\.(htaccess|\.)?|index\.html)/',$file)) {
echo "<tr><td><font color = 'white'><a href='$newdir$file'>$file</a></font></td>";
echo "<td><input type='submit' value ='Delete'></td></tr>";
echo "<input align='right' type='hidden' value='$file' name='file'>";
}
}
closedir($dh);
}
}
?>
</div>
</table>
</form>
Which links to the following PHP script:
<?php
session_start();
$file = $_POST['file'];
$dir = '../uploads/store/';
$file = $dir . $file;
opendir($dir);
if(unlink($file)) {
echo "File sucessfully deleted";
$_SESSION['username'] = 'guitarman0831';
header('Refresh: 2;url=http://www.ohjustthatguy.com/uploads/uploads.html');
} else {
echo "Error: File could not be deleted";
$_SESSION['username'] = 'guitarman0831';
header('Refresh: 2;url=http://www.ohjustthatguy.com/uploads/uploads.html');
}
?>
However, when the Delete button is pressed in the HTML form, the item above the one intended to delete is deleted.
Hope this makes sense.
NOTE: I'm not going for security with these scripts, I'm going to work on that later. It's only me using this service right now.
Your HTML form needs to have the various submit buttons pass the value for $file instead of using hidden fields.
The problem is that all of the hidden fields are POSTed to delete.php when you submit the form. Then, since you haven't used the PHP-friendly HTML array variable syntax, PHP uses only the last of these to set the value of $_POST['file']. If you do a var_dump of $_POST in delete.php, you will see what the POSTed input is.
The easiest thing to do, with your current markup, is just to have each submit button be named file and pass $file as its value. i.e. you could do:
<button name="file" value="example.txt" type="submit">Delete</button>
Alternately, you could use radio buttons or some other markup.