I"m struggling with Stripe. I'm using PHP and I'm trying to set up a simple store, with no CMS. Wondering how I can pass the amount into charge.php so I can charge different amounts for different products. Here's my code:
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => 1900;,
'currency' => 'gbp'
));
Here's the code from index.php - I would like to charge the customer whatever is in "data-amount" on the form below. Not quite sure how to do so.
<form action="inc/charge.php" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<?php echo $stripe['publishable_key']; ?>"
data-amount="1900"
data-currency="GBP"
data-name="Pure - Tumblr Theme"
data-allow-remember-me="false"
data-description="Premium Tumblr Theme"
data-image="/128x128.png">
</script>
</form>
More comprehensive, go from index.php to charge.php rather than the reverse.
<?php
#set your variables
$amount = 500;
$name = 'My Company';
$currency = 'gbp';
$description = 'Value Plan';
$uid = get->your->uid;
$email = get->your->email;
?>
<center><form action="../charge.php" method="post">
<!-- make these hidden input types for the post action to charge.php -->
<input type="hidden" name="amount" value="<?php echo $amount?>">
<input type="hidden" name="name" value="<?php echo $name;?>">
<input type="hidden" name="currency" value="<?php echo $currency;?>">
<input type="hidden" name="description" value="<?php echo $description;?>">
<input type="hidden" name="uid" value="<?php echo $uid;?>">
<input type="hidden" name="email" value="<?php echo $email;?>">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key = "<?php echo $stripe['publishable_key']; ?>"
data-amount = "<?php echo $amount;?>"
data-name = "<?php echo $name;?>"
data-currency = "<?php echo $currency;?>"
data-description = "<?php echo $description;?>"
data-email = "<?php echo $user->data()->email; ?>"
data-billing-address = "true"
data-allow-remember-me = "false"
>
</script>
</form></center>
Then in charge.php you can call the input values you hid in index.php
<?php
$token = $_POST['stripeToken'];
$email = $_POST['email'];
$uid = $_POST['uid'];
$currency = $_POST['currency'];
$amount = $_POST['amount'];
$description = $_POST['description'];
#This is the standard try catch block stripe suggests
try{
$charge = Stripe_Charge::create(array(
"amount" => $amount,
"currency" => $currency,
"customer" => $charge_to,
"description" => $description
));
} catch(Stripe_CardError $e) {
$error = $e->getMessage();
// Since it's a decline, Stripe_CardError will be caught
$body = $e->getJsonBody();
$err = $body['error'];
print('Status is:' . $e->getHttpStatus() . "\n");
print('Type is:' . $err['type'] . "\n");
print('Code is:' . $err['code'] . "\n");
// param is '' in this case
print('Param is:' . $err['param'] . "\n");
print('Message is:' . $err['message'] . "\n");
} catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
?>
Why do you want to charge whatever is in data-amount? Where do you get that value from? data-amount tells Stripe what the user allows you to charge. amount in Stripe_Charge::create is what you actually charge.
You could populate a hidden input field with the same value as data-amount. But i don't know what you would gain by that.
Your PHP skript should calculate the amount to pay. Don't trust the client. He could change the value of data-amount to pay less, i.e. 50.
Using the following the charge would work, but client pays 50 pence instead of 1900.
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $_POST['hidden_amount']
Ask Stripe for the total calculated payment. If the client has messed with data-amount the charge will fail.
'amount' => $shoppingcart->getTotal();,
Related
I am learning to create a simple signup and login page which using password_hash and password_verify function.
The sign up page is working fine, and the password_hash are able to encrypt my password in the mysql database. As photo below.
Only thing that is not working is that I cannot make the login to work, its always return to error message saying that the password is invalid. I am not using the hashed password, i am using the password that I entered during sign-up (which is just 123).
Below is my code:
Login Form:
<div class="InnerDiv">
<form method="post" action="">
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input name="email" type="email" value="<?php echo #$_POST['email']; ?>" class="form-control input-fields" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" required="true">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input name="password" type="password" class="form-control input-fields" id="exampleInputPassword1" placeholder="Password" required="true">
</div>
<center>
<button name="submit2" type="submit" class="btn btn-primary btn-login-form">Login</button>
<p data-toggle="modal" data-target="#forgotpassdialog" class="forgot-para">Forgot Password?
</p>
</center>
</form>
</div>
Verify login credentials
<?php
if (isset($_GET['msg'])) {
$var=$_GET['msg'];
echo "<script>alert('$var')</script>";
}
if(isset($_POST['submit2'])){
$email = $_POST["email"];
$password = $_POST["password"];
$data = mysqli_query($sql_con,"select *from students where stdemail = '$email' AND password='$password'");
$datarow = mysqli_num_rows($data);
if ($datarow > 0) {
if (password_verify($email, $password)) {
$row = mysqli_fetch_array($data);
$value3 = $row['id'];
$_SESSION['sid'] = $value3;
echo "<script>window.location='/students/dashboard.php'</script>";
}
}
else{
echo "<script>alert('Invalid password')</script>";
}
}
?>
Any help would be appreciated, let me know if more details is needed.
EDITED: I have tried to substitute the $email with the hashpassword value in the password_verify, but still return invalid message.
<?php
if (isset($_GET['msg'])) {
$var=$_GET['msg'];
echo "<script>alert('$var')</script>";
}
if(isset($_POST['submit2'])){
$email = $_POST["email"];
$password = $_POST["password"];
$data = mysqli_query($sql_con,"select *from students where stdemail = '$email' AND password='$passwordDB'");
$datarow = mysqli_num_rows($data);
if ($datarow > 0) {
if (password_verify($password, $passwordDB)) {
$row = mysqli_fetch_array($data);
$value3 = $row['id'];
$_SESSION['sid'] = $value3;
echo "<script>window.location='/students/dashboard.php'</script>";
}
}
else{
echo "<script>alert('Invalid password')</script>";
}
}
?>
You can't just make up some extra variables and slap them in the code. Your new version is no better than the previous one because you're selecting on a password variable that isn't initialised, and you're not retrieving the hashed password for PHP to check.
There's also the issue of possible SQL injection to address.
So, here's a rewritten version of your code, with some key changes:
Mysqli is set to throw an exception if there's an error.
I've used the OOP structure of MySQLi because it's less verbose and easier to follow
I've restructured your query to used a prepared statement, thus avoiding SQL injection problems
I've reworked your query to retrieve the student ID and hashed password. No other data is required in this code.
the code correctly verifies the user-supplied password against the hashed version retrieved from the database
session_start();
// Set MySQLi to throw an exception if it detects an error
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$sql_con = new mysqli('server', 'usernane', 'userpass', 'database');
if (isset($_POST['submit2'])) {
$email = $_POST["email"];
$password = $_POST["password"];
// set up query to retrieve id and hashed password
$query = "select id, password from students where stdemail = ?";
// Prepare query & bind parameters, execute
$stmt = $sql_con->prepare($query);
$stmt->bind_param('s', $email);
$stmt->execute();
// Bind variable to accept the result
$stmt->bind_result($id, $hashedPassword);
// fetch result. There should only be one, so no loop required.
$data = $stmt->fetch();
// Check we retrieved some data, and if so, check the password.
if ($data && password_verify($password, $hashedPassword)) {
$_SESSION['sid'] = $id;
echo "<script>window.location='/students/dashboard.php'</script>";
} else {
echo "<script>alert('Invalid credentials')</script>";
}
}
} catch(Exception $e) {
echo $e->getMessage();
}
I have run this code on my server - it works. If you have problems check your server connection, and ensure that the passwords in your database have been correctly hashed with password_hash().
Note: for this example the exception handler just displays the exception message. Your live code should not do that, but should handle the exception appropriately.
I have this code to display a user's name:
<div><?php echo 'My name is ' . '<span id="output">' . $_SESSION['firstname'] . '</span>' ?></div>
I'd like to change what's displayed in <span id="output"></span> when a user changes their profile.
This is what I use to change their profile data in the database (shortened to only include what's needed):
<form action="" method="POST">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname">
<button type="submit" name="submit">Submit</button>
</form>
if (isset($_POST['submit'])) {
$username = $_SESSION['username'];
$query = "SELECT * FROM `users` WHERE username='$username'";
$result = mysqli_query($connect, $query) or die(mysqli_error());
$profile = mysqli_fetch_assoc($result);
$update = "UPDATE users SET firstname = '$firstname' WHERE username = '$username'";
$result2 = mysqli_query($connect, $update);
if (mysqli_query($connect, $update)) {
$_SESSION['firstname'] = $firstname;
echo 'Profile updated successfully';
}
}
The thing is, I don't know how to change the "output" to the new $_SESSION['firstname'] without refreshing the page.
I would assume that I'd need to use JQuery's ajax function, but I'm not sure how to specifically use this function to get it done.
A lot of things are wrong with the code. Besides that point here is a simple ajax request.
$('.submit').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: 'yourscript.php',
data: {firstname: $('#firstname').val()},
success: function(data){
$('#firstname').html(data);
}
});
})
And for PHP:
# 'yourscript.php',
if(isset($firstname = $_POST['firstname'])){
// do your stuff.
echo 'your new data you want to display';
} else {
echo 'something went wrong';
}
Am trying to dynamically add the fields for subjects and the grades obtained, but am getting an error "Undefined index: subject in..." when posting those variables using java script.
Could there be something am missing with my posting mechanism. Notice that in the form data am not puting id="subject" to avoid picking the id for only one subject, and am using name="subject[]" to show an array, but I
dont seem to know how to represent this in the java script as we will see below.
form data as follows;
<tr>
<td colspan="6"><div align="center"><strong>
<p style="color:#930">Academic Qualification</p>
</strong></div></td>
</tr>
<?php
require_once("connection/connectPDO.php");
$sql="CALL sp_getSubjects()";
//Initiate and Call Stored Procedure Using PDO
$pdo = new PDOConfig();
$resultsSubject = $pdo->query($sql);
foreach($resultsSubject as $rowSubject)
{
?>
<tr>
<td width="35%" colspan="3"><div align="right"><?php echo $rowSubject['SubjectName']; ?>:<input name="subject[]" type="hidden" value="<?php echo $rowSubject['SubjectID']; ?>" /></div></td>
<td width="65%" colspan="3"><select name="grades[]" id="grades" class="validate[required]">
<option value="">--Select Grade--</option>
<?php
$sql="CALL sp_grabGrades()";
//Initiate and Call Stored Procedure Using PDO
$pdo = new PDOConfig();
$resultset = $pdo->query($sql);
foreach($resultset as $row)
{
?>
<option value="<?php echo $row['GradeObtainedID']; ?>"> <?php echo $row['Grade']; ?> </option>
<?php } ?>
</select></td>
<?php } ?>
</tr>
the form looks like this
Academic Qualification
English <--select-->
Biology <--select-->
Science <--select-->
the java script code is as follows;
$(document).ready(function(){
$("#submit").click(function(){
//if invalid do nothing
if(!$("#formD").validationEngine('validate')){
return false;
}
var vgrades = $("#grades").val();
var vsubject = $("#subject").val();
$.post("sendInitialApplication.php",
{
grades : vgrades,
subject : vsubject
/*Handles response from server*/
function(response){
alert(response);
});
alert("You are here");
});
});
the PHP code "sendInitialApplication.php" is as follows
<?php
$method = $_SERVER['REQUEST_METHOD'];
function connect(){
try{
$dbConn = new PDO('mysql:host=localhost; dbname=student', 'root', 'root');
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConn;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
/*Checks if method is HTTP POST*/
if(strtolower($method) == 'post'){
$grades = addslashes($_POST['grades']);
$subjects = addslashes($_POST['subject']);
try {
$dbHandler = connect();
$dbHandler->beginTransaction();
//Saving Various subjects with distinct grade obtained
foreach($subjects as $key => $subject)
{
$setIndexSubject = 'CALL sp_sendIndexSubject(:vSubjectID,:vGradeObtainedID)';
$stmt_subject = $dbHandler->prepare($setIndexSubject);
$stmt_subject->bindValue(':vSubjectID', $subject);
$stmt_subject->bindValue(':vGradeObtainedID', $grades[$key]);
$stmt_subject->execute();
$stmt_subject->closeCursor();
}
$dbHandler->commit();
echo "The Operation was Successful!!!!!!";
} catch (PDOException $e) {
$dbHandler->rollback();
die($e->getMessage());
}
}else{
echo "Oops! Make sure Method is POST";
}
?>
I'm expecting that $_POST['subject'] and $_POST['grades'] should be array. Than you cannot use $subjects = addslashes($_POST['subjects']), but $subjects = $_POST['subjects']. Calling addslashes on array throws PHP warning and returns NULL.
Edit:
I suggest modify logic of your code.
Input type hidden, with subject id, will not work, as you expects. Modify your list:
// ... obtaining subjects from db ...
foreach($resultsSubject as $rowSubject) {
?>
<tr>
<td>
<select name="grade[<?= $rowSubject['SubjectID']; ?>]">
<option value="">--Select Grade--</option>
<?php
// ... obtaining grades from db ...
foreach($resultset as $row) {
?>
<option value="<?php echo $row['GradeObtainedID']; ?>"> <?php echo $row['Grade']; ?> </option>
<?php
}
?>
</select>
</td>
</tr>
<?php
}
Than serialized form should return array:
grade = array (
subjectID1 => selectedGradeId,
subjectID2 => selectedGradeId,
...
)
And data processing in sendInitialApplication.php:
// prepare db transaction
$grades = $_POST['grade'];
foreach ($grades as $subject => $grade) {
$setIndexSubject = 'CALL sp_sendIndexSubject(:vSubjectID,:vGradeObtainedID)';
$stmt_subject = $dbHandler->prepare($setIndexSubject);
$stmt_subject->bindValue(':vSubjectID', $subject);
$stmt_subject->bindValue(':vGradeObtainedID', $grade);
$stmt_subject->execute();
$stmt_subject->closeCursor();
}
// close db transaction
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 may be being stupid, but I am trying to process a registration form using an AJAX call to a PHP page. My PHP page is working perfectly on it's own, but when I try to post the form data to the PHP page through AJAX nothing happens.
This is my AJAX call:
$(document).ready(function ($) {
$("#register").submit(function(event) {
event.preventDefault();
$("#message").html('');
var values = $(this).serialize();
$.ajax({
url: "http://cs11ke.icsnewmedia.net/DVPrototype/external-data/register.php",
type: "post",
data: values,
success: function (data) {
$("#message").html(data);
}
});
});
});
This is the form:
<div id="registerform">
<form method='post' id='register'>
<h3>Register</h3>
<p>Fill in your chosen details below to register for an account</p>
<p>Username: <input type='text' name='username' value='' /><br />
Password: <input type='password' name='password' ><br />
Repeat Password: <input type='password' name='repeatpassword'></p>
<input name='submit' type='submit' value='Register' >
<input name='reset' type='reset' value='Reset'><br /><br />
</form>
<div id="message"></div>
</div>
And this is my PHP page:
<?php function clean_string($db_server = null, $string){
$string = trim($string);
$string = utf8_decode($string);
$string = str_replace("#", "#", $string);
$string = str_replace("%", "%", $string);
if (mysqli_real_escape_string($db_server, $string)) {
$string = mysqli_real_escape_string($db_server, $string);
}
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return htmlentities($string);
}
function salt($string){
$salt1 = 'by*';
$salt2 = 'k/z';
$salted = md5("$salt1$string$salt2");
return $salted;
}
?>
<?php
//form data
$submit = trim($_POST['submit']);
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$repeatpassword = trim($_POST['repeatpassword']);
// create variables
$message = '';
$s_username = '';
//connect to database
{databaseconnection}
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
if(!$db_server){
//error message
$message = "Error: could not connect to the database.";
}else{
$submit = clean_string($db_server, $_POST['submit']);
$username = clean_string($db_server, $_POST['username']);
$password = clean_string($db_server, $_POST['password']);
$repeatpassword = clean_string($db_server, $_POST['repeatpassword']);
//check all details are entered
if ($username&&$password&&$repeatpassword){
//check password and repeat match
if ($password==$repeatpassword){
//check username is correct length
if (strlen($username)>25) {
$message = "Username is too long, please try again.";
}else{
if (strlen($password)>25||strlen($password)<6) {
//check password is correct length
$message = "Password must be 6-25 characters long, please try again.";
}else{
mysqli_select_db($db_server, $db_database);
// check whether username exists
$query="SELECT username FROM users WHERE username='$username'";
$result= mysqli_query($db_server, $query);
if ($row = mysqli_fetch_array($result)){
$message = "Username already exists. Please try again.";
}else{
//insert password
$password = salt($password);
$query = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
mysqli_query($db_server, $query) or die("Registration failed. ".
mysqli_error($db_server));
$message = "Registration successful!";
}
}
}
}else{
$message = "Both password fields must match, please try again.";
}
}else{
$message = "You must fill in all fields, please try again.";
}
}
echo $message;
mysqli_close($db_server);
?>
Apologies for all the code. I feel I may be making a stupid mistake but I don't know why the data isn't being posted or returned.
Thanks in advance!
Notice: This is more a comment than an answer but this is more readable since it includes code.
== EDIT ==
I Checked your code on http://cs11ke.icsnewmedia.net/DVPrototype/#registerlogin, your form doesn't have a id assigned to it
First: use your console...do you see an XMLHTTPREQUEST in your console?
What are the responses/headers etc? I can't stress this enough: use your console and report back here!!!
Next up the overly complicated ajax call...dumb it down to:
$('#register').submit(function(){
$('#message').html('');
$.post("http://cs11ke.icsnewmedia.net/DVPrototype/external-data/register.php",
$(this).serialize(),
function(response){
console.log(response);
$('#message').html(response);
}
);
return false;
});
In your PHP put this on top to check whether anything at all came through:
die(json_encode($_POST));
Please use Firebug or any other tool, to checḱ if the AJAX-script is called, what is its answer and if there are any errors in the script
My form is not submitting data to my database.
This is the PHP code:
<?php require 'core.inc.php'; ?>
<?php require 'connection.inc.php'; ?>
<?php
if(isset($_POST['username']) && isset($_POST['password']) &&
isset($_POST['password_again']) && isset($_POST['firstname']) &&
isset($_POST['surname'])){
$username = $_POST['username'];
$password = $_POST['password'];
$hashed_password = sha1($password);
$password_again = sha1('password again');
$username = $_POST['firstname'];
$password = $_POST['surname'];
//check if all fields have been filled
if(!empty($username)&& !empty($password) && !empty($password_again) &&
!empty($firstname)&& !empty($surname)){
if($password != $password_again){
echo 'Passwords do not match.';
} else {
//check if user is already registered;
$query = "SELECT username FROM user WHERE username = {$username} ";
$query_run = mysqli_query($connection, $query);
if (mysqli_num_rows ($query_run)==1){
echo 'User Name '.$username.' already exists.';
} else {
//register user
$query = "INSERT INTO `user` VALUES ('', '".$username."',
'".$password_hashed."','".$firstname."','".$surname."',)";
}
if($query_run = mysqli_query($connection, $query)){
header('Location: reg_succed.php');
} else {
echo 'Sorry we couldn\'t register you at this time. try again later';
}
}
}
} else {
echo 'All fields are required';
}
?>
<h2>Create New User</h2>
<form id="form" action="<?php echo $current_file ?>" method="POST">
<fieldset title="Login details" id="frame">
<legend>USER LOGIN DETAILS</legend>
<label>User Name:</label><br/>
<input type="text" name = "username" id = "username" value="<?php if(isset($username)){ echo $username; } ?>" maxlength="50" placeholder="Enter your Username" required/><br/>
<label>First Name:</label><br/>
<input type="text" name="firstname" id = "firstname" value="<?php if(isset($firstname)){ echo $firstname;} ?>" maxlength="50" placeholder="Enter your Firstname" required/><br/>
<label>Surname:</label><br/>
<input type="text" name="surname" id="surname" value="<?php if(isset($surname)) {echo $surname;} ?>" maxlength="50" placeholder="Enter your Surname" required/><br/>
<label>Password:</label><br/>
<input type="password" name="password" id="password" maxlength="50" placeholder="Enter your Password" required/><br/>
<label>Password Again:</label><br/>
<input type="password" name="password_again" id="password again" maxlength="50" placeholder="Enter your Password" required/><br/>
<input type="submit" name = "register" id = "register" value="Register">
</fieldset>
</form>
connection code
<?php
require_once("constants.php");
// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS, DB_NAME);
if (!$connection) {
die("Database connection failed: " . mysqli_error($connection));
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
?>
core.inc.php code
<?php
ob_start();
session_start();
$current_file = $_SERVER['SCRIPT_NAME'];
if(isset( $_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])){
$http_referer = $_SERVER['HTTP_REFERER'];
}
?>