I have a login page called signin.php where a user can enter an email and password. On clicking submit button, page directs to connection_validate.php. This page validates the user entered data with database. If it's a registered user, the page directs to calendar.php. If the entered data is incorrect, it should redirect to signin.php. If the entered data is incorrect, I have placed cookie like this:
//action to be done if e mail id and password matches with database records
if(mysql_num_rows($result)>0)
{
header('location:calendar.php');
}
//action to be done if e mail id and password does not matches with database records
else
{
setcookie('message','incorrect login data');
header('location:signin.php');
}
In signin.php, I have written the code for displaying an alert if login information is incorrect like this:
<?php
include("include/minfooter.php");
if(isset($_COOKIE["message"]))
{
if(!($_COOKIE["message"]==" "))
{
echo "<script>
alert('Incorrect login information');
</script>";
setcookie("message"," ",time()-3600);
}
}
?>
My issue is that alert is displaying each time when I load the signin page if I have entered a error login data once. If I press the back button from the calendar.php to signin.php also, alert starts showing. I understood that the problem is with cookie. Cookie has not been removed. How can I solve this issue?
Update your signin.php as follows
<?php
include("include/minfooter.php");
if (isset($_COOKIE["message"]))
{
echo "<script>
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
var msg = '" . $_COOKIE["message"] . "';
if (msg != '')
alert('Incorrect login information');
delete_cookie('message');
</script>";
}
?>
If you are using a session you can use the $_SESSION variable instead of a cookie value. Also you can not use setcookie() AFTER you have output content since setcookie() will send an HTTP header which must be sent prior to any content being sent.
session_start();
//action to be done if email id and password matches with database records
if (mysql_num_rows($result) > 0)
{
header('Location: calendar.php');
exit;
}
//action to be done if email id and password does not matches with database records
else
{
$_SESSION['message'] = 'incorrect login data';
header('Location: signin.php');
exit;
}
Then:
<?php
session_start();
include("include/minfooter.php");
if (!empty($_SESSION['message']))
{
echo "<script>alert('" . $_SESSION["message"] . "');</script>";
$_SESSION['message'] = '';
}
?>
Ok maybe is better to use session for that use a index ['messages'] on the $_SESSION array, then cleanup, the cookie should be used when you want reference some info after the user get out of your page. I made your code on using cookies, but consider using session:
<?php include("include/minfooter.php");
if(isset($_COOKIE["message"]) && !empty($_COOKIE["message"])
{
echo "<script>
var msg = '<?php echo $_COOKIE["message"];?>';
if (msg != "")
alert('Incorrect login information');
</script>";
unset($_COOKIE["message"]);
}
?>
Related
I need a little help here. I have a page profile.php and a option to delete the accound :
// DELETE THE ACCOUNT !!
$_SESSION["delacc"] = FALSE;
if (isset ($_POST ['deleteaccount'])) {
$deleteaccount = $_POST['deleteaccount'];
$delacc="DELETE FROM users WHERE username='$username'";
$resdelacc = mysqli_query($con,$delacc);
if ($resdelacc) {
header('Location: index.php');
$_SESSION["delacc"] = TRUE;
unset($_SESSION['username']);
} else {
echo "ERROR !!! Something were wrong !!";
}
}
the problem is in if ($resdelacc). If this is true, result that the account was deleted, unset session username (logout) and after this I want to redirect the page to index.php where I have the code :
if(isset($_SESSION["delacc"])) {
if($_SESSION["delacc"] == TRUE) {
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
$_SESSION['delacc'] = FALSE;
}
}
My only problem is that this line " header('Location: index.php');" (from profile.php) don't run in any case. When the user click the button "DELETE ACCOUNT", the page remain profil.php, then, if do refresh or access another page, is redirected and appear as guest.
Very easy .. The reason is after in the resulted output page you can't redirect. so you've prepare it to be redirected after some seconds enough for user to read the result message.
Like this:
if($_SESSION["delacc"] == TRUE) {
$_SESSION['delacc'] = FALSE;
echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="7;url=http://'.$_SERVER['HTTP_HOST'].'/index.html"/>';
echo "</head><body>";
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
}
that change will redirect to the index.html after 7 seconds.
PS. The Generated HTML result page make it starts by this code after the POST handling direct. (before any echo) because echo will start generating the results page and the only logical place to redirect is inside the HEADER before any BODY elements
<meta http-equiv="refresh" content="0";url="/index.php"/>
The redirect (url) don't run for index.php because I have another redirect before :
if(isset($_SESSION['username'])==FALSE) {
header('Location: login.php');
}
but is ok, I put the message "DELETED SUCCESFULLY" in login.php and deleted from index.php . I set content=0, because after deleted, the user will be restricted for page profile.php and need to change immediatelly to another. Due of the verification of SESSION['username'] which can return profile.php, I can not redirect to another page ... is a conflict. I need a little to think better this code with redirects, I know can solve it better :D thanks for explanations and help
I need to be able to orientate with a php code that communicates with data from a mysql database, this file is called "validate.php". Its main functions are to verify that there are no empty fields at the time of login, and assign a profile if a user has value 1 and another profile when the value is 0 in the records of the table "users"
The idea is that "validate.php" check the user and direct it to a page according to their profile, but I can not do that.
My code is:
<?php
require('access_db.php');
session_start();
if(isset($_POST['send'])) { // We verify that the form data has been sent
//We verify that the user_name and the user_pass fields are not empty
if(empty($_POST['user_name']) || empty($_POST['user_pass'])) {
echo"
<script>
alert('Please enter your username and password correctly ');
location.replace('login.php');
</script>
";
}else {
//"Clean" the form fields of possible malicious code
$user_name = mysqli_real_escape_string($link,trim($_POST['user_name']));
$user_pass = mysqli_real_escape_string($link,trim($_POST['user_pass']));
// We verify that the data entered in the form match those of the DB
$query=mysqli_query($link,"select user_id,user_name,user_admin FROM users WHERE user_name='".$user_name."' and user_pass ='".$user_pass."'");
$row = mysqli_fetch_array($query);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row["user_name"];
$_SESSION['user_admin'] = $row["user_admin"];
if($_SESSION['user_admin']==1){
echo "dashboard.php";
}else{
echo "dashboard2.php";
}
{
}
}else{
header("Location: login.php");
}?>
My main problem is here:
if($_SESSION['user_admin']==1){
echo "dashboard.php";
}else{
echo "dashboard2.php";
}
When I login with my admin user in my page "login.php" you should check the information and go to a page according to your profile, only appears in the browser "http://localhost/proyect/validate.php" and the text "dashboard" on the page, But, if I write in the browser "http://localhost/proyect/dashboard.php" load the page with all the information.
I do not know what I'm doing wrong.
Someone can help me, I'll be very grateful, I've been on this for days.
Thanks.
Don't print, try this instead:
if($_SESSION['user_admin']==1){
header('location:dashboard.php');
exit;
}else{
header('location:dashboard2.php');
exit;
}
Thanks for the suggestion Magnus Eriksson
you need to redirect not echo out the contents of the php file
and also do check for { as there are extra ones
if($_SESSION['user_admin']==1){
header("Location: dashboard.php");
}else{
header("Location: dashboard2.php");
}
Hey guys am trying to determine if two minutes are over in php..I have an input box and a php script that checks if 5 seconds are over or not..What i need is when the user inserts the correct value i just want to display password is correct and you are now logged in with the existing token.
After 5 seconds i want to display the message like you cant login with this token id anymore.
But the problem is everytime am geting the message you are now logged in with the existing token after 5 seconds. its not showing up the message you cant login .....
The code i have used..
<?php
session_start();
$_SESSION['logintime'] = time();
$name = $_POST['fname'];
$tokenvalue = 'sample';
if($name != $tokenvalue) {
echo 'the token is incorrect<br>';
} else {
echo "the token is correct<br>";
}
if (time() > $_SESSION['logintime'] + 5) {
echo 'you cant login with this token id anymore<br>';
} else {
echo 'you are now logged in with the existing token';
}
Hope can i diplay the message you cant login with this token id anymore after 5 seconds ??..
Where am i doing wrong ??..Any help would be apreciated..Thanx
A PHP script is executed by the server. As soon as you see something in your browser, there is no action on the server anymore (at least in this script).
To accomplish what you are trying here, you need to use AJAX (asynchronous javascript and xml).
There are some things that are eglible in this case:
Hardcoded request after x-seconds with javascript (I would recommend using jQuery for this):
setTimeout(function(){$('#message').load('myScript.php');}, 5000);
You could use SSE (Sever-Sent Events), where you open a persistent connection to the server and push the event after x-seconds. There are good tutorials on HTML5rocks and MDN.
You could use only javascript, because the message will only be on the client side - you need to validate the time anyways, before you save a user input. For this you could also use jQuery:
setTimeout(function(){$('#message').html('you cant login with this token id anymore<br>');}, 5000);
Update: there are some things strange in your code (I will try to explain what I mean using comments):
<?php
session_start();
// you set the login, before you validate the users input
$_SESSION['logintime'] = time();
// thats okay, but actually not really necessary
$name = $_POST['fname'];
// thats okay for a test only :)
$tokenvalue = 'sample';
if($name != $tokenvalue) {
// you should use exit() or die() when the login fails to end the script
echo 'the token is incorrect<br>';
} else {
// first you use the word "token" now "password"
echo "the password is correct<br>";
}
if (time() > $_SESSION['logintime'] + 5) {
echo 'you cant login with this token id anymore<br>';
} else {
echo 'you are now logged in with the existing token';
}
Update2: Maybe this helps you - it does what you described in the question:
<html>
<head>
</head>
<body>
<?php
$tokenvalue = 'sample';
if(isset($_POST['token'])){
if($_POST['token'] === $tokenvalue) {
echo '<div id="success">The password is correct.<br>You are now logged in with the existing token.</div>';
}
}
?>
<form action="" method="post">
Token: <input type="text" name="token"><br>
<input type="submit" value="Submit">
</form>
<script>
if(typeof(document.getElementById('success')) != 'undefined') {
setTimeout(function(){document.getElementById('success').innerHTML = "You can't login with this token anymore."},5000);
}
</script>
</body>
</html>
this is my php page.. if anyone directly visits this page it will read session if the value is not set then value and redirect to page.html. else it will print some message. this is working on local host but not on live server.
<?php
session_start();
$name = $_SESSION['team']; //a value stored in session which i used on this page
if (($_SESSION["abc"] !== 'good')) {
header('Location: http://www.abc.com/page.html');
}
else{
echo $name. 'you have completed register process part one you may continue!';
}
?>
Use This
<?php
session_start();
$name = $_SESSION['team']; //a value stored in session which i used on this page
if (($_SESSION["abc"] !== 'good')) {
?>
<script>
window.location = "http://www.abcd.com/page.html";
</script>
<?php
}
else{
echo $name. 'you have completed register process part one you may continue!';
}
?>
I have a simple coding problem. I try to create a page with a textbox and a share button.
When the user clicks the share button the text in the textbox get inserted as string into the database table named "posts".
I use the following code.
<?php
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
else
echo "<script type='text/javascript'>alert('some error')</script>";
}
else
{
?>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
Status : <input type = "text" name ="status">
<input type = "submit" name ="share">
</form>
<?php
}
This solution works fine but there is a problem when the user refreshes the page. The browser will show a message window asking for resend the information, which will submit the post to the table again. Then the same entry is in the table twice.
I want the user to stay on the same page after submitting. But a page refresh should not show the message window or send the information again.
Thanks in advance!
Redirect the user after he shares, use redirect
header('Location: whatever.php');
exit;
Use this :
<?php
if(isset($_POST['share'])) {
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res) {
?>
<script type='text/javascript'>alert('Posted successfully')</script>
<?php
header('Location: whatever.php');
exit;
} else {
?>
<script type='text/javascript'>alert('some error')</script>
<?php
header('Location: whatever.php');
exit;
}
}
?>
And btw better don't alert the users using javascript
AND DO USE BRACES AROUND IF ELSE
P.S : You Can Also Redirect An User Using JavaScript window.location
Header Reference
It's called "redirect-after-post": After you received the post request and did something useful with it, you redirect the user (usually) back to theire own post, or whatever.
You can try doing redirect just after your logic saving the post is done.
header("location: $my_page");
exit();
Set variable $your_page with the name of page which contains your code
$my_page = 'yourpage.php';
This should work:
$my_page = 'your_page.php'
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
{
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
header("location: $my_page");
exit();
}
else
{
echo "<script type='text/javascript'>alert('some error')</script>";
header("location: $my_page");
exit();
}
}
Right after you have finished inserting your query and everything, change to another page using:
<?php
header('Location: /path/to/yourotherpage.php');
exit();
?>
What this does, is it is a redirect to another page, which removes all POST data from the browser's 'memory' of the page.
On that page, you write something like 'Your stuff has been submitted and recorded', whatever you want, your choice.
If your user refreshes on that page, nothing will be inserted at all.
That should work.