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)?>">
Related
im new in php programming and ive a problem recently. I have 1 html page with a Search Box and a php script using for grep in a specific file on local host. This is what i want, when a user type string of char and click on enter that send a POST to modify my php var $contents_list, and grep all filename where the string is found.
<?php
$contents_list = $_POST['search'];
$path = "/my/directory/used/for/grep";
$dir = new RecursiveDirectoryIterator($path);
$compteur = 0;
foreach(new RecursiveIteratorIterator($dir) as $filename => $file) {
$fd = fopen($file,'r');
if($fd) {
while(!feof($fd)) {
$line = fgets($fd);
foreach($contents_list as $content) {
if(strpos($line, $content) != false) {
$compteur+=1;
echo "\n".$compteur. " : " . $filename. " : \n"."\n=========================================================================\n";
}
}
}
}
fclose($fd);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form action="page2.php" method="post">
<INPUT TYPE = "TEXT" VALUE ="search" name="search">
</form>
</body>
And when i go to my html page and type text in searchbar, that redirect me to my php script "localhost/test.php" and i have 500 internal error.
So I want:
To see result of the php script on the same html page, but i dont know how to do that :/
And if the previous filename return was same like previous result, dont print it, to avoid double result.
I hope its clear and youve understand what i want to do, so thanks for the people who want to help me <3
My recommendations:
Combine the code into the single index.php file for simplicity
Separate logic for search and output to achieve clean separation of duties
Add helper text such as nothing found or enter text
index.php content:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<form action="index.php" method="post">
<input type="text" placeholder="search" name="search">
</form>
<?php
// Check if the form was submitted.
if (isset($_POST['search']) && (strlen($_POST['search'])) > 0) {
$search_line = $_POST['search'];
$path = "/my/directory/used/for/grep";
$dir_content = new RecursiveDirectoryIterator($path);
// Array to store results.
$results = [];
// Iterate through directories and files.
foreach (new RecursiveIteratorIterator($dir_content) as $filename => $file) {
$fd = fopen($file, 'r');
if ($fd) {
while (!feof($fd)) {
$file_line = fgets($fd);
if (strpos($file_line, $search_line) !== FALSE) {
$results[] = $filename;
}
}
fclose($fd);
}
}
// Output result.
echo "<pre>";
if ($results) {
foreach ($results as $index => $result) {
echo ($index + 1) . " :: $result\n";
}
}
else {
echo "Nothing found!";
}
echo "</pre>";
}
else {
// When nothing to search.
echo "<pre>Enter something to search.</pre>";
}
?>
</body>
</html>
Dear Fellow PhP Experts,
I am writing below code to export HTML table data in PHP.
Its working nicely in localhost. However, when I deployed to the domain, there is warning-
'Warning: Cannot modify header information - headers already sent by
(output started at ../result_month.php:64 //dbconnect.php line//) in
../result_month.php on line 77 //header("Location: $FileName") line//'.
Seeking suggestion from you, what I am exactly doing wrong.
<?php require_once('dbconnect.php'); ?>
<?php
//To generate report, home page added below data to query desired information.
$month=$_POST["themonth"];
$year=$_POST["theyear"];
?>
<?php //I am not intended to redirect to new page when pressing export button
if(isset($_POST["export"]))
{
//as i am in the same page, need to generate query string again, that is why kept this month and year in hidden inputs
$month_visit=$_POST["selected_month"];
$year_visit=$_POST["selected_year"];
$FileName = "data_" . $month_visit . "_" . $year_visit . ".csv";
header("Location: $FileName"); //its showing error in this line
$output = fopen($FileName, 'w');
// output the column headings
fputcsv($output, array('ID', 'Name'));
// fetch the data
$query_string = "SELECT ID, Name from Participant";
$rows = mysql_query($query_string);
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
fclose($output);
}
?>
<form method="post"> // added this form at the top of HTML table to add export button
<input type="hidden" name="selected_year" value="<?php echo $year; ?>">
<input type="hidden" name="selected_month" value="<?php echo $month; ?>">
<input type="submit" name="export" value="Export to CSV" />
</form>
<?php
$result = mysql_query("SELECT ID, Name from Participant");
echo "displaying query data in html table";
?>
Any content without PHP open tag are treated as HTML, sent as HTTP_BODY.
HTTP_BODY will be sent after HTTP_HEADER was closed.
Try these codes:
<?php
require_once('dbconnect.php');
//To generate report, home page added below data to query desired information.
$month=$_POST["themonth"];
$year=$_POST["theyear"];
//I am not intended to redirect to new page when pressing export button
if(isset($_POST["export"]))
{
//as i am in the same page, need to generate query string again, that is why kept this month and year in hidden inputs
$month_visit=$_POST["selected_month"];
$year_visit=$_POST["selected_year"];
$FileName = "data_" . $month_visit . "_" . $year_visit . ".csv";
// WARNING : Uncomment this will cause header() call failed.
//echo "THIS IS HTTP_BODY";
header("Location: $FileName"); //its showing error in this line
$output = fopen($FileName, 'w');
// output the column headings
fputcsv($output, array('ID', 'Name'));
// fetch the data
$query_string = "SELECT ID, Name from Participant";
$rows = mysql_query($query_string);
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
fclose($output);
}
?>
<form method="post"> // added this form at the top of HTML table to add export button
<input type="hidden" name="selected_year" value="<?php echo $year; ?>">
<input type="hidden" name="selected_month" value="<?php echo $month; ?>">
<input type="submit" name="export" value="Export to CSV" />
</form>
<?php
$result = mysql_query("SELECT ID, Name from Participant");
echo "displaying query data in html table";
?>
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...
So we are making in the class a sort of log. There is a input box and a button. Everytime the button is pressed, PHP will write on the text file and prints the current log. Now the text appears on the bottom, and we need to have the text appear on the top. Now how would we do that?
We tried doing this with alot of my classmates but it all resulted in weird behavours. (Like text is printed more then once, etc)
Thanks alot!
EDIT: Sorry, here is the code:
<html lang="en">
<head>
<title>php script</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form name="orderform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="text"/>
<input type="submit" value="Submit" />
<?php
//Basic variables
echo("<br/>");
$myFile = "log.txt";
$logfile = fopen($myFile,'r+');
$theData = fread($logfile,filesize($myFile));
//Cookie stuff so the username is rememberd.
$username = $_COOKIE['gebruikerscookie'];;
if(isset($_POST['username'])){
$gebruiker = $_POST['username'];
if($_COOKIE['gebruikerscookie'] == $gebruiker){
$username = $_COOKIE['gebruikerscookie'];
echo("Welcome back");
}else{
setcookie("gebruikerscookie", $gebruiker);
$username = $_COOKIE['gebruikerscookie'];
echo("Welcome dude!");
}
}
//Checks if theres something inside
if(isset($_POST['text'])){
$message = "<br/>". $username ." : " . $_POST['text'];
fwrite($logfile, $message ,strlen($message));
}
echo($theData);
?>
</form>
</body>
Check the fopen manual on modes: http://www.php.net/manual/en/function.fopen.php
Try 'r+' Open for reading and writing; place the file pointer at the beginning of the file.
Altough without any code this is hard to answer.
<?php
$contentToWrite = "Put your log content here \n";
$contentToWrite .= file_get_contents('filename.log');
file_put_contents('filename.log', $file_data);
?>
This will add the previous content of your file after your cureent content and write on your file.
Please reply if you have any doubt.
you're just missing the
fclose();
I assume, since not closing a filehandle can cause a lot of strange errors like this.
So
$myFile = "log.txt";
$logfile = fopen($myFile,'r+');
........
//Checks if theres something inside
if(isset($_POST['text'])){
$message = "<br/>". $username ." : " . $_POST['text'];
fwrite($logfile, $message ,strlen($message));
}
fclose($logfile); // close it outside the if-condition!
echo($theData);
should do the trick
$log = file('log.txt');
krsort($log);
foreach($log as $line) echo "$line<br>\n";
I need some help with some php scripting. I wrote a script that parses an xml and reports the error lines in a txt file.
Code is something like this.
<?php
function print_array($aArray)
{
echo '<pre>';
print_r($aArray);
echo '</pre>';
}
libxml_use_internal_errors(true);
$doc = new DOMDocument('1.0', 'utf-8');
$xml = file_get_contents('file.xml');
$doc->loadXML($xml);
$errors = libxml_get_errors();
print_array($errors);
$lines = file('file.xml');
$output = fopen('errors.txt', 'w');
$distinctErrors = array();
foreach ($errors as $error)
{
if (!array_key_exists($error->line, $distinctErrors))
{
$distinctErrors[$error->line] = $error->message;
fwrite($output, "Error on line #{$error->line} {$lines[$error->line-1]}\n");
}
}
fclose($output);
?>
The print array is only to see the errors, its only optional.
Now my employer found a piece of code on the net
<?php
// test if the form has been submitted
if(isset($_POST['SubmitCheck'])) {
// The form has been submited
// Check the values!
$directory = $_POST['Path'];
if ( ! is_dir($directory)) {
exit('Invalid diretory path');
}
else
{
echo "The dir is: $directory". '<br />';
chdir($directory);
foreach (glob("*.xml") as $filename) {
echo $filename."<br />";
}
}
}
else {
// The form has not been posted
// Show the form
?>
<form id="Form1" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Path: <input type="text" name="Path"><br>
<input type="hidden" name="SubmitCheck" value="sent">
<input type="Submit" name="Form1_Submit" value="Path">
</form>
<?php
}
?>
That basically finds all xmls in a given directory and told me to combine the 2 scripts.
That i give the input directory, and the script should run on all xmls in that directory and give reports in txt files.
And i don't know how to do that, i'm a beginner in PHP took me about 2-3 days to write the simplest script. Can someone help me with this problem?
Thanks
Make a function aout of your code and replace all 'file.xml' to a parameter e.g. $filename.
In the second script where the "echo $filename" is located, call your function.