How to add delay in php - javascript

for account verification process when user click on verfication link . He /She instantly redirects to dashboard . But I want to give a confirmation message that his/her account has been verified for some seconds.
here is my code
<?PHP
require_once 'include/Functions.php';
$db = new DB_Functions();
if(isset($_GET['username'])&&isset($_GET['q']))
{
$username= $_GET['username'];
$hash= $_GET['q'];
$salt = "498#2D83B631%3800EBD!801600D*7E3CC13";
$resetkey = hash('sha512', $salt.$username);
if($hash==$resetkey){
$user = $db->activateAccount($username);
if ($user != false) {
// user is found
echo '<script>';
echo 'document.getElementById("result_status").innerHTML = "<strong>Congratulations! Your Account has been verified .</strong>"';
echo '</script>';
$passwords=$db->getPasswordFromUsername($username);
$users = $db->loginUserWithMdfPassword($username, $passwords);
if ($users != false) {
// password is found
$properlyLogged=true;
if($properlyLogged) {
// season for storing data start here
session_start();
$_SESSION['username']=$username;
header('Location: http://localhost/mywebsite/dashboard.php');
exit();
// season for storing data end here
}}
}
}else {
echo '<script>';
echo 'document.getElementById("result_status").innerHTML = "<strong>Session has been expired.</strong>"';
echo '</script>';
}}
?>

sleep wont work for what you want.
you're redirecting your user using header('location:...'); and you cannot modify header information after you've outputted data (ie - showed message to user).
you'll have to preform the redirect using javascript with a setTimeout
<?PHP
require_once 'include/Functions.php';
$db = new DB_Functions();
if(isset($_GET['username'])&&isset($_GET['q']))
{
$username= $_GET['username'];
$hash= $_GET['q'];
$salt = "498#2D83B631%3800EBD!801600D*7E3CC13";
$resetkey = hash('sha512', $salt.$username);
if($hash==$resetkey){
$user = $db->activateAccount($username);
if ($user != false) {
// user is found
echo '<script>';
echo 'document.getElementById("result_status").innerHTML = "<strong>Congratulations! Your Account has been verified .</strong>";';
// set timeout for 3 seconds - then redirect
echo "setTimout(function(){window.location.href = 'http://localhost/mywebsite/dashboard.php';},3000)"
echo '</script>';
$passwords=$db->getPasswordFromUsername($username);
$users = $db->loginUserWithMdfPassword($username, $passwords);
if ($users != false) {
// password is found
$properlyLogged=true;
if($properlyLogged) {
// season for storing data start here
session_start();
$_SESSION['username']=$username;
//comment out header redirect
//header('Location: http://localhost/mywebsite/dashboard.php');
exit();
// season for storing data end here
}}

This would probably be easier with a JavaScript approach.
instead of header('Location: http://localhost/mywebsite/dashboard.php');
put
echo '<script>setTimeout(function(){window.location.href = "http://localhost/mywebsite/dashboard.php"}, 5 * 1000);</script>'
This will wait for X * 1000 milliseconds (in my example, 5 seconds) and then redirect to the destination.

Related

How to show alert box after successful or not data deletion in mssql

I want to show JavaScript alert after successful or not data deletion in MSSQL. How to do this? I have written this code but it shows only the message=success part alert everytime, even when the deletion dont work becasue of errors like "conflict with reference(foreign_key)" So when i click on this link.
echo "<a class='activater' href='ma_QualiOverviewloeschen.php?TestaufstellungID=".$row['TestaufstellungID'] ."&QualiID=".$row['QualiID'] ."' title='Qualitest löschen' data-toggle='tooltip' onclick='confirm_delete()'> <span class='glyphicon glyphicon-trash'></span></a>";
It calls the following php Page, which handle the SQL Part:
$QualiDelete =("DELETE FROM MyDB.dbo.Testaufstellung WHERE MyDB.dbo.Testaufstellung.TestaufstellungID = :TestaufstellungID");
$QualiDelete .=("DELETE FROM MyDB.dbo.AllgemeineAngaben WHERE MyDB.dbo.AllgemeineAngaben.QualiID = :QualiID");
$sth = $connection->prepare($QualiDelete);
$sth->execute(array(':TestaufstellungID' => $TestaufstellungID, ':QualiID:' => $QualiID));
if($sth)
{
header("location: ma_QualiOverview.php?message=success");
}
else
{
echo sqlsrv_errors();
header("location: ma_QualiOverview.php?message=failed");
}
$connection = null;
Back to the main page where the link is clicked the following ifelseconsider on messageshould Show me the right alert.
<?php
if($_GET['message']=='success'){
echo '<script language="javascript">';
echo 'alert("Erfolgreich gelöscht.");';
echo '</script>';
} elseif($_GET['message']=='failed'){
echo '<script language="javascript">';
echo 'alert("Nicht gelöscht, da Quali "ongoing" ist.");';
echo '</script>';
}
?>
What do i miss?
$sth will never be falsy, you have to check the return value of $sth->execute
Also, you should echo the errors after sending out the header.
Since $sth is always defined, you always get the success result
See the modified code here
$QualiDelete =("DELETE FROM MyDB.dbo.Testaufstellung WHERE MyDB.dbo.Testaufstellung.TestaufstellungID = :TestaufstellungID");
$QualiDelete .=("DELETE FROM MyDB.dbo.AllgemeineAngaben WHERE MyDB.dbo.AllgemeineAngaben.QualiID = :QualiID");
$sth = $connection->prepare($QualiDelete);//Check the value returned instead of $sth
$result = $sth->execute(array(':TestaufstellungID' => $TestaufstellungID, ':QualiID:' => $QualiID));
if($result )
{
header("location: ma_QualiOverview.php?message=success");
}
else
{
header("location: ma_QualiOverview.php?message=failed");
echo sqlsrv_errors();//Echo must be after header
}
$connection = null;

How to manage Php sessions in same page in php

I have a Index page in Php and a login link. When user login to the site then i want to redirect to the same page (index.php). At the place of login link I want to show the username of the user or client. I have a php login code like this
$error = '';
if (isset($_POST['login']) && !empty($_POST['email'])
&& !empty($_POST['password'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$sel_user = "select * from customer where email='$email' AND password='$password'";
$run_user = mysql_query($sel_user);
$check_user = mysql_num_rows($run_user);
if($check_user == 1){
$_SESSION['email']=$email;
echo "<script>window.open('userinfo.php','_self')</script>";
}
else {
$error = 'Invalid username or password';
}
}
in this code page is redirecting to another page after login but i want to redirect it to same page as index.php. And add links like my account and logout links instead of login link in index.php. I have a Php sessions page code like this
if(!isset($_SESSION))
{
session_start();
}
$login_session=$_SESSION['email'];
if(!isset($_SESSION['email']))
{
// not logged in
header('Location: login.php');
exit();
}
How can i make this for example like flipkart.com. Please help me.
You can do one thing:
Go for the code that you have already written for the login, i.e.,
$error = '';
if (isset($_POST['login']) && !empty($_POST['email'])
&& !empty($_POST['password'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$sel_user = "select * from customer where email='$email' AND password='$password'";
$run_user = mysql_query($sel_user);
$check_user = mysql_num_rows($run_user);
if($check_user == 1){
$_SESSION['email']=$email;
echo "<script>window.open('userinfo.php','_self')</script>";
}
else {
$error = 'Invalid username or password';
}
}
After this you do a check of the session variable
if(!isset($_SESSION))
{
session_start();
}
$login_session=$_SESSION['email'];
if(!isset($_SESSION['email']))
{
// not logged in
header('Location: index.php'); //change the redirect page to index.php
//now customize the menu accoringly
echo "<nav class='your-class'>";
echo "<li>";
echo "<ul>Login</ul>";
//Some more menus
echo "</nav>";
exit();
}
else
{
header('Location: index.php'); //now configure the menu accordingly
//now customize the menu accoringly on login
echo "<nav class='your-class'>";
echo "<li>";
echo "<ul>My Account</ul>";
//Some more menus
echo "<ul>Logout</ul>";
echo "</nav>";
}
But as far as I know this is somewhat tiresome and please try to avoid the queries like this. Use PDO instead. Thanks.
Try this
header('location:'.$_SERVER['PHP_SELF']);
instead of
echo "<script>window.open('userinfo.php','_self')</script>";
and for manage links
<ul>
<?php if(isset($_SESSION['email'])){ ?>
<li><a href="logout.php" >Logout</a></li>
<?php }else{ ?>
<li><a href="index.php" >Home</a></li>
<?php }?>
</ul>

Popup alert script in a php file [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to let a user log in. If the password and username is wrong, I want a popup to appear alerting the user on the error. When they close the alert, it goes back to index.php which is back to login screen.
But when it is wrong password/username, ends up going back to index.php without any popup messages first. My browser setting is not blocking any popups. Can I know what I'm doing wrong please.
<?php
if($login == true){
//Do login process
//this portion works as long as correct username and password
}
else{
echo '<script language="javascript">alert("Please enter valid username and password");</script>';
header("location:index.php");
}
?>
//login.php
<?php
$username = "exampleuser";
$password = "examplepass";
$host = "localhost";
$dbHandle = mysql_connect($host, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("database_name", $dbHandle);
$myUserName = $_POST['user'];
$myPassword = $_POST['pass'];
if(ctype_alnum($myUserName) && ctype_alnum($myPassword)){
$query1 = "SELECT * FROM users WHERE username='$myUserName'";
$result1 = mysql_query($query1);
$count1 = mysql_num_rows($result1);
if($count1 == 1){
$query2 = "SELECT password FROM users WHERE username='$myUserName'";
$result2 = mysql_query($query2);
$row = mysql_fetch_array($result2, MYSQL_ASSOC);
$pass = $row['password'];
if(password_verify($myPassword, $pass)){
$seconds = 120 + time();
setcookie(loggedIn, date("F js - g:i a"), $seconds);
header("location:mysite.php");
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
?>
If you send headers to php it goes directly on index.php after the page goes in your condition.
If you try this code:
<?php
if($login == true){
//Do login process
//this portion works as long as correct username and password
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
you will see that your code is correct. You need to track an event on popup closing to redirect to index.php via ajax or via http redirect.
EDIT 1:
Here you have a complete page with pdo. This is not the best way to do the job but it works. As you will see in the comments you have to avoid xss attacks and you should change database structure saving password hashed and salt to hide the users' clear password.
Here's the code.
<?php
//login.php
//connection via PDO
try{
$pdo = new PDO ('mysql:host=localhost; dbname=database_name', 'exampleuser' , 'examplepass', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//alert errors and warnings
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
exit('Database Error.');
}
//prepared statements sanitize input binding parameters, for you but you can use some libraries to prevent sql injection
$myUserName = trim(filter_var($_POST['user'], FILTER_SANITIZE_STRING));;
$myPassword = trim(filter_var($_POST['pass'], FILTER_SANITIZE_STRING));;
if(!empty($myUserName) && ctype_alnum($myUserName) && !empty($myPassword) && ctype_alnum($myPassword)){
$query1 = $pdo->prepare("SELECT password FROM users WHERE username = :username_param");
//bind parameter avoiding principal injection (pdo does not cover xss attacks, avoid it with other methods)
$query1->bindParam("username_param", $myUserName);
$result = $query1->fetch();
// or you can do $result = $query1->fetchColumn(); to get directly string instead of array
if($result['password']){
//you should use password_verify() if you have an hash stored in database, you should not save password in database.
//please google about best practice storing password, it's full of beautiful guides
//bad practice but will do the work
if($myPassword == $result){
$seconds = 120 + time();
setcookie('loggedIn', date("F js - g:i a"), $seconds);
header("location:mysite.php");
}else{
printAlert("Password incorrect");
}
}else{
printAlert("Username not valid");
}
}
else{
printAlert("Invalid data");
}
function printAlert($text){
echo "<script language='javascript'>
alert('$text');
window.location.href = 'http://index.php';
</script>";
die();
}
?>

php login form pass vars

i have a page login
in page have html form with textboxes and submit button
and in top of page i have PHP code thet chacke if name and password in database
if name and password in database page go to new page and pass the name and password to next page
i can do it with get metod like the vars in the URL
but i want to pass and go to new page with Post metod
how i can do it??
pleas help me with code....
in code html :
form name="frmlogin"action="<?= $_SERVER['PHP_SELF'] ?>" method="post" >
and in top of the page have PHP code:
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["name"];
$password = $_POST["password"]; if ($name == '' || $password == '') {
$msg = "You must enter all fields";
} else {
$sql = "SELECT * FROM tbluser WHERE fldUsername = '$name' AND fldPass = '$password'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
/*header('Location: YOUR_LOCATION');
exit;*/
$msg = "Username and password match";
echo '<script type="text/javascript">
window.location.href = "smartphon100.php?name='. $name .'&password='. $password .'";
}
if (mysql_num_rows($query) <= 0) {
$msg = "Username and password do not match";
}
}
}
help me to change the javascript window.location to post metod
You can go for php redirect also.
header('location:smartphon100.php?name='. $name .'&password='. $password) ;
BTW: you are passing password in browser?
If I understand correctly, you're trying to redirect a user after successfully logging in.
I see that your current code attempts to redirect using Javascript, the issue seems to be with the quotes on the value you tried to enter.
Try to change this line:
window.location.href = "smartphon100.php?name='. $name .'&password='. $password .'";
to this:
window.location.href = "smartphon100.php?name='.$name.'&password='. $password";
Overall you should read about security as the code you presented is very vulnerable.
PHP: SQL Injection - Manual
If you're trying to pass the values to another page in a POST method using Javascript, you could take a look at this answer:
JavaScript post request like a form submit
Although as I don't see a reason for posting the values more than once,
I recommend you to read about PHP sessions, cookies, and encryption, which allow you to store values that you can use across the website securely.
A simple example to using session:
<?php
//Starts the session, you need to use this line in every PHP file that'll need to access session variables
session_start();
$_SESSION['user'] = "Donny"; //Storing a user name
?>
A simple example of session use with your code:
Foo.php
session_start();
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["name"];
$password = $_POST["password"]; if ($name == '' || $password == '') {
$msg = "You must enter all fields";
} else {
$sql = "SELECT * FROM tbluser WHERE fldUsername = '$name' AND fldPass = '$password'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
$_SESSION['user'] = $name;
$_SESSION['pass'] = $password;
$msg = "Username and password match";
echo '<script type="text/javascript">window.location.href = "smartphon100.php";</script>';
}
if (mysql_num_rows($query) <= 0) {
$msg = "Username and password do not match";
}
}
}
Bar.php
<?php
session_start();
//Accessing the values:
echo $_SESSION['user'];
echo $_SESSION['pass'];
?>
NOTE:
It's not good to store values like that as again, they're not secure, please read about hashing passwords.
PHP: Password Hashing

SESSION value not passing after redirection to the thank you page

I am trying to pass $email field to thank you page which appears after redirection once user submits the enquiry form.
Its a 2 step enquiry form with thank you page being last.
It seems like the SESSION is live on thank you page however the values are lost. I'd like to get $email field posted on the thank you page to an iframe. Please let me know where exactly the session id is going wrong?
Here are the codes:
Step 1: Small Enquiry form
<?php
error_reporting(0);
session_start();
require_once('validation.class.php');
if(isset($_REQUEST['btnSubmit']) == 'Next'){
$obj = new validation();
$obj->add_fields(trim($_POST['txt_fname']), 'req', 'Enter your first name.');
$obj->add_fields(trim($_POST['txt_contact']), 'req', 'Enter phone number.');
$obj->add_fields(trim($_POST['txt_finamount']), 'req', 'Enter the amount.');
$obj->add_fields(trim($_POST['sel_loantype']), 'req', 'Please select vehicle type.');
$error = $obj->validate();
if($error){
$error_msg = "".$error."";
$_SESSION['error_msgs'] = $error_msg;
header("location:".$_SERVER['HTTP_REFERER']."");
exit();
}else{
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit();
/*$fname = trim($_REQUEST["txt_fname"]);
$surname = trim($_REQUEST["txt_surname"]);
$phone = trim($_REQUEST["txt_contact"]);
$finamount = trim($_REQUEST['txt_finamount']);
$sel_loantype = trim($_REQUEST['sel_loantype']);
$message = '<html><body>';
$message .= '<table rules="all" width="100%" style="border:1px solid #666;" cellpadding="10">';
$message .= "<tr><td><strong>First Name:</strong> </td><td>" . strip_tags($fname) . "</td></tr>";
if($surname != ''){
$message .= "<tr><td><strong>Surname:</strong> </td><td>" . strip_tags($surname) . "</td></tr>";
}
$message .= "<tr><td><strong>Phone:</strong> </td><td>" . strip_tags($phone) . "</td></tr>";
$message .= "<tr><td><strong>Amount to Finance:</strong> </td><td>" . strip_tags($finamount) . "</td></tr>";
$message .= "<tr><td><strong>Loan Type:</strong> </td><td>" . strip_tags($sel_loantype) . "</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
$ToEmail = 'testemail#gmail.com';
$EmailSubject = "GET A QUICK QUOTE from ".strip_tags($fname);
$mailheader = "From: ".strip_tags($fname)."\r\n";
//$mailheader .= "Reply-To: ".$_REQUEST["txt_email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = $message;
if(#mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader)){
$_SESSION['sucess'] = "Your message has been sent successfully.";
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit;
}else{
$_SESSION['sucess'] = "Sorry! Your message has not been sent.";
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit;
}*/
}
}
?>
Step 2 Code:
<?php
error_reporting(0);
session_start();
require_once('validation.class.php');
?>
<script type="text/javascript">
function submitToCRM()
{
$.ajax({
type: 'POST',
url: 'http://test.com.au/quick-quote/car-finance/quickquote-one.php',
data: $("#applynowform").serialize(),
beforeSend: function () {
$("#loadingimg").show();
},
success: function (){
//alert(data);
window.location.href = "http://www.test.com.au/thank-you";
}
});
Step 3: The above page sends data to quickquote-one.php form processing script which has below code.
<?php
if(!isset($_SESSION))
{
session_start();
}
$_SESSION['user_email'] = $_POST['email'];
Step 4: thank you page (this page has below code)
<?php
if(!isset($_SESSION))
{
session_start();
$_SESSION['user_email'] = $_POST['email'];
echo $_SESSION['user_email'];
}
?>
Add
session_set_cookie_params(0);
before your
session_start();
You can also pass the SID (session ID) between the pages using the URL to make sure it isn't lost in transition.
url: 'http://test.com.au/quick-quote/car-finance/quickquote-one.php?<?php echo htmlspecialchars(SID); ?>',
and
window.location.href = "http://www.test.com.au/thank-you?<?php echo htmlspecialchars(SID); ?>";
You're losing the session because you're sending the browser to the next URL without a relative path but instead a fully-qualified domain. This is a security measure to prevent session IDs from being inadvertently sent to the wrong server.
Another small solution would be to use relative paths like /page.php instead of http://www.domain.com/page.php
Read more here (PHP Manual)
In step 4 your setting
$_SESSION['user_email']
again. If the form has refreshed then your post is empty and you are overwriting the session with an empty value. Try removing it from step 4 and just leave.
<?php
if(isset($_SESSION['user_email']) && !empty($_SESSION['user_email']))
{
echo $_SESSION['user_email'];
}
?>
Also you are trying to echo your session email value IF the session is NOT set. I don't think that will work if the session is actually set..
i think it is better to start a session in one page and access all the session variables throghout if all the pages are connected to eachother. it will be some thing like we create login page. When user logs in capture alll the required values in a session and can be accessed through out the application even after refresh.
$query = "SELECT Useid,UserName,AccountStatus, FullName FROM Users WHERE UserName = :UserName";
from this query we can get the session variables easily.
if($login_ok)
{
//for last visit
$Month = 2592000 + time();
//this adds 30 days to the current time
setcookie(AboutVisit, date("F jS - g:i a"), $Month);
//last visit ends here.
$_SESSION['user'] = $row['UserName'];
$_SESSION['userid'] = $row['Useid'];
$_SESSION['fullname'] = $row['FullName'];
}
where ever you need th variable you can use like this
$username=$_SESION['user'];
I think this will work instead of startign session every time in each page.
Hope it helps

Categories

Resources