Mysqli and PDO combined with Javascript and Ajax... possible? - php

Simple question from a noob programer. Thinking of several different styles and features to a project i have for a social website. question is this...
can you combine mysqli and PDO style programs?
having difficulty inserting data into database with php, ajax and javascript modules. it says "success" but doesnt insert the info with mysqli. i HAVE used PDO successfully. but my code looks right... it has the same syntax as the tutorial i am looking at with mysqli. this is the code...
<!-- ********************************** -->
<!-- *********** signup.php *********** -->
<!-- ********************************** -->
<?php
session_start();
// If user is logged in, header them away
if(isset($_SESSION["username"])){
header("location: message.php?msg=NO to that weenis");
exit();
}
?><?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("php_includes/db_conx.php");
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?><?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$cryptpass = crypt($p);
include_once ("php_includes/randStrGen.php");
$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (username, email, password, gender, country, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p_hash','$g','$c','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "auto_responder#yoursitename.com";
$subject = 'yoursitename Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>yoursitename Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;"><img src="http://www.yoursitename.com/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">yoursitename Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* E-mail Address: <b>'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="css/style.css">
<style type="text/css">
</style>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else if( _("terms").style.display == "none"){
status.innerHTML = "Please view the terms of use";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g);
}
}
function openTerms(){
_("terms").style.display = "block";
emptyElement("status");
}
/* function addEvents(){
_("elemID").addEventListener("click", func, false);
}
window.onload = addEvents; */
</script>
</head>
<body>
<?php include_once("includes/template_header.php"); ?>
<div id="pageMiddle">
<h3>Sign Up Here</h3>
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
<?php include_once("includes/template_country_list.php"); ?>
</select>
<div>
<a href="#" onclick="return false" onmousedown="openTerms()">
View the Terms Of Use
</a>
</div>
<div id="terms" style="display:none;">
<h3>Web Intersect Terms Of Use</h3>
<p>1. Play nice here.</p>
<p>2. Take a bath before you visit.</p>
<p>3. Brush your teeth before bed.</p>
</div>
<br /><br />
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
</div>
<?php include_once("includes/template_bottom.php"); ?>
</body>
</html>
<!-- ********************************** -->
<!-- *********** activation.php ******* -->
<!-- ********************************** -->
<?php
if (isset($_GET['id']) && isset($_GET['u']) && isset($_GET['e']) && isset($_GET['p'])) {
// Connect to database and sanitize incoming $_GET variables
include_once("php_includes/db_conx.php");
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
$e = mysqli_real_escape_string($db_conx, $_GET['e']);
$p = mysqli_real_escape_string($db_conx, $_GET['p']);
// Evaluate the lengths of the incoming $_GET variable
if($id == "" || strlen($u) < 3 || strlen($e) < 5 ){
// Log this issue into a text file and email details to yourself
header("location: message.php?msg=activation_string_length_issues");
exit();
}
// Check their credentials against the database
$sql = "SELECT * FROM users WHERE id='$id' AND username='$u' AND email='$e' AND password='$p' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
// Evaluate for a match in the system (0 = no match, 1 = match)
if($numrows == 0){
// Log this potential hack attempt to text file and email details to yourself
header("location: message.php?msg=Your credentials are not matching anything in our system");
exit();
}
// Match was found, you can activate them
$sql = "UPDATE users SET activated='1' WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
// Optional double check to see if activated in fact now = 1
$sql = "SELECT * FROM users WHERE id='$id' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
// Evaluate the double check
if($numrows == 0){
// Log this issue of no switch of activation field to 1
header("location: message.php?msg=activation_failure");
exit();
} else if($numrows == 1) {
// Great everything went fine with activation!
header("location: message.php?msg=activation_success");
exit();
}
else {
// Log this issue of missing initial $_GET variables
header("location: message.php?msg=missing_GET_variables");
exit();
}}
?>
<!-- ********************************** -->
<!-- *********** message.php ********** -->
<!-- ********************************** -->
<?php
$message = "";
$msg = preg_replace('#[^a-z 0-9.:_()]#i', '', $_GET['msg']);
if($msg == "activation_failure"){
$message = '<h2>Activation Error</h2> Sorry there seems to have been an issue activating your account at this time. We have already notified ourselves of this issue and we will contact you via email when we have identified the issue.';
} else if($msg == "activation_success"){
$message = '<h2>Activation Success</h2> Your account is now activated. Click here to log in';
} else {
$message = $msg;
}
?>
<div><?php echo $message; ?></div>
<!-- ********************************** -->
<!-- ********* randStrGen.php ********* -->
<!-- ********************************** -->
<?php
function randStrGen($len){
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz0123456789$$$$$$$1111111";
$charArray = str_split($chars);
for($i = 0; $i < $len; $i++){
$randItem = array_rand($charArray);
$result .= "".$charArray[$randItem];
}
return $result;
}
?>
is it possible to rewrite so different modules interact?

Related

sign up form Code not working

Hello Guys this is sign up form. Please read this code and try to answer
I have two problems with this code
1) I am getting a warning
Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\signup.php:252) in C:\xampp\htdocs\signup.php on line 295
2) When I click on Create account after filling form the button does nothing
i.e. it does not inserting values in table.
<?php
session_start();
// If user is logged in, header them away
if(isset($_SESSION["username"])){
header("location: message.php?msg=NO to that weenis");
exit();
}
?><?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("includes/db_connnection.php");
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?><?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("includes/db_connection.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$n = preg_replace('#[^a-z ]#i', '', $_POST['n']);
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$s = preg_replace('#[^a-z ]#i', '', $_POST['s']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($n == "" || $u == "" || $e == "" || $n == "" || $p == "" || $g == "" || $s == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$p_hash = md5($p);
//$cryptpass = hash('sha1',$p);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (name, username, email, password, gender, stream, ip, signup, lastlogin, notescheck)
VALUES('$n','$u','$e', '$p_hash','$g','$s','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "example#gmail.com";
$subject = 'yoursitename Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>yoursitename Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;"><img src="http://www.yoursitename.com/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">yoursitename Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* E-mail Address: <b>'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
#signupform{
margin-top:24px;
}
#signupform > div {
margin-top: 12px;
}
#signupform > input,select {
width: 200px;
padding: 3px;
background: #F3F9DD;
}
#signupbtn {
font-size:18px;
padding: 12px;
}
#terms {
border:#CCC 1px solid;
background: #F5F5F5;
padding: 12px;
}
</style>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var n = _("name").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var s = _("stream").value;
var g = _("gender").value;
var status = _("status");
if(n == "" || u == "" || e == "" || n == "" || p1 == "" || p2 == "" || s == "" || g == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else if( _("terms").style.display == "none"){
status.innerHTML = "Please view the terms of use";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&n="+n+"&e="+e+"&n="+n+"&p="+p1+"&s="+s+"&g="+g);
}
}
function openTerms(){
_("terms").style.display = "block";
emptyElement("status");
}
/* function addEvents(){
_("elemID").addEventListener("click", func, false);
}
window.onload = addEvents; */
</script>
</head>
<body>
<div id="pageMiddle">
<h3>Sign Up Here</h3>
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Name:</div>
<input id="name" type="text" onfocus="emptyElement('status')">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="88">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="100">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<div>Stream:</div>
<select id="stream" onfocus="emptyElement('status')">
<option disabled selected value>--select your option--</option>
<option value="Arts">India</option>
<option value="Biology">USA</option>
<option value="Maths">Russia</option>
</select>
<div>
<a href="#" onclick="return false" onmousedown="openTerms()">
View the Terms Of Use
</a>
</div>
<div id="terms" style="display:none;">
<h3>Web Intersect Terms Of Use</h3>
<p>1. Play nice here.</p>
<p>2. Take a bath before you visit.</p>
<p>3. Brush your teeth before bed.</p>
</div>
<br /><br />
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
</div>
</body>
</html>
<?php
if (isset($_GET['id']) && isset($_GET['u']) && isset($_GET['e']) && isset($_GET['p'])) {
// Connect to database and sanitize incoming $_GET variables
include_once("includes/db_connection.php");
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
$e = mysqli_real_escape_string($db_conx, $_GET['e']);
$p = mysqli_real_escape_string($db_conx, $_GET['p']);
// Evaluate the lengths of the incoming $_GET variable
if($id == "" || strlen($u) < 3 || strlen($e) < 5 || strlen($p) != 74){
// Log this issue into a text file and email details to yourself
header("location: message.php?msg=activation_string_length_issues");
exit();
}
// Check their credentials against the database
$sql = "SELECT * FROM users WHERE id='$id' AND username='$u' AND email='$e' AND password='$p' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
// Evaluate for a match in the system (0 = no match, 1 = match)
if($numrows == 0){
// Log this potential hack attempt to text file and email details to yourself
header("location: message.php?msg=Your credentials are not matching anything in our system");
exit();
}
// Match was found, you can activate them
$sql = "UPDATE users SET activated='1' WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
// Optional double check to see if activated in fact now = 1
$sql = "SELECT * FROM users WHERE id='$id' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
// Evaluate the double check
if($numrows == 0){
// Log this issue of no switch of activation field to 1
header("location: message.php?msg=activation_failure");
exit();
} else if($numrows == 1) {
// Great everything went fine with activation!
header("location: message.php?msg=activation_success");
exit();
}
} else {
// Log this issue of missing initial $_GET variables
header("location: message.php?msg=missing_GET_variables");
exit();
}
?>
ajax.js file
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
main.js file
function _(x){
return document.getElementById(x);
}
function toggleElement(x){
var x = _(x);
if(x.style.display == 'block'){
x.style.display = 'none';
}else{
x.style.display = 'block';
}
}

PHP and AJAX registration form for start page

I am learning to create a social ntwk. I hv used an AJAX framework for the signup page and it wked. Now I am trying to use the same framewk for the start page . Its nt wking. The problems are with the gender conditionals. The submit button does nt click.Hw cn I fix this code so that form submits whn user is either male or female
}
$sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$gender = $row["gender"];
}
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["f"])){
// CONNECT TO THE DATABASE
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$f = preg_replace('#[^a-z0-9]#i', '', $_POST['f']);
$l = preg_replace('#[^a-z0-9]#i', '', $_POST['l']);
$wt= preg_replace('#[^a-z ]#i', '', $_POST['wt']);
$a= preg_replace('#[^a-z ]#i', '', $_POST['a']);
$ws= preg_replace('#[^a-z ]#i', '', $_POST['ws']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// FORM DATA ERROR HANDLING
if($f == "" || $l == "" || $wt || $a == "" || $ws || $c == "" ){
echo "The form submission is missing values.";
exit();
} else {
// Add user info into the database table for the main site table
$sql = "UPDATE users SET firstname='$f', lastname ='$l', wagsbooty ='$wt', abs ='$a', wagsboobs ='$ws', crash ='$c' WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
echo "startup_success";
exit();
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="style/style.css">
<style type="text/css">
#startupform{
margin-top:24px;
}
#startupform > div {
margin-top: 12px;
}
#startupform > input,select {
width: 200px;
padding: 3px;
background: #F3F9DD;
}
#startupbtn {
font-size:18px;
padding: 12px;
}
</style>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function startup(){
var f = _("firstname").value;
var l = _("lastname").value;
var wt = _("wagsbooty").value;
var a = _("abs").value;
var ws = _("wagsboobs").value;
var c = _("crash").value;
var status = _("status");
if(f == "" || l == "" wt || a == "" || ws || c == "" ){
status.innerHTML = "Fill out all of the form data";
} else {
_("startupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "start_page1.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "startup_success"){
status.innerHTML = ajax.responseText;
_("startupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("startupform").innerHTML = "OK!";
}
}
}
ajax.send("f="+f+"&l="+l+"&wt="+wt+"&a="+a+"&ws="+ws+"&c="+c);
}
}
</script>
</head>
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
<h3>Fill in this form to create your profile!</h3>
<form name="startupform" id="startupform" onsubmit="return false;">
<div>Firstname: </div>
<input id="firstname" type="text" onfocus="emptyElement('status')" maxlength="16">
<br /><br />
<div>Lastname: </div>
<input id="lastname" type="text" onfocus="emptyElement('status')" maxlength="16">
<br /><br />
<div>
<?php
if($gender === 'm'){
echo "WAG with hottest booty :";?></br>
<select id="wagsbooty" onfocus="emptyElement('status')" maxlength="255">
<?php include_once("template_wags_list.php");
}else{
echo "Star with hottest abs:";?></br>
<select id="abs" onfocus="emptyElement('status')" maxlength="255">
<?php include_once("template_abs_list.php");
}
?>
</select>
</div>
</br>
<div>
<?php
if($gender === 'm'){
echo "WAG with hottest boobs :";?></br>
<select id="wagsboobs" onfocus = "emptyElement('status')" maxlength="255">
<?php include_once("template_boobs_list.php");
}else{
echo "I have a crash on :";?></br>
<select id="crash" onfocus ="emptyElement('status')" maxlength="255">
<?php include_once("template_crash_list.php");
}
?>
</div>
</select>
</br>
</br>
<button id="startupbtn" onclick="startup()">Create Profile</button>
<span id="status"></span>
</form>
</div>
<?php include_once("template_pageBottom.php"); ?>
</body>
</html>
You don't have anywhere on the page for the user to select their gender within the page - you should add either a radio button or a select box to the page and pass that info to the startup() function.

php and mysql allowing successful login for emails with _ and other special characters

hi can someone please help me. i have a login script and when i set a users username to eric#email.com it works fine but if their email is eric_1#email.com and other special characters it echoes out the count error 1 where it says there was one error in the form.
how can i allow my script to succesfully log in user with _ in their email or with any other special characters? im really new to php and mysql and would really be greatful if someone could show me how to fix this.
<?php
if (logged_in())
{
$_SESSION['login_message']="<div class=\"login-overlay\"></div><div class=\"login-box\"><div class=\"loginframe2\">
<h1>Login You In Securely </h1>
<p> PlaytimeBoys.com is login you in securely. Please wait.<br/><br/>
<div class=\"login-logo\">
<img src=\"assets/css/photobox/loading.gif\" width=\"24\" height=\"24\"><div class=\"login-text-logo\">Login You In. Please Wait</div></div>
</div></div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
}
include_once("includes/form_functions.php");
// START FORM PROCESSING
if (isset($_POST['submit'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data
$required_fields = array('email', 'password');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
$fields_with_lengths = array('email' => 30, 'password' => 30);
$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));
$email = trim(mysql_prep($_POST['email']));
$password = trim(mysql_prep($_POST['password']));
$hashed_password = md5($password);
if ( empty($errors) ) {
// Check database to see if email and the hashed password exist there.
$query = "SELECT id, email, close_account ";
$query .= "FROM ptb_users ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND password = '{$hashed_password}' ";
$query .= "AND close_account = '0' ";
$query .= "LIMIT 1";
$result_set = mysql_query($query);
confirm_query($result_set);
if (mysql_num_rows($result_set) == 1) {
// email/password authenticated
// and only 1 match
$found_user = mysql_fetch_array($result_set);
$_SESSION['user_id'] = $found_user['id'];
$_SESSION['email'] = $found_user['email'];
$_SESSION['sub_expires'] = $found_user['subscription_expires'];
$result = mysql_query("UPDATE ptb_users SET user_online='Online' WHERE id=".$_SESSION['user_id']."")
or die(mysql_error());
if($result)
{
$_SESSION['login_message']="<div class=\"login-overlay\"></div><div class=\"login-box\"><div class=\"loginframe2\">
<h1>Login You In Securely </h1>
<p>login you in securely. Please wait.<br/><br/>
<div class=\"login-logo\">
<img src=\"assets/css/photobox/loading.gif\" width=\"24\" height=\"24\"><div class=\"login-text-logo\">Login You In. Please Wait</div></div>
</div></div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
}
}else{
// email/password combo was not found in the database
$message = "<div class=\"infobox_out\"><strong>Email / Password combination incorrect.</strong><br />
Please make sure your caps lock key is off and try again.</div>";
echo "<div class=\"infobox-close2\"></div>";
}
} else {
if (count($errors) == 1) {
$message = "<div class=\"infobox_out\">There was 1 error in the form.<div>";
} else {
$message = "<div class=\"infobox_out\">There were " . count($errors) . " errors in the form.<div>";
}
}
} else { // Form has not been submitted.
if (isset($_GET['logout']) && $_GET['logout'] == 1) {
$message = "<div class=\"infobox\">You are now logged out.</div>";
echo "<div class=\"infobox-close3\"></div>";
} else { // Form has not been submitted.
if (isset($_GET['logout']) && $_GET['logout'] == 5) {
$message = "<div class=\"infobox-noprofile2\"><strong>Account Banned -</strong> We could not log you in because your account's<br/> been banned. Contact us at: Support#admin.com.</div>";
echo "<div class=\"infobox-close12\"></div>";
} else { // Form has not been submitted.
if (isset($_GET['logout']) && $_GET['logout'] == 6) {
$message = "<div class=\"infobox-noprofile2\"><strong>Account Warning -</strong> You recently violated a condition in our User Policy. Due to this you are receiving this warning. If you continue to violate any policy<br/> your account will be banned. Review User Policy and<br/>login when ready.</div>";
echo "<div class=\"infobox-close12\"></div>";
} else { // Form has not been submitted.
if (isset($_GET['logout']) && $_GET['logout'] == 2) {
$message = "<div class=\"infobox_out\">Sorry, we've had to log you out. Your session has expired.</div>";
echo "<div class=\"infobox-close2\"></div>";
} else { // Form has not been submitted.
if (isset($_GET['logout']) && $_GET['logout'] == 1) {
$message = "<div class=\"infobox\">You are now logged out.</div>";
echo "<div class=\"infobox-close3\"></div>";
}
}
}
}
}
$email = "";
$password = "";
}
?>
<br/>
<?php if (!empty($message)) {echo "<p class=\"message\">" . $message . "</p>";} ?>
<form action="login.php" rel="shadowbox;height=300;width=500" method="post" >
<div class="row email">
<input type="email" id="email" name="email" placeholder="Email" value="<?php echo htmlentities($email); ?>" />
</div>
<div class="row password">
<input type="password" id="password" name="password" placeholder="Password" value="<?php echo htmlentities($email); ?>" />
</div>
<input type="submit" name="submit" value="Login >" />
</form>
<?php if (!empty($errors)) { display_errors($errors); } ?>
I don't know if I can find you an actual answer, but I can't see you using escape string here, which means your code could be subject to SQL injection. If the problem is something to do with the underscore being a special character, you should do this (you should be doing it anyway, really!)
$myescapedstring = escapestring($mystring)
You should be doing this for anything which is being passed to your database for querying.
You'd implement it like this:
$email = escapestring(trim(mysql_prep($_POST['email'])));
$password = escapestring(trim(mysql_prep($_POST['password'])));
$hashed_password = md5($password);

register page...doesn't work properly

i got my register page but when the submit button is pressed it doesn't carry out the checks that it should. instead it misses them all out for some strange reason and returns the page with no error text.
<?php
require "PasswordHash.php";
require "header.php";
require "globe.php";
echo "<body>
<div class='container'>";
echo "<div class='centered'>
<ul id='nav'>
<li><a href='login.php'>Home </a></li>
<li><a href='register.php'>Register</a></li>
<li><a href='forgotpassword.php'>Forgot Password</a></li>
<li><a href='contact.php'>Contact</a></li>
<li><a href='t&c.php'>Terms and Conditions</a></li>
</ul>";
echo"
<img src='banner1.jpg' width='800px' height='200px' />
<div class='regban'>
<img src='outsideimage/registertop.png' width='800px' height='40px' />
</div>
<div class='registertext'>
Registiring to Zone Wars allows you to be that one step closer to being part of our fantastic community! Simply register for free and with our quick registration form you will be playing very soon! <br />
<font color='red'><i>Please note registration is not currently taking place due to large maintenance. We are sorry for any inconvenience this may have caused. </i></font>";
$regsec = htmlentities($_SERVER['PHP_SELF']);
if (isset($_POST['register']))
{
$user = trim($_POST['user']);
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
$email = trim($_POST['email']);
$email2 = $_POST['email2'];
$gender = $_POST['gender'];
$error_string = '';
require_once('recaptchalib.php');
$privatekey = "HIDDEN AS ITS PRIVATE";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
$hasher = new PasswordHash(8, false);
$hash_cost_log2 = 8;
$hash_portable = FALSE;
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
function isValidEmail($email = '')
{
return preg_match("/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*#[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/ix",$email);
}
$userrow = mysqli_query($mysqli, "SELECT * FROM Persons WHERE username = '" . mysqli_real_escape_string($mysqli, $user) . "'");
$row_cnt = mysqli_num_rows($userrow);
$emailrow = mysqli_query($mysqli, "SELECT * FROM Persons WHERE email = '" . mysqli_real_escape_string($mysqli, $email) . "'");
$row_cnt1 = mysqli_num_rows($emailrow);
if (!$resp->is_valid) {
$error_string .= '<center>The reCAPTCHA wasnt entered correctly. Go back and try it again.</center><br />';
}
else if ($user == '') {
$error_string .= '<center>You left the Username field blank!.</center><br />';
}
else if (strlen($user) < 4) {
$error_string .= '<center>Your Username must be at least 4 characters long.</center><br />';
}
else if (strlen($user) > 8) {
$error_string .= '<center>You Username cannot be longer then 8 characters.</center><br />';
}
else if ( !preg_match("/^[a-z]+[\w.-]*$/i", $user) ) {
$error_string .='<center>Your username may only contain letters, numbers, dots, underscores, hyphen and start with a letter</center>';
}
else if ($row_cnt != 0) {
$error_string .= '<center>Your Username exists</center><br />';
}
else if ($pass1 == '')
{
$error_string .='<center>You left the password field blank.<br /></center>';
}
else if ($pass2 == '') {
$error_string .='<center>You left the confirmation password blank<br /></center>';
}
else if ($pass1 != $pass2) {
$error_string .='<center>Your password and confirmation password do not match<br /></center>';
}
else if(strlen($pass1) > 72) {
$error_string .='<center>Your password cannot be longer then 72 characters<br /></center>';
}
else if ($email == '') {
$error_string .='<center>You left the email field blank!.<br /></center>';
}
else if ($email != $email2) {
$error_string .='<center>Your email and confirmation email did not match.<br /></center>';
}
else if (!isValidEmail($email)) {
$error_string .= '<center>Please enter a valid email address.<br></center>';
}
else if ($row_cnt1 != 0) {
$error_string .= '<center>Your email address exists</center><br />';
}
else {
if ($error_string != '') {
echo "<font color=red> '$error_string' </font><br /><center> Please go back and fix the errors <a href=register.php>here</a></center>";
}
else {
$hash = $hasher->HashPassword($pass1);
get_post_var($user);
get_post_var($email);
$euser = mysqli_real_escape_string($mysqli, $user);
$eemail = mysqli_real_escape_string($mysqli, $email);
if (strlen($hash) >= 20) {
mysqli_query($mysqli, "INSERT INTO Persons (Username, Password, Email, Gender) VALUES ('$euser', '$hash', '$eemail', '$gender')");
echo "You have signed up to the game! Please login <a href='login.php'here</a>. ";
}
else
{
echo "<center>A fatal error occured. Please contact the Admin board</center><br />";
}
}
}
}
else
{
echo "
<form action='$regsec' method='POST'>
<table align='center' border='0'>
<tr><td align='right'>Username:</td><td><input type='text' name='user' /></td></tr>
<tr><td align='right'>Password:</td><td><input type='password' name='pass1' /></td></tr>
<tr><td align='right'>Confirm Password:</td><td><input type='password' name='pass2' /></td></tr>
<tr><td align='right'>Email Address:</td><td><input type='text' name='email' /></td></tr>
<tr><td align='right'>Confirm Email Address:</td><td><input type='text' name='email2' /></td></tr>
<tr><td align='right'>Gender:</td><td><select name='gender'><option value='Male'>Male</option><option value='Female'>Female</option></select></td></tr>
<tr><td colspan='2'><center>";
require_once('recaptchalib.php');
$publickey = "HIDDEN AS ITS PRIVATE"; // you got this from the signup page
echo recaptcha_get_html($publickey);
echo "</center></td><td></td></tr>
<tr><td colspan='2'><center>By registring you have read and agreed our <a href='t&c.php'>Terms and Conditions</a></center></td><td></td></tr>
<tr><td colspan='2'><center><input type='submit' name='register' value='register'></center></td><td></td></tr>
</table></form>";
}
echo "</div>
<img src='outsideimage/registerbott.png' width='800px' height='20px' />
</div>";
echo " <br />
<div class='image'>
<img alt='' src='outsideimage/bottom.png' />
<div class='text'>
<small>Copyright © 2012 All Rights Reserved.</small>
</div>
<div class='text1'>
<small>";
date_default_timezone_set('Europe/London');
echo date('l jS \of F Y h:i:s A');
echo "</small>
</div>
</div>
</body>";
?>
You are not getting any error messages because you are not printing it out. You assign your error messages to variable $error_string, but there's no where in the code where it prints it out. Try putting an echo after your last else statement.
if (!$resp->is_valid) {
...
}
else if ($user == '') {
...
}
else if (strlen($user) < 4) {
...
}
...
else {
...
}
echo $error_string;
Also, seems like the last else in your validation seems unnecessary since you're checking if $error_string is empty or not.

Ajax not refreshing

I am trying to setup a register box to create new account. I am trying to load the html form through ajax and passing data to a php file.
I want to make the div which is containing the form to reload every time when the "register" button is hit to get the result from the php script and display it out. However, my code seems not working properly (The ajax handling div will not load the form ). Below are my codes:
Register.php:
<?php
session_start();
$email = $_POST['email'];
$email = mysql_real_escape_string($email);
$pwd = $_POST['pwd'];
$repwd = $_POST['repwd'];
$lname = $_POST['lname'];
$fname = $_POST['fname'];
$isValidEmail = 1;
if (substr_count($email, '#') != 1){
$isValidEmail = 0;
}
if($pwd != $repwd){ //check if password and re-entered passwords are the same
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Password and Re-entered Password are different.';
} else if( strlen($pwd) < 6 || strlen($pwd) > 64 ) { //check if password is 6 - 64 characters
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Password must be 6 - 64 characters.';
} else if( strlen($email) > 255) { //check if the email is too long
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Email exceeded maximum length.';
} else if ($isValidEmail != 1){
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Invalid Email.';
} else if (ctype_space($lname) || ctype_space($fname)){
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Please enter your name.';
} else {
if ($mysqli = new mysqli("localhost", "root", "", "my_db")){
$stmt = $mysqli->prepare("SELECT email FROM users WHERE email = ?");
$stmt->bind_param('s',$email);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
$stmt->close();
if ($result == $email) { //check if the input email exists in the database, duplicated user
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Email '.$email.' is already used.';
} else {
$hash = hash('sha256', $pwd);
function createSalt()
{
$string = md5(uniqid(rand(), true));
return substr($string, 0, 3);
}
$salt = createSalt();
$hash = hash('sha256', $salt . $hash);
$stmt = $mysqli->prepare("INSERT INTO users ( email, lastName, firstName, password, salt )
VALUES ( ? , ?, ?, ? ,? )");
$stmt->bind_param('sssss', $email, $lname, $fname, $hash, $salt);
if ($stmt->execute()){
$_SESSION['message'] = 'Registered.';
} else {
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Database query error occured.';
}
$stmt->close();
}
} else {
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Error connecting to the database.';
}
}
header("Location: Home.php");
$mysqli->close();
?>
ajax.js:
$(document).ready(function() {
$('#submit_register').click(function(){
$('#register_form').submit( function(){
$.ajax({
type: 'POST',
url : 'Register.php',
data: $('#register_form').serialize(),
success: function () {
var myURL = "Register_form.php#register_div";
$('#ajaxHandle').load(myURL);
return false;
},
});
});
});
});
Register_form.php:
<!DOCTYPE html>
<html lang="en">
<head>
<?php session_start(); ?>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div class="span-23 prepand-top last" id="register_div" style="background:gray;">
<div id="wrapper_register" class="span-21 last" style="padding-top: 20px; padding-left:20px; padding-bottom:20px;">
<form id="register_form" action="register.php" method="post">
<legend class="large">Register</legend>
<?php
if ($_SESSION['message']){
$class = "";
if ($_SESSION['error']){
$class = "error";
} else {
$class = "success";
}
echo "<div class=\"$class span-4 last\">";
echo $_SESSION['message'];
echo "</div>";
unset ($_SESSION['error']);
unset ($_SESSION['message']);
}
?>
<div class="span-23 prepand-top last">
<p>E-mail address: <br>
<input type="text" name="email" maxlength="255" /></p><br>
<p>Last Name: <br><input type="text" name="lname" maxlength="255" /></p><br>
<p>First Name: <br>
<input type="text" name="fname" maxlength="255" /></p><br>
<p>Password: <br>
<input type="password" name="pwd" /><p class="quiet">6 - 64 characters</p><br>
<p>Re-enter Password: <br><input type="password" name="repwd" /></p><br>
<input id="submit_register" type="submit" value="Register" /><br>
</div>
</form>
</div>
</div>
</body>
</html>
I am doing something wrong? Any advice will be appreciated. Thank you very much!
I think I figured it out. I have put the refreshing jquery code in the wrong place. It worked when I put it within the .submit scope:
$(document).ready(function() {
$('#submit_register').click(function(){
$('#register_form').submit( function(){
$.post(
'Register.php',
$(this).serialize()
);
var myURL = "Register_form.php#register_div";
$('#ajaxHandle').load(myURL);
return false;
});
});
});

Categories