How to stay signed in even after clicking refresh button - php

I am new to php and I want to add a functionality such that whenever user fills the form and logs in, the php code runs perfectly fine but after refreshing the page user have to again fill the form. I don't know code nor have knowledge of further.I tried googling but I only see these kind of solutions:
header(refresh: 5, url: url);
or
meta tag
That refreshes automatically but not after clicking the refresh button.
This is my php code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="services.css"/>
<link rel="stylesheet" type="text/css" href="bootstrap-css/bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="bootstrap-3.3.5-dist/css/bootstrap.min.css">
<script type="text/javascript" src="validate.js"></script>
<style>
a{
color: dodgerblue;
}
a:hover{
color: dodgerblue;
font-size: 101%;
}
span{
font-size: 110%;
line-height: 8px;
font-style: bold;
margin-left: 50px;
}
body{
background-color: #F0F0F0 ;
}
button{
margin-left: 15px;
}
</style>
</head>
<body link="slateblue">
<div id="LogIn"><b>Log In</b></div><br>
<form method="post" onsubmit="return logInPass()" action="log.php">
<div class="col-xs-4"/>
<label for="usr">Email:</label>
<input id="usrEmail" name="usrEmail" type="email" class="form-control" size="25%" placeholder="sample#example.com"/>
</div>
<br><br><br><br>
<div id="PasswordField" class="col-xs-4"/>
<label for="u_pswd">Password:</label>
<input id="u_pswd" type="password" class="form-control" size="25%" placeholder="Enter alteast 8 characters" />
</div>
<br><br><br><br>
<button id="submit" name="checkout" class="btn btn-primary" type="submit" value="submit">Log In</button>
</form>
<br><br>
<span>Not a part of GameRangers? Click here for Sign Up!</span>
<br>
</body>
</html>
<?php
echo "<style>body{font-family: segoe ui; font-size: 110%;}</style>";
session_start();
$_SESSION['username'] = $_POST['usrEmail'];
echo"Welcome ".$_SESSION['username']."<br><br>";
echo "Today is ".date("Y-m-d")."<br>".date("h:i:sa")."<br>";
?>

use sessions:
session_start(); // in top of PHP file
...
$_SESSION["userName"] = $userName;
in your page
session_start();
if(isset($_SESSION["userName"]) && $_SESSION["userName"] != ''){
//redirect to logged in page
}

as you are using sessions to store user name . This session can be used in if condition as like i had used here:
<div id="nav1">
<?php session_start();
if($_SESSION['id']=='')
{
?>
<font style="font-size:16px; font-weight:bold; color:#063443;">Welcome, Guest <a href="Login.php" >SignIn</a></font>
<?php }
else
{ ?>
<font style="font-size:16px; font-weight:bold; color:#063443;">Welcome, <?php echo $_SESSION['name'];?> My Account</font>
<?php }
?></div>
Here i had stored User Id in session[id] which will make a condition to show user login or not.

Firstly you're outputting before header with the location of session_start();.
Place it as your first line under your opening <?php tag, and you're missing an underscore in $SESSION and for $SESSION['username'], it is a superglobal.
The session isn't being recorded/stored because of it.
Sidenote: I'm really hoping that wasn't a typo on your part.
That should read as $_SESSION['username']
Having used error reporting, would have signaled a notice of an undefined variable.
Make sure that $_POST['usrEmail'] also holds a value and the element bears the same name attribute, and that the session is started inside all pages using sessions and with no typos as you have now.
Add error reporting to the top of your file(s) which will help find errors.
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
If you want to retain session values in a form, use a ternary operator for the inputs:
<input type="text" name= "usrEmail" id="usrEmail" value="<?php echo !empty(htmlspecialchars($_SESSION['username'])) ? htmlspecialchars($_SESSION['username']) : ''; ?>">
...and apply that same method to your other form inputs.
Check to see if the session is set and not empty.
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_SESSION["userName"]) && !empty($_SESSION["userName"]) )
{
// do something
}
else{
// do something else
}

Use SESSION or COOKIES to store logged in status
On successful sign in, set a session variable or cookie.
Then check if the session variable or cookie is isset and is the intented value, then keep the user on the page. Otherwise, redirect to login.
Also keep session_start() at the beginning of the page.
Edits to make it clear for the OP
Add session_start() at the beginning of the page. After validating the username and password, if an existing user, set a session using the below code.
$_SESSION['u_name'] = $_POST['usrEmail'];
otherwise, redirect to login page.
Then on top of all user specific pages (the pages that are accessible only to logged in users) paste the below code.
session_start();
if(!isset($_SESSION['u_name']))
{
header('location:login.php?redirect='.$_SERVER['REQUEST_URI']);
exit;
}
Hope this will help.

Related

How to redirect following submit button code to same page and if possible without reloading

I have created a code that run in a popup of WordPress website, the purpose of this code is to validate entered data available in mysql db table if available it displays relative code else it executes other code.
I have tried
action="<?php echo $_SERVER['PHP_SELF']; ?>"
and
headlocation(.......)
but none worked, it is submitting code and redirecting to index.php to display results.
<style><?php include 'search-zip.css'; ?>
</style>
<?php
include 'search-config.php';
$conn = OpenCon();
?>
<h3 class="formhead">Available in</h3>
<h2 class="formhead">Melbourne Inner Suburbs</h2>
<form class="form-wrapper" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="$POSTCODE" id="search" size="25" maxlength="35" value="<?php echo $_REQUEST['$POSTCODE'] ?>" />
<input type="submit"
name="submit" value="Search" id="submit"></form>
<p class="form-text">Please search your postal code for service availability</p>
<?
if (isset($_POST['submit'])) {
{
$zipcode=$_REQUEST['$POSTCODE'];
$sql = "SELECT * FROM service_location WHERE zipcode = $zipcode";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
?>
<style>.formhead{display:none;} .form-wrapper{display:none;} .form-text{display:none;}</style>
<div class="available">
<img class="zipimage" src="https://www.hastygrocer.com.au/wp-content/uploads/2019/07/hasty-grocer-available-popup-image.png" alt="Happy Minion" >
<h2 style="text-align: center;">Experience Melbourne's</h2>
<h2 style="text-align: center;"><i style="color: #3aafa9; font-family: Faster One script=all rev=2; font-size: 60px;">Fast</i> & <b style="color: green; font-family: Aladin; font-size: 60px;">Fresh </b></h2>
<h2 style="text-align: center;">Grocery Delivery</h2>
<span class="pum-close popmake-close "><button class="zipbutton" type="button">Shop</button></span></div>
<?
} else {
?>
<style>.formhead{display:none;} </style>
<div class="available">
<h3 style="text-align: center;">Get Notified When Available in <b style=" text-align: center;font-weight: 800; font-family: arial; color: #3aafa9;"><?php echo "$zipcode"?></b></h3>
<div class="zipform"><?php echo do_shortcode( '[contact-form-7 id="613" title="PopUp"]' ); ?></div>
</div>
<?
}
}}
?>
I created this code to redirect to same page.
but this is redirecting to index.php to display result.
please help me in fixing this using any php or ajax that may fix this code.
sorry I am not an expert developer I got code from internet and created the following code.
Thanks in advance
See this part of code: action="<?php echo $_SERVER['PHP_SELF']; ?>"
The submit will be performed to the link passed from the $_SERVER array, but PHP manual says:
$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these.
Try to make an <? echo $_SERVER['PHP_SELF']; ?> and see what is printed. You will probably get the index.php location.
Try to set the action to the page that contains the form.

how to create similar php pages but with different urls

I'm currently learning php so I'm a beginner I have learned the basics and some advanced stuff but now I'm trying to make a project to help me learn faster which will be basically a Math test in times table in which a user will enter the site, and then the user will enter his name and click 'Begin test' to enter the test which is 10 questions. the user need to answer the question first by clicking on a button and then click on 'Next' to go to next question and after finishing 10 questions the result will be shown to him something like "You have answered CorrectAnswersNumber from total of 10 questions!".
I have made something like this when I was learning ASP.Net MVC but in php it is a bit complicated. So my question is should I need to create 10 php pages that contains code to generate random numbers for the questions? if so how can I pass whether the user has answered the question right or wrong?
What I have did so far is the page in the first which contain the username and save it by using a session here is my code for the index.php page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Math Test</title>
</head>
<body style="background-color: #DDD">
<h1 style="font-size: 75px;" align="center">Math Test</h1>
<form method="POST" action="Math_Test.php">
<div style="text-align: center;">
<input type="text" name="Name" style="width: 500px; height: 100px; font-
size: 75px; color: blue;">
<br /><br />
<input type="submit" value="Begin Test" style="width: 250px auto;
height: 100px auto; font-size: 75px;">
</div>
</form>
</body>
</html>
and the code for the secondpage:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$Name = $_POST['Name'];
} else {
echo "<h1 align='center' style='margin-top: 250px;'>Sorry, You can't
access this page directly.<br /> Please go back ant try again or simply
click here!</h1>";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Math Test</title>
</head>
<body style="background-color: #DDD;">
<?php echo "<h1 align='center' style='font-size: 100px;'>Hi " . $Name .
"</h1>"; ?>
</body>
</html>
You can do something like this on your index page
<?php
// starts session
session_start();
// check if submit button was clicked
if ( isset($_POST['submit']) ) {
$name = htmlspecialchars(trim($_POST['name']));
// check if name was provided
if ( $name !== '' ) {
// store name in session
$_SESSION = array(
'answered_questions' => 0,
'correct_answers' => 0,
'wrong_answers' => 0,
'name' => $name
);
// redirect to second page
header('Location: second_page.php');
exit();
}
// set error if name was not provided
$error = 'Please provide your name';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Math Test</title>
</head>
<body style="background-color: #DDD">
<h1 style="font-size: 75px;" align="center">Math Test</h1>
<?php
// no name was provided so display the error message
if ( isset($error) ) {
echo '<p style="color: red">'. $error . '</p>'
}
?>
<form method="POST" action="">
<div style="text-align: center;">
<input type="text" name="name" style="width: 500px; height: 100px; font-
size: 75px; color: blue;">
<br /><br />
<input type="submit" name="submit" value="Begin Test" style="width: 250px auto;
height: 100px auto; font-size: 75px;">
</div>
</form>
</body>
</html>
And then on your second page you do something like so
<?php
// starts session
session_start();
// check if name key and value is not in the session
// if not there, then redirect back to the index.php page
if ( !isset($_SESSION['name']) ) {
header('Location: index.php');
exit();
}
if ( isset($_POST['submit']) ) {
$answer = (int)$_POST['answer'];
$expected_answer = $_SESSION['first'] * $_SESSION['second'];
$_SESSION['answered_questions'] += 1;
if ( $expected_answer == $answer ) {
$_SESSION['correct_answers'] += 1;
} else {
$_SESSION['wrong_answers'] += 1;
}
if ( $_SESSION['answered_questions'] == 10 ) {
// reset the session values from that page except name of course
header('Location: show_results.php');
exit();
}
$_SESSION['first'] = rand(1, 10); // random number between 1 and 20
$_SESSION['second'] = rand(1, 10);
} else {
$_SESSION['first'] = rand(1, 10); // random number between 1 and 20
$_SESSION['second'] = rand(1, 10);
}
// set the variable name to value in the session
$name = $_SESSION['name'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Math Test</title>
</head>
<body>
<?php var_dump($_SESSION); ?>
<h1>Hello, <?php echo $name; ?></h1>
<form method="POST" action="">
<p><?php
echo $_SESSION['first'] . ' * ' . $_SESSION['second'] . ' = ';
?><input type="text" name="answer" id="answer" required></p>
<p><input type="submit" name="submit"></p>
</form>
</body>
</html>
Then after if you want you can handle all the logic on the second page if you want as per #SamiKuhmonen advice
You don't need to do 10 pages for PHP to handle the math test that you are trying to do, instead, there is a technique called AJAX, which you can read about it from this URL:
https://www.tutorialspoint.com/php/php_and_ajax.htm
they have a very nice tutorial that deals with databases as well, which will help you in your case.
Give it a look and try to implement it, it will help you learn much faster.
Just for the record, PHP does have MVC frameworks, two are popular for developers,
Laravel: https://laravel.com/
Codeigniter: https://codeigniter.com/
Both supports MVC, I'll recommend you to go first with Codeigniter, once you feel that you are comfortable in PHP, switch to Laravel.
All the best, happy coding!

How to create and infinite while loop- php

basically I have a simple user page which I access after logging in via a login page. In the user page, there is my personal data displayed from my previous registration. And there is also a form where I can enter new information such as my favourite color and hobby (which I can insert multiple times). All the records goes into the DB succesfully. The problem is, everytime I submit a new data from the form in the user page, my personal data that are displayed in the same page dissapears. When I check the DB, nothing is lost, everything remains there. The only problem is, everytime I submit a data, my personal data which is displayed on the same page dissapears. BUt when I log in, it is there again. I suspect it might be due to non-infinite while looping everytime I press the submit button to insert new information.
How do I create an infinite while loop if this is the problem.??please help. If this is not the problem, please help me. tq so much. Below is partial of my script. tq.
<?php
//useracc-test.php
//start session
session_start();
// require 'lib/password.php';
require 'connect-test.php';
//retrieving part below
$userName= isset($_POST['username']) ? $_POST['username'] : '';
//$id= isset($_POST['id']);
$query = "SELECT id, name, username, telno FROM users WHERE username = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $userName);
$stmt->execute();
$res = $stmt->get_result();
?>
<html>
<head>
<style type="text/css">
#apDiv2 {
position: absolute;
left: 272px;
top: 148px;
width: 350px;
height: 338px;
z-index: 1;
}
#apDiv3 {
position: absolute;
left: 37px;
top: 379px;
width: 320px;
height: 157px;
z-index: 2;
}
</style>
<link href="SpryAssets/SpryTabbedPanels.css" rel="stylesheet" type="text/css">
<script src="SpryAssets/SpryTabbedPanels.js" type="text/javascript"></script>
</head>
<body>
<div id="apDiv3">
<div id="TabbedPanels1" class="TabbedPanels">
<ul class="TabbedPanelsTabGroup">
<li class="TabbedPanelsTab" tabindex="0">Tab 1</li>
<li class="TabbedPanelsTab" tabindex="0">Tab 2</li>
</ul>
<div class="TabbedPanelsContentGroup">
<div class="TabbedPanelsContent">
<p>
</p>
<?php while($row = $res->fetch_array()): ?>
<p><?php echo $row['id']; ?></p>
<p><?php echo $row['name']; ?></p>
<p><?php echo $row['username']; ?></p>
<p><?php echo $row['telno']; ?>
<?php endwhile; ?>
<?php
if(isset($_POST['submit']))
{
$id = $_POST['id'];
$name2 = $_POST['name2'];
$color2 = $_POST['color2'];
$hobby2 = $_POST['hobby2'];
$stmt = $conn->prepare("INSERT INTO useradvert (id,name2,color2,hobby2) VALUES (?,?,?,?)");
$stmt->bind_param("isss",$id,$name2,$color2,$hobby2);
$stmt->execute();
// $stmt->close();
// $conn->close();
}
?>
</p>
</div>
<div class="TabbedPanelsContent">
<form name="form2" method="post" action="useracc-test.php">
<p> </p>
<p>id :
<input type="text" name="id" id="id">
</p>
<p>name :
<input type="text" name="name2" id="name2">
</p>
<p>color2 :
<input type="text" name="color2" id="color2">
</p>
<p>hobby2 :
<input type="text" name="hobby2" id="hobby2">
</p>
<p>
<input type="submit" name="submit" id="submit" value="submit">
</p>
</form>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
</div>
</div>
</div>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p>
<script type="text/javascript">
var TabbedPanels1 = new Spry.Widget.TabbedPanels("TabbedPanels1");
</script>
</body>
</html>
When you submit a form, the browser refreshes the page with whatever the submission form returns. So after the script updates the database, it needs to display the new contents of your profile, just like the original profile page does.
A simple way to do this is for the script to send a redirect back to the page that displays the profile form. When it's done, it can do:
header("Location: profile.php");
Another option is to use AJAX to submit the changes, rather than normal HTTP form submission. You'll need to learn Javascript for this.
the code would be:
while (true) {
//loop body
}
BUT in PHP code stops executing after the max_execution_time expires (ini_set('max_execution_time', 300);). You don't want an infinite loop in PHP because you want output from PHP and that will only happen after the script finishes.
Infinite loops are good for embedded code where the machine has to keep running code like a robot or a clockradio.
tq to all for the sugesstions. I appreciate. I apologise if my language is not polite because english is my 3rd language at home. It is not my native language. This is how i speak. I already solved the problem. I just use "print" function and made minor modifications. and the data never disappear. problem solved.tq all.

how to change my web site's elements style dynamicly

In index.php file I first check if $_SESSION['user'] is set it would not show the login form and if not, the login form should be shown.
Here is my login form style
<style>
#login_form{visibility:hidden;}
</style>
And my PHP script is:
<?php
if(isset($_SESSION['user']))
dont show the login form;
else
show the login form;
?>
and the question is: how can I change the #login_form style to visible?
Why not adding an inline style (perhaps a class would be even better) when the user is logged in?
<form style="<?php if(isset($_SESSION['user'])) { echo 'visibility: hidden;';}?>">
<!-- Rest of the form -->
</form>
Or even better, print the form only when is logged in (so visitors can't force the browser to display the form):
<?php if(isset($_SESSION['user'])) { ?>
<form>
<!-- Rest of the form -->
</form>
<?php } ?>
Create a CSS class:
.invisible {
visibility: hidden;
}
Then apply it when your user is already logged in:
<form class="<?=isset($_SESSION['user']) ? 'invisible' : ''?>">
You can have it directly in the div that holds the form, like this:
<div style="<?if(isset($_SESSION['user'])){echo 'display:block'}else{echo 'display:none'}?>">
...Form code
</div>

How do I pass a mysql record ID from one page to another?

I have a search form that when you click on the more info link for a record will open a new window for that record to display additional information and I use <a href=more_info.php?id=$rows[id]>to pass the id to the next page and that works great.
On that next page I have a button that pops up a small browser window using this <a href="#" onclick="window.open('signature_pad.html', 'newwindow', 'width=500, height=200'); return false;"> this windows pops up with a signature pad.
What I need to do is pass that record ID from the second window to the popup window so when the customer signs the signature pad their signature is posted into the correct record.
so here is the code for the 2nd and popup pages: (I only posted the code for the button section of the 2nd page to save space as the code for that page is fairly long and only the button portion pertains to this question)
<table class="auto-style16" style="width: 615px; height: 28px;">
<td style="width: 435px; height: 22px;" class="auto-style7">
**<input type="button" value="Get Signature" />**
And the popup window
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Signature Pad</title>
<!-- The Signature Pad -->
<script type ="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="signature-pad.js"></script>
</head>
<body>
<center>
<fieldset style="width: 435px">
<br/>
<br/>
<div id="signaturePad" style="border: 1px solid #ccc; height: 55px; width: 400px;"></div>
<br/><br/><br/>
<button id="clearSig" type="button">Clear Signature</button>
<button id="saveSig" type="button">Save Signature</button>
<div id="imgData"></div>
<br/>
</fieldset>
</center>
<div id="debug"></div>
</body>
</html>
This is the doesn't work page you have:
more_info.php
<p>I have some text here and am just a HTML page saved as .php</p>
<table class="auto-style16" style="width: 615px; height: 28px;">
<td style="width: 435px; height: 22px;" class="auto-style7">
**<input type="button" value="Get Signature" />**
This is how it should be:
more_info.php
<?php
$myId = $_GET['id'];
?>
<p>I have some text here and am a HTML with PHP page saved as .php</p>
<table class="auto-style16" style="width: 615px; height: 28px;">
<td style="width: 435px; height: 22px;" class="auto-style7">
**<input type="button" value="Get Signature" />**
On my above example, I am making use of php for 2 things, first I received the query string id and save it into my variable $myId then I print the variable to the HTML location it should for the window.open. You can also print the $_GET directly but I prefer not to in case I need to further do things to the variable like sanitization, etc.
More information on $_GET
To carry a variable across your PHP application you can use either GET / POST (hidden option) or PHP Session, or use your database
Since you need to save variables across your web app, you have to incorporte sessions (with or w/o database).
On top of each page add this:
session_start(); and this will allow your web app server track each user.
Then assign any vars to session $_SESSION['user']='Bob';
Then, when you get familiar with sessions, you can just keep track of user id and keep the rest in the database
Check this article and go from there

Categories