So I've got this form where users signs his ass up. When the user filled in all the details, he clicks on the submit button. An Ajax request submits the form and puts all the details in the database. If that has happen without any errors, a hidden div with two (payments) buttons opens up. After clicking on the iDeal or PayPal button, colorbox opens up and show the 'overview-page'. Now I'd like to show the users information from the database via $_SESSION['user_id']. But somehow, I'm not storing the session orso as the 'overview-page' is empty.
I'm not sure what I'm missing, any heads up would be awesome!
This is the form:
<div class="content main container" id="goShowOrderForm">
<div class="content main box">
<div id="udidOrderForm" class="order form">
<form action="post" id="orderForm" name="form">
<label for="email">Email</label>
<input type="email" class="input-fullwidth" name="email">
<div class="two-column">
<label for="password">Password</label>
<input type="password" name="password">
</div>
<div class="two-column right">
<label for="repassword">Confirm Password</label>
<input type="password" name="re_password">
</div>
<input type="hidden" name="token" value="<?php echo $_SESSION['guest_token'] ?>">
</form>
<div class="orderFormActions">
<input type="submit" class="button darkblue order" name="submitNewStep" id="submitNewStep" value="Nu afrekenen">
<div class="button red cancel" id="cancelUdidOrder">Afbreken</div>
</div>
</div>
</div>
Ajax post page (to store data in db after submit)
<?php
include '../includes/database/db_connect.php';
include '../includes/database/functions.php';
if($_POST) {
//Form data
$email = safe($mysqli,$_POST['email']);
$guestToken = safe($mysqli,$_POST['token']);
$password = veilig($mysqli,$_POST['password']);
$rePassword = veilig($mysqli,$_POST['re_password']);
//Check if everything has been filled in correctly
if ($email == '' || $password == '' || $rePassword == '') {
echo "orderFormRequiredFields";
exit();
}
//Check emailFormat
if (!CheckEmailFormat($email)) {
echo "orderFormerrorEmailFormat";
exit();
}
//Check if email already exist
$checkIfEmailExist = mysqli_query($mysqli,"SELECT * FROM members WHERE email = '$email'");
if (mysqli_num_rows($checkIfEmailExist) > 0){
echo "orderFormEmailAlreadyExist";
exit();
}
//Check if the two passwords do match
if ( $password == $rePassword ) {
//Als wachtwoorden overeen komen, maak er een hashed pw + salt van
$salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
$saltedPW = $password . $salt;
$hashedPW = hash('sha256', $saltedPW);
} else {
echo "orderFormErrorPasswordConfirm";
exit();
}
$tstamp = time();
$token = md5(uniqid(mt_rand()));
//Add user to the database
$createUser = mysqli_query($mysqli,"INSERT INTO members (account_active, email, guest_token, password, salt)
VALUES ('0', '$email', '$guestToken', '$hashedPW', '$salt'); ");
//begin storing user_id
//Check for the users salt
$getSalt = mysqli_query($mysqli,"SELECT salt FROM members WHERE email = '$email';");
if (!$getSalt) {
echo "Error Salt";
exit();
}
$row = mysqli_fetch_assoc($getSalt);
$salt = $row['salt'];
//Find the user details
$saltedPW = $password . $salt;
$hashedPW = hash('sha256', $saltedPW);
$findUser = mysqli_query($mysqli,"SELECT * FROM members WHERE email = '$email' AND password = '$hashedPW'");
$roww = mysqli_fetch_assoc($findUser);
$user_id = $roww['user_id'];
//If users exist, count should be 1
$count = mysqli_num_rows($findUser);
if($count == 1) {
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = $email;
} else {
echo "Error";
exit();
}
//end
echo "succesMsgOrderForm";
}
?>
This is the basic of the overview page
<?php
include 'includes/database/db_connect.php';
include 'includes/database/functions.php';
sec_session_start();
$user_id = $_SESSION['user_id'];
$getAllDetails = mysqli_query($mysqli,"SELECT * FROM members WHERE user_id = '$user_id' ") OR die (mysqli_error($mysqli));
$row = mysqli_fetch_array($getAllDetails);
$email = $row['email'];
?>
<body>
user_id is: <?php echo $user_id ?> <br>
email is: <?php echo $email ?>
</body>
Thank you,
Edit #1 sec_session_start() part which is in functions.php:
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = SECURE;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
ini_set('session.use_only_cookies', 1);
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(); // regenerated the session, delete the old one.
}
Edit #2 - Part where I open up the colorbox (javascript)
$(document).on('click', '#pay_ideal', function(){
$.colorbox({
width: 500,
height: 350,
speed: 350,
closeButton: false,
href:"order-overview.php"
});
});
You need to check session status before refreshing your session lik;
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = SECURE;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
ini_set('session.use_only_cookies', 1);
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
if (session_id() == '') {
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id();
}
}
Related
I am writing a simple login validation. (I know people say I shouldn't deal with passwords in plaintext, because it's dangerous, however, I am doing this for a school assignment where we do not need to use any security.) The issue I am having here is that I can't get the message for login to be successful. I am getting a login failure. I inserted a couple of users and passwords into a database table. What I need to do is to get the value from the "name" column and the "pwd" (password) column from my database table and allow a successful login (in Javascript) if the user's input has a match with the user and password in the database table.
Here is my form code:
<form method="post" action="login.php" onsubmit="validateForm()" id="loginForm" name="loginForm">
Name:<br>
<input type="text" name="personName"><br>
Password:<br>
<input type="password" name="pswd"><br>
<input type="submit" name="submit" id="submit" value="Login" />
</form>
Javascript:
<script>
function validateForm()
{
var n = document.loginForm.personName.value;
var p = document.loginForm.pswd.value;
//The var below is what I need help on.
var name = "<?php echo $row['name']; ?>";
//The var below is what I need help on.
var ps = "<?php echo $row['pwd']; ?>";
if ((n == name) && (p == ps))
{
alert ("Login successful!");
return true;
}
else
{
alert ("Login failed! Username or password is incorrect!");
return false;
}
}
</script>
PHP code (I have an empty while statement just in case I need it):
<?php
function validateLogin()
{
//I hid this information from here.
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$dbc = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($dbc->connect_error)
{
die("Connection failed: " . $dbc->connect_error);
}
$n = $_POST["personName"];
$p = $_POST["pswd"];
$query = "SELECT `name`, `pwd` FROM `chatApp`";
$result = $dbc->query($query);
$numRows = mysql_num_rows($result);
$count = 1;
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
}
}
else
{
echo "0 results";
}
$dbc->close();
}
if(array_key_exists('loginForm',$_POST))
{
validateLogin();
}
?>
I have a question on how to automatically show alert message. I have set the time limit to 10s but I need to manually refresh the page then alert message will pop up. Alert message that will be display will tell the user the session is over and reload the page. Here is my code
<?php
//start session
session_start();
//database connection
$conn = mysqli_connect("localhost","root","","test");
//default timezone
date_default_timezone_set('Asia/Kuala_Lumpur');
//if user click login button
if(!empty($_POST["login"]))
{
//query table to verify inserted value
$result = mysqli_query($conn,"SELECT * FROM users WHERE username = '" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
//fetch result result row as an associative, a numeric array, or both
$row = mysqli_fetch_array($result);
//if it is true
if($row)
{
//declare a session for selected value using id and time logged in
$_SESSION["user_id"] = $row['id'];
$_SESSION['timestamp'] = time();
}
else
{
//redirect to homepage
echo '<script type="text/javascript">alert("Invalid Username or Password!");window.location = "userlogin_session.php";</script>';
}
}
//check for session timeout
if(isset($_SESSION['timestamp']))
{
//set time limit in seconds
$expireAfterSeconds = 10;
//calculate many seconds have passed since the user was last active
$secondsInactive = time() - $_SESSION['timestamp'];
//convert seconds into minutes
$expireAfter = $expireAfterSeconds / 60 ;
//check to see if time is equals or above given time limit
if($secondsInactive >= $expireAfter)
{
//kill session.
session_unset();
session_destroy();
//redirect to homepage
echo '<script type="text/javascript">alert("Session Over");window.location = "userlogin_session.php";</script>';
}
}
//if user click logout button
if(!empty($_POST["logout"]))
{
//kill session.
session_unset();
session_destroy();
}
?>
You'll need to do it in Javascript, not PHP. You can however send the PHP var to the javascript, or just hard code it (seconds * 1000) and then get it to alert or modal window:
setTimeout(function(){
alert ('Session timeout message or code here');
}, <?= $timeout; ?>);
This is my full code.
<?php
//start session
session_start();
//database connection
$conn = mysqli_connect("localhost","root","","test");
//default timezone
date_default_timezone_set('Asia/Kuala_Lumpur');
//if user click login button
if(!empty($_POST["login"]))
{
//query table to verify inserted value
$result = mysqli_query($conn,"SELECT * FROM users WHERE username = '" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
//fetch result result row as an associative, a numeric array, or both
$row = mysqli_fetch_array($result);
//if it is true
if($row)
{
//declare a session for selected value using id and time logged in
$_SESSION["user_id"] = $row['id'];
$_SESSION['timestamp'] = time();
}
else
{
//redirect to homepage
echo '<script type="text/javascript">alert("Invalid Username or Password!");window.location = "userlogin_session.php";</script>';
}
}
//check for session timeout
if(isset($_SESSION['timestamp']))
{
//set time limit
$expireAfterSeconds= 10;
//calculate many seconds have passed since the user was last active
$secondsInactive = time() - $_SESSION['timestamp'];
echo $secondsInactive;
//check to see if time is equals or above given time limit
if($secondsInactive >= $expireAfterSeconds)
{
//kill session.
session_unset();
session_destroy();
//redirect to homepage
//echo '<script type="text/javascript">alert("Session Over");window.location = "userlogin_session.php";</script>';
?>
<script>
alert("Session Over");
window.location = "userlogin_session.php";
</script>';
<?php
}
}
//if user click logout button
if(!empty($_POST["logout"]))
{
//kill session.
session_unset();
session_destroy();
}
?>
<html>
<head>
<title>User Login</title>
</head>
<body>
<?php
//if session not exist
if(empty($_SESSION["user_id"]))
{
?>
<form action="" method="post" id="frmLogin">
<div><?php if(isset($message)) { echo $message; } ?></div>
<div>
<div><label for="login">Username</label></div>
<div><input name="user_name" type="text"></div>
</div>
<div>
<div><label for="password">Password</label></div>
<div><input name="password" type="password"> </div>
</div>
<div>
<div><input type="submit" name="login" value="Login"></span></div>
</div>
</form>
<?php
}
//if session exist
else
{
$result = mysqli_query($conn,"SELECT * FROM users WHERE id = '" . $_SESSION["user_id"] . "'");
$row = mysqli_fetch_array($result);
?>
<form action="" method="post" id="frmLogout">
<div>
Welcome <?php echo ucwords($row['username']); ?>, You have successfully logged in!<br>Click to <input type="submit" name="logout" value="Logout">
</div>
</form>
</div>
</div>
<?php
}
?>
</body>
</html>
I am working with stripe payment and I am trying to set the amount to a variable. I see there's a lot of questions in regards to this out there, but I haven't been able to find he answer.
On the top of the page I query my database for the a number and do some basic math to set the amount. I echo the cost just to make sure it's working and it is. Here's the code for that
require_once('../stripe/lib/Stripe.php');
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host={$config->dbhost};dbname={$config->dbname}", $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$id= $_GET['rid'];
$query = $dbh->prepare("SELECT hours FROM svcrequest WHERE id=? ");
$query->execute(array($id));
$rslt = $query->fetch(PDO::FETCH_ASSOC);
$cost = ($rslt[hours] * 27)*100;
echo $cost;
I then try to assign the cost to another variable amount inside some if statement and exception and I try to echo the amount but I get nothing.
// Set the order amount somehow:
$amount = $cost; // in cents
echo $amount;
$email = "info#intelycare.com";
$description = "Jane Doe"; //customer
When I echo $amount nothing shows. Here the full code for the page. I could use some help with this.
<?php
// Created by Larry Ullman, www.larryullman.com, #LarryUllman
// Posted as part of the series "Processing Payments with Stripe"
// http://www.larryullman.com / series / processing - payments - with - stripe /
// Last updated February 20, 2013
// The class names are based upon Twitter Bootstrap (http://twitter.github.com / bootstrap / )
// This page is used to make a purchase.
// Every page needs the configuration file:
// Uses sessions to test for duplicate submissions:
session_start();
?><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>
IntelyCare
</title>
<script type="text/javascript" src="https://js.stripe.com/v2/"> </script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"> </script>
<script src="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.js"> </script>
</head>
<body>
<?php
require_once('../stripe/lib/Stripe.php');
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host={$config->dbhost};dbname={$config->dbname}", $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$id= $_GET['rid'];
$query = $dbh->prepare("SELECT hours FROM svcrequest WHERE id=? ");
$query->execute(array($id));
$rslt = $query->fetch(PDO::FETCH_ASSOC);
$cost = ($rslt[hours] * 27)*100;
echo $cost;
// Set the Stripe key:
// Uses STRIPE_PUBLIC_KEY from the config file.
echo '<script type="text/javascript">Stripe.setPublishableKey("' . STRIPE_PUBLIC_KEY . '");</script>';
// Check for a form submission:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// Stores errors:
$errors = array();
// Need a payment token:
if(isset($_POST['stripeToken']))
{
$token = $_POST['stripeToken'];
// Check for a duplicate submission, just in case:
// Uses sessions, you could use a cookie instead.
if(isset($_SESSION['token']) && ($_SESSION['token'] == $token))
{
$errors['token'] = 'You have apparently resubmitted the form. Please do not do that.';
}
else
{
// New submission.
$_SESSION['token'] = $token;
}
}
else
{
$errors['token'] = 'The order cannot be processed. Please make sure you have JavaScript enabled and try again.';
}
// Set the order amount somehow:
$amount = $cost; // in cents
echo $amount;
$email = "info#intelycare.com";
$description = "Jane Doe"; //customer
// Validate other form data!
// If no errors, process the order:
if(empty($errors))
{
// create the charge on Stripe's servers - this will charge the user's card
try
{
// Include the Stripe library:
// set your secret key: remember to change this to your live secret key in production
// see your keys here https://manage.stripe.com / account
Stripe::setApiKey(STRIPE_PRIVATE_KEY);
// Charge the order:
// Create a Customer
$customer = Stripe_Customer::create(array(
"card" => $token,
"description"=> $description
)
);
// Charge the Customer instead of the card
Stripe_Charge::create(array(
"amount" => $amount ,# amount in cents, again
"currency"=> "usd",
"customer"=> $customer->id
)
);
// Save the customer ID in your database so you can use it later
//saveStripeCustomerId($user, $customer->id);
// Later...
//$customerId = getStripeCustomerId($user);
$charge = Stripe_Charge::create(array(
"amount" => $amount,// amount in cents, again
"currency"=> "usd",
"customer"=> $customer
)
);
// Check that it was paid:
if($charge->paid == true)
{
// Store the order in the database.
// Send the email.
// Celebrate!
}
else
{
// Charge was not paid!
echo '<div class="alert alert-error"><h4>Payment System Error!</h4>Your payment could NOT be processed (i.e., you have not been charged) because the payment system rejected the transaction. You can try again or use another card.</div>';
}
} catch(Stripe_CardError $e)
{
// Card was declined.
$e_json = $e->getJsonBody();
$err = $e_json['error'];
$errors['stripe'] = $err['message'];
} catch(Stripe_ApiConnectionError $e)
{
// Network problem, perhaps try again.
} catch(Stripe_InvalidRequestError $e)
{
// You screwed up in your programming. Shouldn't happen!
} catch(Stripe_ApiError $e)
{
// Stripe's servers are down!
} catch(Stripe_CardError $e)
{
// Something else that's not the customer's fault.
}
} // A user form submission error occurred, handled below.
} // Form submission.
?>
<h1>
IntelyCare
</h1>
<form action="buy.php" method="POST" id="payment-form">
<?php // Show PHP errors, if they exist:
if(isset($errors) && !empty($errors) && is_array($errors))
{
echo '<div class="alert alert-error"><h4>Error!</h4>The following error(s) occurred:<ul>';
foreach($errors as $e)
{
echo "<li>$e</li>";
}
echo '</ul></div>';
}?>
<div id="payment-errors">
</div>
<span class="help-block">
Form of Payment accepted: Mastercard, Visa, American Express, JCB, Discover, and Diners Club.
</span>
<br />
<input type="text" name="clientid" value="<?php if(isset($_GET['rid'])) {echo $_GET['rid']; } ?>" >
<br />
<label> Card Number </label>
<input type="text" size="20" autocomplete="off" class="card-number input-medium">
<span class="help-block"> Enter the number without spaces or hyphens. </span>
<label> CVC </label>
<input type="text" size="4" autocomplete="off" class="card-cvc input-mini">
<label> Expiration (MM/YYYY) </label>
<input type="text" size="2" class="card-expiry-month input-mini">
<span> / </span>
<input type="text" size="4" class="card-expiry-year input-mini">
<button type="submit" class="btn" id="submitBtn">
Submit Payment
</button>
</form>
<script src="../stripe/buy.js">
</script>
</body>
</html>
I reached out to Stripe and they gave me couple recommendations, here's a solution to the problem hopefully it benefits someone else. I am able to pass a variable amount for stripe payment. Below is my charge.php file, I am not handling errors yet but I will include it later.
<?php
require_once(dirname(__FILE__) . '/config.php');
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host={$config->dbhost};dbname={$config->dbname}", $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$id= $_GET['rid'];
$query = $dbh->prepare("SELECT hours, cid FROM svcrequest WHERE id=? ");
$query->execute(array($id));
$rslt = $query->fetch(PDO::FETCH_ASSOC);
$cost = ($rslt['hours'] * 23)*100;
echo $cost;
$cid = $rslt['cid'];
$query = $dbh->prepare("SELECT email, fname, lname FROM client JOIN users ON client.uid = users.id WHERE uid =(SELECT uid FROM client WHERE id=?)");
$query->execute(array($cid));
$user =$query->fetch(PDO::FETCH_ASSOC);
$email = ($user['email']);
echo $email;
$token = $_POST['stripeToken'];
$customer = Stripe_Customer::create(array(
'email' => $email,
'card' => $token
));
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $cost,
'currency' => 'usd'
));
echo '<h3>Charge today:</h3>' . $cost;
?>
I have a site using a PHP script to login the user. It works fine in most browsers, but IE8 and IE9 seem to be having trouble with the cookies. I've read a bunch of similar posts, but so far nothing seems to help. Any ideas as to where the problem is here? Details are code are below.
We are using this code for our login script: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Login Form
<?php
if($error == 1) echo "<p class=\"error\">Your Log in information is incorrect</p>";
?>
<form class="form-horizontal" role="form" action="includes/process_login.php" method="post" name="login_form">
<div class="form-group">
<!-- <label for="inputEmail1" class="col-md-2 control-label">Email</label> -->
<div class="col-md-12">
<input type="email" class="form-control" id="inputEmail1" name="inputEmail1">
</div>
</div>
<div class="form-group">
<!-- <label for="inputPass1" class="col-md-2 control-label">Password</label> -->
<div class="col-md-12">
<input type="password" class="form-control" id="inputPass1" name="inputPass1">
</div>
</div>
</div>
</div>
</div>
</div>
<div id="login-content">
<div class="form-group">
<button type="submit" class="btn btn-default signin-btn" onclick="formhash(this.form, this.form.inputPass1);">Sign In</button>
</div>
</form>
Process Login Page
<?php
header('P3P: CP="NOI ADM DEV COM NAV OUR STP"');
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
if (isset($_POST['inputEmail1'], $_POST['p'])) {
$email = $_POST['inputEmail1'];
$password = $_POST['p']; // The hashed password.
exit($email);
if (login($email, $password, $mysqli) == true) {
// Login success
header('Location: ../index.php');
} else {
// Login failed
header('Location: ../index.php?error=1');
}
} else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
Login Function
//checks login info against db
function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, fname, lname, pass, salt, type_id
FROM users
WHERE email = ?
LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $fname, $lname, $db_password, $salt, $user_type);
$stmt->fetch();
// hash the password with the unique salt.
$password = hash('sha512', $password . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$user_type = preg_replace("/[^0-9]+/", "", $user_type);
$_SESSION['user_id'] = $user_id;
$_SESSION['user_type'] = $user_type;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$fname . $lname);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512',
$password . $user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
The answer was in the javascript. Basically IE8 does not allow changing the 'type' of a field and there was a javascript function that hashed the password and then put the value in a new field where it set the type to hidden. I just made the field already set to hidden and then it worked.
So i am making a registration page on my website. At the moment it is more just a test then anything. I have it working more or less and when a user attempts to sign up it works just fine HOWEVER there is no change on the page. I have created a Confirmation page but no matter what i try i can't seem to get the button to redirect as well.
<form name="register" method="post" action="register.php">
Username:<input name="user" type="text" id="user">
<br>
Password:<input name="pass" type="password" id="pass">
<br>
Repeat Password:<input name="rpass" type="password" id="rpass">
<br>
<input type="submit" name="submit" value="Register">
</form>
From what i can tell in the last few hours of research the reason onclick and wrapping the button in a link does not work is because the type="submit" instead of "button". Is there any way do make this button redirect? If not with HTML perhaps with a JS or PHP ?
<?php
session_start(); //Must Start a session.
require "config.php"; //Connection Script, include in every file!
//Check to see if the user is logged in.
//'isset' check to see if a variables has been 'set'
if(isset($_SESSION['username'])){
header("location: members.php");
}
//Check to see if the user click the button
if(isset($_POST['submit']))
{
//Variables from the table
$user = $_POST['user'];
$pass = $_POST['pass'];
$rpass = $_POST['rpass'];
//Prevent MySQL Injections
$user = stripslashes($user);
$pass = stripslashes($pass);
$rpass = stripslashes($rpass);
$user = mysqli_real_escape_string($con, $user);
$pass = mysqli_real_escape_string($con, $pass);
$rpass = mysqli_real_escape_string($con, $rpass);
//Check to see if the user left any space empty!
if($user == "" || $pass == "" || $rpass == "")
{
echo "Please fill in all the information!";
}
else
{
//Check too see if the user's Passwords Matches!
if($pass != $rpass)
{
echo "Passwords do not match! Try Again";
}
//CHECK TO SEE IF THE USERNAME IS TAKEN, IF NOT THEN ADD USERNAME AND PASSWORD INTO THE DB
else
{
//Query the DB
$query = mysqli_query($con,"SELECT * FROM members WHERE username = '$user'") or die("Can not query the TABLE!");
//Count the number of rows. If a row exist, then the username exist!
$row = mysqli_num_rows($query);
if($row == 1)
{
echo "Sorry, but the username is already taken! Try again.";
}
//ADD THE USERNAME TO THE DB
else
{
$add = mysqli_query($con,"INSERT INTO members (id, username, password) VALUES (null, '$user' , '$pass') ") or die("Can't Insert! ");
}
}
}
}
?>
As I commented, simply do
else
{
$add = mysqli_query($con,"INSERT INTO members (id, username, password) VALUES (null, '$user' , '$pass') ") or die("Can't Insert! ");
header("location: thankyou.html");
}