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>
Related
I currently have a loginsystem where a user is able to register and login as a user.
When the user is logged in they should be able to upload a profile image.
The problem that i have is that when i press the Signup button, i gets rediretec to this URL (http://localhost/php51/login.php) Instead of this (http://localhost/php51/index.php).
The thing is that when the user has been registered, then the user should pop up on index.php and show a default profile pic for the user.
Instead i just get a blank page on (http://localhost/php51/login.php).
This is my database with the columns:
I have two tables in my Database called (loginsystem)
the two tables are:
table "profileimg" with the columns (id, status, userid)
and the table "users" with columns (user_email, user_id, user_name, user_password, user_phone, user_zip)
This is my code:
INDEX.php
<?php
session_start();
include_once 'dbh.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<?php
// Check if there is users
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['user_id'];
$sqlImg = "SELECT * FROM profileimg WHERE userid='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div>";
if($rowImg['status'] == 0) {
echo "<img src='uploads/profile".$id.".jpg'";
} else {
echo "<img src='uploads/profiledefault.jpg'";
}
echo $row['name'];
echo "</div>";
}
}
} else {
echo "No registered users :";
}
//Her checker vi for om man er logget ind,
//og viser herefter upload FORM
if (isset($_SESSION['id'])) {
if ($_SESSION['id'] == 1) {
echo " You are logged in!";
}
//If the user is logged in, we allow the user to upload a profile image
echo "<form action = 'upload.php' method='POST' enctype = 'multipart/form-data'>
<input type = 'file' name = 'file'>
<button type = 'submit' name = 'submit'>UPLOAD FILE</button>
</form>";
} else {
echo " You are not logged in!";
echo "<form action='login.php' method='POST'>
<input type='text' name='name' placeholder='Name'>
<input type='text' name='phone' placeholder='phone'>
<input type='text' name='email' placeholder='email'>
<input type='text' name='zip' placeholder='zip'>
<input type='password' name='password' placeholder='password'>
<button type ='submit' name='submitSignup'>Signup</button>
</form>";
}
?>
<!--We use HTML forms when we want to upload images or files-->
<!--The form HAS to be set as a POST method, and it needs the "enctype" attribute, which specifies that the content we are submitting using the form is a file-->
<p> Login as user </p>
<form action="login.php" method="POST">
<button type="submit" name="submitLogin"> Login </button>
</form>
<p> Logout as user </p>
<form action="logout.php" method="POST">
<button type="submit" name = "submitLogout">Logout</button>
</form>
</body>
</html>
LOUGOUT.php
<?php
session_start();
session_unset();
session_destroy();
header("Location: index.php");
UPLOAD.php
<?php
//First we check if the form has been submitted
if (isset($_POST['submit'])) {
//Then we grab the file using the FILES superglobal
//When we send a file using FILES, we also send all sorts of information regarding the file
$file = $_FILES['file'];
//Here we get the different information from the file, and assign it to a variable, just so we have it for later
//If you use "print_r($file)" you can see the file info in the browser
$fileName = $file['name'];
$fileType = $file['type'];
//The "tmp_name" is the temporary location the file is stored in the browser, while it waits to get uploaded
$fileTempName = $file['tmp_name'];
$fileError = $file['error'];
$fileSize = $file['size'];
//Later we are going to decide the file extensions that we allow to be uploaded
//Here we are getting the extension of the uploaded file
//First we split the file name into name and extension
$fileExt = explode('.', $fileName);
//Then we get the extention
$fileActualExt = strtolower(end($fileExt));
//Here we declare which extentions we want to allow to be uploaded (You can change these to any extention YOU want)
$allowed = array("jpg", "jpeg", "png", "pdf");
//First we check if the extention is allowed on the uploaded file
if (in_array($fileActualExt, $allowed)) {
//Then we check if there was an upload error
if ($fileError === 0) {
//Here we set a limit on the allowed file size (in this case 500mb)
if ($fileSize < 500000) {
//We now need to create a unique ID which we use to replace the name of the uploaded file, before inserting it into our rootfolder
//If we don't do this, we might end up overwriting the file if we upload a file later with the same name
//Here we create a unique ID based on the current time, meaning that no ID is identical. And we add the file extention type behind it.
$fileNameNew = uniqid('', true).".".$fileActualExt;
//Here we define where we want the new file uploaded to
$fileDestination = 'uploads/'.$fileNameNew;
//And finally we upload the file using the following function, to send it from its temporary location to the uploads folder
move_uploaded_file($fileTempName, $fileDestination);
//Going back to the previous page
header("Location: index.php");
}
else {
echo "Your file is too big!";
}
}
else {
echo "There was an error uploading your file, try again!";
}
}
else {
echo "You cannot upload files of this type!";
}
}
SIGNUP.php
<?php
include_once 'dbh.php';
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$zip = $_POST['zip'];
$password = $_POST['password'];
$sql = "INSERT INTO users (name, phone, email, zip, password)
VALUES ('$name', '$phone', '$email', '$zip', '$password')";
mysqli_query($conn, $sql);
$sql = "SELECT * FROM users WHERE name = '$name' AND phone='$phone'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$userid = $row['user_id'];
$sql = "INSERT INTO profileimg (userid, status)
VALUES ('$userid', 1)";
mysqli_query($conn, $sql);
header("Location: index.php");
}
} else {
echo "Error";
}
DBH.PHP
<?php
$conn = mysqli_connect("localhost", "root", "", "loginsystem");
LOGIN.PHP
<?php
session_start();
if (isset($_POST['submitLogin'])) {
$_SESSION['id'] = 1;
header("Location: index.php");
}
In your file index.php you need to change the line
echo "<form action='login.php' method='POST'>
to
echo "<form action='signup.php' method='POST'>
Right now you're sending your signup data to the wrong place
I´m always getting "Invalid request" because of the "POST variables were not sent to this page". I already chech the javascript on the console and it was fine. And i read eveithing about this problem, maybe the problem is not the code. Can somebody please help me?
This is my index.php (login page)
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
if (login_check($mysqli) == true) {
$logged = 'in';
} else {
$logged = 'out';
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Secure Login: Log In</title>
<link rel="stylesheet" href="styles/main.css" />
<script type="text/JavaScript" src="js/sha512.js"></script>
<script type="text/JavaScript" src="js/forms.js"></script>
</head>
<body>
<?php
if (isset($_GET['error'])) {
echo '<p class="error">Error Logging In!</p>';
}
?>
<form action="process_login.php" method="POST" name="login_form">
Email: <input type="text" name="email" />
Password: <input type="password"
name="password"
id="password"/>
<input type="button"
value="Login"
onclick="formhash(this.form,this.form.password);"
/>
</form>
<?php
if (login_check($mysqli) == true) {
echo '<p>Currently logged ' . $logged . ' as ' .
htmlentities($_SESSION['username']) . '.</p>';
echo '<p>Do you want to change user? Log out.</p>';
} else {
echo '<p>Currently logged ' . $logged . '.</p>';
echo "<p>If you don't have a login, please <a
href='register.php'>register</a></p>";
}
?>
</body>
</html>
And this is my login_process:
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p']; // The hashed password.
if (login($email, $password, $mysqli) == true) {
// Login success
header('Location: protected_page.php');
} else {
// Login failed
header('Location: ../index.php?error=1');
}
} else {
// The correct POST variables were not sent to this page.
echo 'invalid Request';
}
And the form that seems to be working:
function formhash(form, password) {
// Create a new element input, this will be our hashed password field.
var p = document.createElement("input");
// Add the new element to our form.
document.body.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
// Make sure the plaintext password doesn't get sent.
password.value = "";
// Finally submit the form.
form.submit();
}
And the functions:
function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password
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, $username, $db_password);
$stmt->fetch();
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. We are using
// the password_verify function to avoid timing attacks.
if (password_verify($password, $db_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);
$_SESSION['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512',
$db_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;
}
}
}
Thank you for your time.
I've made a popup message with auto-refresh function, so every few minutes the popup will appear to display the records. And it worked.
The following is the JavaScript code that auto refreshes:
$(document).ready(function() {
setInterval(function() {
$('#rtnotice').load('plugins/notice/n_notice_invoice.php').fadeIn("slow");
}, 5000)
});
code of n_notice_invoice.php
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("#noticearea").hide();
});
});
</script>
<?php
try{
require_once "../../config/c_config.php";
$db = dbConn::getConnection();
$timestamp = $_REQUEST['term'];
$sqlck = $db->prepare("SELECT COUNT(id_notice_alert) as ttlinv FROM str_notice_alert WHERE date_alert > '$timestamp'");
$sqlck->execute();
$resck = $sqlck->fetch(PDO::FETCH_ASSOC);
if($resck['ttlinv'] == '0')
{}else{
?>
<div id="noticearea">
<div id="modal">
<div class="modal-content">
<div class="header">
<div id="circle" align="center"><h1><?php echo $resck['ttlinv'];?></h1></div><div class="titlenotice"><h1>NOTICE ALERT<?php echo $timestamp; ?></h1></div>
<div class="break"></div>
</div>
<div class="copy">
<p>
<table width="100%" class="gridtable">
<tr><th>No</th><th>Name</th><th>Status</th><th>Location</th><th>Date</th></tr>
<?php
$sqll = $db->prepare("SELECT * FROM str_notice_alert");
$sqll->execute();
while($resl = $sqll->fetch(PDO::FETCH_ASSOC)){
?>
<tr><td align="center"><?php echo $resl['id_notice_alert']; ?></td><td><?php echo $resl['alert_name']; ?></td><td align="center"><?php echo $resl['alert_status']; ?></td><td align="center"><?php echo $resl['alert_location']; ?></td><td><?php echo $resl['date_alert']; ?></td></tr>
<?php } ?>
</table>
</p>
</div>
<div class="cf footer">
<button id="hide" class="btn">Close</button>
</div>
</div>
<div class="overlay"></div>
</div></div>
<?php
$sqltrunc = $db->prepare("TRUNCATE TABLE str_notice_alert");
$sqltrunc->execute();
}$db = null;}
catch (PDOException $e) {
echo "Connection Error " . $e->getMessage();
}
?>
After a popup message is displayed, it will display the file n_notice_invoice.php existing records and also delete the records via queries available. In any appearances. But the question is, why the records are not updated / changed. uUnless I refresh the file directly n_notice_invoice.php, and then auto-refresh displays the most recent data.
$timestamp = $_REQUEST['term'];
should be updated each time you call the page. You should load the page with Ajax passing $timestamp as a parameter instead of just loading it.
To get what you need can I suggest you to use long polling? PHP long polling or even better with node.js. For php for example the "server" page:
$timeStart = time();
// Create connection
$con = mysqli_connect('localhost','root','','polldb');
// Check connection
if (mysqli_connect_errno($con))
die ('Failed to connect to MySQL: ' . mysqli_connect_error() );
// select where item is new
if(isset($_POST['timestamp'])){
$timestamp = $_POST['timestamp'];
}else{
// get current database time
$row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
$timestamp = $row['now'];
}
$sql = "SELECT * FROM `notification` WHERE timestamp > '$timestamp'";
$newData = false;
$notifications = array();
// loop while there is no new data and is running for less than 20 seconds
while(!$newData && (time()-$timeStart)<20){
// check for new data
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)){
$notifications[] = $row;
$newData = true;
}
// let the server rest for a while
usleep ( 500000 );
}
// get current database time
$row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
$timestamp = $row['now'];
mysqli_close($con);
// output
$data = array('notifications'=>$notifications,'timestamp'=>$timestamp);
echo json_encode($data);
exit;
and the client:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
pullNotification();
});
function pullNotification(timestamp){
var data = {};
if(typeof timestamp!='undefined')
data.timestamp = timestamp;
$.post('longpoll.php',data,function(msg){
var newData = '';
for(i in msg.notifications){
newData+=msg.notifications[i].message+'\n';
}
if(newData!='')
alert(newData);
pullNotification(msg.timestamp);
},'json');
}
</script>
This will check for database updates and will pop them up. Every 20 seconds it will renew the request. Obviously you have to adapt it to your needs.
I believie your issue comes from cached request (in Browser on in ajax itself)
please try to disable ajax caching :
$(document).ready(function() {
setInterval(function() {
$.ajax({
url: "plugins/notice/n_notice_invoice.php",
cache: false
})
.done(function( data ) {
$('#rtnotice').html(data).fadeIn("slow");
});
}, 5000)
});
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;
?>
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();
}
}