sign up form Code not working - php

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';
}
}

Related

Register isn't creating new users in database

Whenn i will signup in signup.php... The problem is that when I press submit, the credentials are not inserted into the database. Can someone please help me out? Whenn i click on submit thenn i don't get error but succesfully registered.. My php version in directadmin is 5.1.
This is my code of my signup.php:
<head>
<title>.:: NitanCrime ::.</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<?php /* ------------------------- */
include("yep.php");
if(check_login()) {
print "<html>";
print "<head>";
print "<LINK href='images/mxstyle.css' type=text/css rel=stylesheet>";
print "</head>";
print "<body style='background: #grey; margin: 100px;'>";
print "<table align='center' width=100%>";
print "<tr>Je bent al ingelogd</tr>";
mysql_query("DELETE FROM `[online]` WHERE `login`='{$_COOKIE['login']}' AND `validate`='{$_COOKIE['validate']}' AND `IP`='{$_SERVER['REMOTE_ADDR']}'");
unset($_SESSION['login']);
unset($_SESSION['IP']);
unset($_SESSION['data']);
print <<<ENDHTML
</table>
}
</body>
</html>
ENDHTML;
exit;
}
$inboxchek =1;
if(isset($_GET['v']) && ($_GET['v'] == 1 || $_GET['v'] == 2)) {
setcookie("v",$_GET['v'],time()+24*60*60*365,"/","");
$_COOKIE['v'] = $_GET['v'];
}
if(isset($_GET['baas'])) {
setcookie("baas",$_GET['baas'],time()+24*60*60*365,"/","");
$_COOKIE['baas'] = $_GET['baas'];
}
if(!isset($_GET['baas'])) {
setcookie("baas","",time()+24*60*60*365,"/","");
$_COOKIE['baas'] = "";
}
if(isset($_COOKIE['login'],$_COOKIE['validate'])) {
setcookie("login",$_COOKIE['login'],time()+24*60*60,"/","");
setcookie("validate",$_COOKIE['validate'],time()+24*60*60,"/","");
}
mysql_query("UPDATE `[users]` SET `online`=NOW() WHERE `login`='{$data->login}'");
$ref = $_GET['x'];
$dbres = mysql_query("SELECT `id` FROM `[users]` WHERE `activated`=1");
$members = mysql_num_rows($dbres);
$dbres = mysql_query("SELECT `id` FROM `[users]` WHERE `level`=100");
$paymembers = mysql_num_rows($dbres);
$dbres = mysql_query("SELECT `id` FROM `[users]` WHERE UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(`online`) < 300");
$online = mysql_num_rows($dbres);
$chek = mysql_query("SELECT `login` FROM `[users]` WHERE `login`='$ref'");
$ok = mysql_num_rows($chek);
function ip() {
if(getenv('HTTP_X_FORWARDED_FOR')) {
return getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('HTTP_CLIENT_IP')) {
return getenv('HTTP_CLIENT_IP');
} else {
return getenv('REMOTE_ADDR');
}
}
$baas = $_COOKIE['baas'];
$IP = ip();
$login = $_POST['login'];
$pass = $_POST['pass'];
$passconfirm = $_POST['passconfirm'];
$email = $_POST['email'];
$type = $_POST['type'];
${"select$type"} = "selected";
if(isset($_POST['submit'])) {
$Dupe = mysql_query("SELECT * FROM `[users]` WHERE `IP`='{$_SERVER['REMOTE_ADDR']}' AND `level`='2'");
$dU = mysql_num_rows($Dupe);
if($dU >=2){ echo " Je Mag Slechts 1 Account per Ip Adres Hebben! $dU"; exit; }
$message = Array(
"Je login mag alleen A-Z, a-z, 0-9, _ en - hebben",
"Vul een geldig e-mail adres in",
"Selecteer een type crimineel",
"Er bestaat al iemand met die login",
"Er is al iemand met die e-mail");
$msgnum = -1;
if(preg_match('/^[a-zA-Z0-9_\-]+$/',$login) == 0)
$msgnum = 0;
if(preg_match('/^.+#.+\..+$/',$email) == 0)
$msgnum = 1;
else {
$dbres = mysql_query("SELECT `id` FROM `[users]` WHERE `login`='$login'");
if(mysql_num_rows($dbres) > 0)
$msgnum = 3;
$dbres = mysql_query("SELECT `id` FROM `[users]` WHERE `email`='$email'");
if(mysql_num_rows($dbres) > 0)
$msgnum = 4;
$clientIP = $IP;
$forwardedFor = ($_SERVER['HTTP_X_FORWARDED_FOR'] != "") ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['HTTP_CLIENT_IP'];
$forwardedFor = preg_replace('/, .+/','',$forwardedFor);
if($ref !='' AND $ok == 0){ echo " Foutive Refferal $ref "; exit; }
if($msgnum == -1) {
$code = rand(100000,999999);
$passs = rand(100000,999999);
$land = rand(1,4);
mysql_query("UPDATE `[users]` SET `land`='1' WHERE `login`='$data->login'");
mysql_query("INSERT INTO `[users]`(`signup`,`login`,`pass`,`regIP`,`email`,`land`) values(NOW(),'$login',MD5('$passs'),'$IP','$email','$land')");
mysql_query("UPDATE `[users]` SET `cash`=`cash`+'10000',`ervaring`=`ervaring`+'500' WHERE `login`='$ref'");
mysql_query("INSERT INTO `[messages]`(`time`,`IP`,`forwardedFor`,`from`,`to`,`subject`,`message`) values(NOW(),'{$_SERVER['REMOTE_ADDR']}','$forwardedFor',' NitanCrime ','$ref','Refferal','Je Maakte $login lid op NitanCrime! Je verdiende 10,000')");
mysql_query("INSERT INTO `[temp]`(login,IP,code,area,time) values('$login','$IP',$code,'$land','signup',NOW())");
$id = mysql_insert_id();
mail($email,"NitanCrime Aanmelding","Hey!\n Welkom op NitanCrime\n\nBedankt voor u registratie. U kunt nu inloggen!\n\nHier is u informatie:\n\nGebruikersnaam: $login\nWachtwoord: $passs\n\nOnthoud u wachtwoord goed, deze kan niet meer achterhaald worden. Deze kan echter wel veranderd worden!\n\nVriendelijke groeten,\n\n NitanCrime","From: NitanCrime <aanmelding#nitancrime.com>\n");
}
}
}
/* ------------------------- */ ?>
<HTML>
<HEAD>
</HEAD>
<body>
<?
if($msgnum != -1) {
if(isset($msgnum) && $msgnum != -1)
print "<td><center>{$message[$msgnum]}</center></td>\n";
if($_GET['x'] == "") {
$baas = "(Geen)";
}
else {
$baas = $_GET['x'];
}
print <<<ENDHTML
<table style="position: absolute; left: 270px; top: 148px;" border=0 cellspacing=0 cellpadding=0>
<form method="post">
<BR><BR><BR>
<table cellspacing="1" cellpadding="2" align="center">
<tr><td align=center colspan="2" class=main><b>Aanmelden</b></td></tr>
<tr><td class=sub width=100><font color=black>Gebruikersnaam:</font></td>
<td class=sub><INPUT name="login" type="text" VALUE='' maxlength="16" style="width: 150;"></td></tr>
<tr><td class=sub width=100><font color=black>Email:</font></td>
<td class=sub><INPUT name="email" type="text" VALUE='' style="width: 150;"></td></tr>
<td class=sub colspan="2" align=center><input type="submit" name="submit" style=" height: 20; width: 110;" value="Aanmelden"></td>
</table>
</tr></form>
ENDHTML;
}
else
print " Je bent aangemeld!, Er is een e-mail gestuurd naar $email met Je wachtwoord! <b>Check u Ongewenste Mail!</b>\n";
?>
</BODY>
</HTML>
<? mysql_close($mysql); ?>
I don't exactly know what [] is for or {} is for, but your '' and "" are messing each other up.
$sql = "DELETE FROM `online` WHERE `login`='$username' LIMIT 1";
mysql_query($sql);
The above piece should work fine, the problem comes from when accessing arrays in php 5.
$sql = "DELETE FROM `online` WHERE `login`='$_COOKIE['login']' LIMIT 1";
mysql_query($sql);
The above line won't work because of the double ''. To get around this try.
$sql = "DELETE FROM `online` WHERE`login`='".$_COOKIE['online']." LIMIT 1";
mysql_query($sql);
Use the double quotes to exit the str, so you can insert your variable.
Hope this helps,
Side note: I'm not exactly sure if it is spacing, but it looks like you have an open if statement somewhere in there.
Also if you are using php 5, mysqli should work just fine. You should still change it mysqli. In many cases, it is faster and more secure. There isn't any more work.

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

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?

AJAX & PHP form validation

Im currently learning my way with ajax. Im trying to make a register / login system with AJAX. I finished the register form and is now working but im having problems with the login one.
ajax/login.php PHP Vaidation for Login
<?php
require_once("../core/config.php");
$username = trim(strip_tags($_POST['username']));
$password= trim(strip_tags($_POST['password']));
$errors = false;
$user_query = $db->query("SELECT * FROM users WHERE username='$username'");
// Empty check -> Username
if(empty($username) && strlen($username) == 0) { $error_username = "<span style='color:red;'> Username is empty </span>"; $errors = true; }
// Empty check -> Password
if(empty($password) && strlen($password) == 0) { $error_password = "<span style='color:red;'> Password is empty </span>"; $errors = true; }
// If exists check
$num = $user_query->num_rows;
if($num < 1) { $error_general = "<span style='color:red;'> User doesn't exist </span>"; $errors = true; } else {
$user = $user_query->fetch_object();
if($user->password != $password) { $error_general = "<span style='color:red;'> Invalid Username or Password </span>"; $errors = true; }
}
//
if($errors == true) {
?>
<?php if(isset($error_general)) { echo $error_general." <br><br>"; } ?>
<?php if(isset($error_username)) { echo $error_username; } ?>
<input type="text" name="login_username" id="login_username" placeholder="Username" value="<?php echo $username; ?>"> <br>
<?php if(isset($error_password)) { echo $error_password; } ?>
<input type="password" name="login_password" id="login_password" placeholder="Password" value="<?php echo $password; ?>">
<br>
<?php } else {
$_SESSION['User'] = true;
header("Location: ". $_SERVER['PHP_SELF']);
}
?>
index.php Form HTML & JS
<!DOCTYPE HTML>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
var loader = $("<div style='text-align: center; float:none; margin: 0 auto;'> <img src='loader-small.gif'> <br> Processing request... </div> <br>");
function process_login() {
var username = $("#login_username").val();
var password =$("#login_password").val();
$(".login_container").html(loader).load("ajax/login.php", {username: username, password: password})
}
</script>
</head>
<body>
<h3> Login </h3>
<form action="" method="POST">
<div class="login_container">
<input type="text" name="login_register" id="login_username" placeholder="Username"> <br>
<input type="password" name="login_password" id="login_password" placeholder="Password">
<br>
</div>
<input type="submit" onclick="process_login(); return false;" name="login_submit" value="Login" style="outline:none;">
</form>
</body>
</html>
When I submit the form with the correct information I get "User doesnt exist", "Username is empty", "Password is empty" and when I submit with wrong information I get "User doesnt exist"
I've been brainstorming for the last 3 hours, yet I have not found a way to fix it
Logical error:
// Empty check -> Username
if(empty($username) || strlen($username) == 0) { $error_username = "<span style='color:red;'> Username is empty </span>"; $errors = true; }
// Empty check -> Password
if(empty($password) || strlen($password) == 0) { $error_password = "<span style='color:red;'> Password is empty </span>"; $errors = true; }
Compare to you code:
// Empty check -> Username
if(empty($username) && strlen($username) == 0) { $error_username = "<span style='color:red;'> Username is empty </span>"; $errors = true; }
// Empty check -> Password
if(empty($password) && strlen($password) == 0) { $error_password = "<span style='color:red;'> Password is empty </span>"; $errors = true; }

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.

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