I have an update password page that won't let me enter the actual current password for the current password field. Instead, it wants the hashed password. Once changed however, the new one is then hashed, which is a good thing. I just need to be able to enter the actual password and not hashed.
Yes I know, no md5; this is more for testing is all.
changepassword.js
<script>
function validatePassword() {
var currentPassword,newPassword,confirmPassword,output = true;
currentPassword = document.frmChange.currentPassword;
newPassword = document.frmChange.newPassword;
confirmPassword = document.frmChange.confirmPassword;
if(!currentPassword.value) {
currentPassword.focus();
document.getElementById("currentPassword").innerHTML = "required";
output = false;
}
else if(!newPassword.value) {
newPassword.focus();
document.getElementById("newPassword").innerHTML = "required";
output = false;
}
else if(!confirmPassword.value) {
confirmPassword.focus();
document.getElementById("confirmPassword").innerHTML = "required";
output = false;
}
if(newPassword.value != confirmPassword.value) {
newPassword.value="";
confirmPassword.value="";
newPassword.focus();
document.getElementById("confirmPassword").innerHTML = "not same";
output = false;
}
return output;
}
</script>
updatepassword.php
<?php
include 'core/login.php'; === this contains the connection, it's obviously good ===
include 'includes/head.php'; === changepassword.js is linked in the head ===
if(count($_POST)>0) {
$result = mysqli_query($link, "SELECT *from users WHERE id='" . $_SESSION["id"] . "'");
$row = mysqli_fetch_array($result);
if($_POST["currentPassword"] == $row["password"]) {
mysqli_query($link, "UPDATE users set `password`='" .md5(md5($_POST['newPassword'])) . "' WHERE id='" . $_SESSION["id"] . "'");
$message = "Password Changed";
} else $errormessage = "Current Password is not correct";
}
print_r($_SESSION);
?>
form on same page:
<div class="container">
<div class="text-center">
<h4>Change password below</h4>
</div><br />
<div class="message"><?php if(isset($message)) { echo $message; } ?></div>
<div class="message"><?php if(isset($errormessage)) { echo $errormessage; } ?></div>
<div class="col-md-4 col-md-offset-4">
<form name="frmChange" method="post" action="" onSubmit="return validatePassword()">
<div class="form-group">
<label>Current Password*</label>
<input type="text" name="currentPassword" class="form-control input-md" />
</div>
<div class="form-group">
<label>New Password*</label>
<input type="text" name="newPassword" class="form-control input-md" />
</div>
<div class="form-group">
<label>Confirm Password*</label>
<input type="text" name="confirmPassword" class="form-control input-md" />
</div>
<br />
<div class="text-center">
<input type="submit" name="submit" class="btn btn-success" value="Submit" />
</div>
</form>
</div>
</div>
Your problem is here:
if($_POST["currentPassword"] == $row["password"]) {
You are comparing the actual text version of the hash (say "password") to the hashed version of that password (say "213y789hwuhui1dh"). This evaluates out to:
if("password" == "213y789hwuhui1dh") {
Which obviously is never accurate. All you have to do to solve the problem is hash the password in the same way you did when you created it. If I understand your code properly, that should be:
if(md5(md5($_POST["currentPassword"]))==$row["password"]) {
SIDE NOTE ON SQL INJECTION
Please note that this code would be super easy to inject into. All a user would have to do is end the "currentPassword" POST value with '; SHOW DATABASE; and they would have unlimited access to your server's MySQL database. Consider learning to use MySQLi Prepared Statements. They are easy to understand, and easy to implement.
I went overboard. Your other question was closed. Juuuuust gonna leave this here... I'm using PHP version PHP 5.2.0.
http://php.net/manual/en/faq.passwords.php
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php
<?php
// so I don't actually have to test form submission, too...
$_POST['current_password'] = 'Tacotaco';
$_POST['new_password'] = 'NINrocksOMG';
$_POST['confirmPassword'] = 'NINrocksOMG';
$_SESSION['id'] = 1;
// this is Tacotaco encrypted... update your db to test
// update users set password = '$2y$10$fc48JbA0dQ5dBB8MmXjVqumph1bRB/4zBzKIFOVic9/tqoN7Ui59e' where id=1
// the following is sooooo ugly... don't leave it this way
if (!isset($_SESSION['id']) or empty($_SESSION['id']) or
!isset($_POST['current_password']) or empty($_POST['current_password']) or
!isset($_POST['new_password']) or empty($_POST['new_password']) or
!isset($_POST['confirmPassword']) or empty($_POST['confirmPassword']) ) {
$message = 'Please enter your password';
}
else {
$sid = $_SESSION['id'];
$currpass = $_POST['current_password'];
$newpass = $_POST['new_password'];
$conpass = $_POST['confirmPassword'];
$message = validate_password($sid, $currpass, $newpass, $conpass);
}
print "<br/>$message<br/>";
function validate_password($sid, $currpass, $newpass, $conpass) {
$mysqli = mysqli_connect('localhost','root','','test')
or die('Error ' . mysqli_error($link));
$stmt = $mysqli->prepare('select id, password from users where id = ?');
$stmt->bind_param("s", $sid);
$stmt->execute();
$stmt->bind_result($userid, $userpass);
$message = '';
if ($stmt->fetch()) {
$stmt->close();
if (strlen($newpass) < 8) {
$message = 'Please enter a password with at least 8 characters';
}
elseif (!preg_match('`[A-Z]`', $newpass)) {
$message = 'Please enter at least 1 capital letter';
}
elseif ($newpass !== $conpass) {
$message = 'Your passwords do not match.';
}
else {
if (password_verify($currpass, $userpass)) {
$hashed_new = password_hash($newpass, PASSWORD_BCRYPT);
$query = 'update users set password = ? where id = ?';
$stmt_new = $mysqli->prepare($query);
$stmt_new->bind_param('ss', $hashed_new, $sid);
if ($stmt_new->execute()) {
$message = 'Password Changed';
}
else {
$message = $mysqli->error;
}
}
else $message = 'Current Password is not correct';
}
}
else {
$message = 'user not found for id $sid';
}
$mysqli->close();
return $message;
}
?>
Related
My PHP username validation with Ajax duplicates my html page inside of html div(this is for showing ajax error) element. I tried some solutions and google it bu can't find anything else for solution. Maybe the problem is about the $_POST but I also separated them in php (all the inputs validation).
Here is PHP code
<?php
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
$infoun[] = 'Your username has at least 6 alphanumeric characters';
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['username'])){
$errorun[] = 'This username is already in use';
}
}
}
if(isset($_POST['fullname'])){
//fullname validation
$fullname = $_POST['fullname'];
if (! $user->isValidFullname($fullname)){
$infofn[] = 'Your name must be alphabetical characters';
}
}
if(isset($_POST['password'])){
if (strlen($_POST['password']) < 6){
$warningpw[] = 'Your password must be at least 6 characters long';
}
}
if(isset($_POST['email'])){
//email validation
$email = htmlspecialchars_decode($_POST['email'], ENT_QUOTES);
if (! filter_var($email, FILTER_VALIDATE_EMAIL)){
$warningm[] = 'Please enter a valid email address';
} else {
$stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
$stmt->execute(array(':email' => $email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['email'])){
$errorm[] = 'This email is already in use';
}
}
}
?>
Here is Javascript
<script type="text/javascript">
$(document).ready(function(){
$("#username").keyup(function(event){
event.preventDefault();
var username = $(this).val().trim();
if(username.length >= 3){
$.ajax({
url: 'register.php',
type: 'post',
data: {username:username},
success: function(response){
// Show response
$("#uname_response").html(response);
}
});
}else{
$("#uname_response").html("");
}
});
});
</script>
<input type="text" name="username" id="username" class="form-control form-control-user" placeholder="Kullanıcı Adınız" value="<?php if(isset($error)){ echo htmlspecialchars($_POST['username'], ENT_QUOTES); } ?>" tabindex="2" required>
<div id="uname_response" ></div>
Here is the screenshot:
form duplicate screenshot
The only code in your PHP file should be within the <?php ?> tags. You need to seperate your PHP code into another file.
I have never worked with $_COOKIES, and now I've been given the task to make it work.
I have been following a couple of tutorials online.
Found here: http://www.phpnerds.com/article/using-cookies-in-php/2
And then here:https://www.youtube.com/watch?v=Dsem42810H4
Neither of which worked for me.
Here is how my code ended up. I shortened it as much as I could.
Starting with the index.php page, which contains the initial login form:
<form role="form" action="index.php" method="post" id="loginForm" name="loginForm">
<input type="text" class="form-control" id="username" name="username"
value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" />
<input type="password" class="form-control" id="password" name="password"
value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>"/>
<button type="button" id="loginSubmit" name="loginSubmit" class="btn btn-primary btn-block btn-flat">Sign In</button>
<input type="checkbox" id="rememberme"
<?php if(isset($_COOKIE['username'])){echo "checked='checked'";} ?> value="1" />
</form>
Here is the JavaScript used to send the form values:
$('#loginSubmit').on('click', function()
{
var username = $('#username').val();
var password = $('#password').val();
var rememberme = $('#rememberme').val();
// skipping the form validation
$.post('api/checkLogin.php', {username: username, password: password, rememberme:rememberme}, function(data)
{
// the data returned from the processing script
// determines which page the user is sent to
if(data == '0')
{
console.log('Username/Password does not match any records.');
}
if(data == 'reg-user")
{
window.location.href = "Home.php";
}
else
{
window.location.href = "adminHome.php";
}
});
});
Here is the processing script, called checkLogin.php. This is where I attempt to set the $_COOKIE:
<?php
include ("../include/sessions.php");
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['password'])));
$rememberme = $_POST['rememberme'];
$select = "SELECT username, fullname, password FROM users WHERE username = '".$username."'";
$query = mysqli_query($dbc, $select);
$row = mysqli_fetch_array($query);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfullname = htmlentities(stripslashes($row['fullname']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword))
{
// setting sessions here
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $dbfullname;
// here is where I attempt to set the $_COOKIE
if(isset($remember))
{
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', $_POST['password'], time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false);
setcookie('password', $_POST['password'], false);
}
echo $username; // this gets sent back to the JavaScript
mysqli_free_result($query);
}
else
{
// username/password does not match any records
$out = 0;
echo $out;
}
}
?>
So now that I have attempted to set the $_COOKIE, I can try to print it to the home page, like so:
<?php echo 'cookie ' . $_COOKIE["username"]; ?>
To which does not work, because all I see is the word 'cookie'.
Besides that, when I log out, I am hoping to see the login form already filled out, which is the overall task I have been trying to complete, but have been unsuccessful at doing so.
I Have 2 problems with this script, something is wrong
1. the email address value can't be selected from the database.
the script works only if I manually type the e-mail
$yourEmail = "email#exemple.com";
after I press the submit button, I want the page to refresh without the website link being changed or after i click send, the contact box should close.
Could you please help to solve these problems?
Thank you in advance!
<?php
$sql = "select * from tables where email='" . $email . "'";
while($row=mysql_fetch_array($sql))
{
$email=$row['email'];
}
$yourEmail = $email; // the email address you wish to receive these mails through
$yourWebsite = "WEBSITE NAME";
$thanksPage = ''; // URL to 'thanks for sending mail' page; leave empty to keep message on the same page
$maxPoints = 4;
$requiredFields = "name,email,comments";
$error_msg = array();
$result = null;
$requiredFields = explode(",", $requiredFields);
function clean($data) {
$data = trim(stripslashes(strip_tags($data)));
return $data;
}
function isBot() {
$bots = array("Indy", "Blaiz", "Java", "libwww-perl", "Python", "OutfoxBot", "User-Agent", "PycURL", "AlphaServer", "T8Abot", "Syntryx", "WinHttp", "WebBandit", "nicebot", "Teoma", "alexa", "froogle", "inktomi", "looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory", "Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot", "crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz");
foreach ($bots as $bot)
if (stripos($_SERVER['HTTP_USER_AGENT'], $bot) !== false)
return true;
if (empty($_SERVER['HTTP_USER_AGENT']) || $_SERVER['HTTP_USER_AGENT'] == " ")
return true;
return false;
}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (isBot() !== false)
$error_msg[] = "No bots please! UA reported as: ".$_SERVER['HTTP_USER_AGENT'];
// lets check a few things - not enough to trigger an error on their own, but worth assigning a spam score..
// score quickly adds up therefore allowing genuine users with 'accidental' score through but cutting out real spam :)
$points = (int)0;
$badwords = array("adult", "beastial", "bestial", "blowjob", "clit", "cum", "cunilingus", "cunillingus", "cunnilingus", "cunt", "ejaculate", "fag", "felatio", "fellatio", "fuck", "fuk", "fuks", "gangbang", "gangbanged", "gangbangs", "hotsex", "hardcode", "jism", "jiz", "orgasim", "orgasims", "orgasm", "orgasms", "phonesex", "phuk", "phuq", "pussies", "pussy", "spunk", "xxx", "viagra", "phentermine", "tramadol", "adipex", "advai", "alprazolam", "ambien", "ambian", "amoxicillin", "antivert", "blackjack", "backgammon", "texas", "holdem", "poker", "carisoprodol", "ciara", "ciprofloxacin", "debt", "dating", "porn", "link=", "voyeur", "content-type", "bcc:", "cc:", "document.cookie", "onclick", "onload", "javascript");
foreach ($badwords as $word)
if (
strpos(strtolower($_POST['comments']), $word) !== false ||
strpos(strtolower($_POST['name']), $word) !== false
)
$points += 2;
if (strpos($_POST['comments'], "http://") !== false || strpos($_POST['comments'], "www.") !== false)
$points += 2;
if (isset($_POST['nojs']))
$points += 1;
if (preg_match("/(<.*>)/i", $_POST['comments']))
$points += 2;
if (strlen($_POST['name']) < 3)
$points += 1;
if (strlen($_POST['comments']) < 15 || strlen($_POST['comments'] > 1500))
$points += 2;
if (preg_match("/[bcdfghjklmnpqrstvwxyz]{7,}/i", $_POST['comments']))
$points += 1;
// end score assignments
foreach($requiredFields as $field) {
trim($_POST[$field]);
if (!isset($_POST[$field]) || empty($_POST[$field]) && array_pop($error_msg) != "Please fill in all the required fields and submit again.\r\n")
$error_msg[] = "Please fill in all the required fields and submit again.";
}
if (!empty($_POST['name']) && !preg_match("/^[a-zA-Z-'\s]*$/", stripslashes($_POST['name'])))
$error_msg[] = "The name field must not contain special characters.\r\n";
if (!empty($_POST['email']) && !preg_match('/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i', strtolower($_POST['email'])))
$error_msg[] = "That is not a valid e-mail address.\r\n";
if (!empty($_POST['url']) && !preg_match('/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i', $_POST['url']))
$error_msg[] = "Invalid website url.\r\n";
if ($error_msg == NULL && $points <= $maxPoints) {
$subject = "Automatic Form Email";
$message = "You received this e-mail message through your website: \n\n";
foreach ($_POST as $key => $val) {
if (is_array($val)) {
foreach ($val as $subval) {
$message .= ucwords($key) . ": " . clean($subval) . "\r\n";
}
} else {
$message .= ucwords($key) . ": " . clean($val) . "\r\n";
}
}
$message .= "\r\n";
$message .= 'IP: '.$_SERVER['REMOTE_ADDR']."\r\n";
$message .= 'Browser: '.$_SERVER['HTTP_USER_AGENT']."\r\n";
$message .= 'Points: '.$points;
if (strstr($_SERVER['SERVER_SOFTWARE'], "Win")) {
$headers = "From: $yourEmail\r\n";
} else {
$headers = "From: $yourWebsite <$yourEmail>\r\n";
}
$headers .= "Reply-To: {$_POST['email']}\r\n";
if (mail($yourEmail,$subject,$message,$headers)) {
if (!empty($thanksPage)) {
header("Location: $thanksPage");
exit;
} else {
$result = 'Your mail was successfully sent.';
$disable = true;
}
} else {
$error_msg[] = 'Your mail could not be sent this time. ['.$points.']';
}
} else {
if (empty($error_msg))
$error_msg[] = 'Your mail looks too much like spam, and could not be sent this time. ['.$points.']';
}
}
function get_data($var) {
if (isset($_POST[$var]))
echo htmlspecialchars($_POST[$var]);
}
?>
html form
<form action="<?php echo basename(__FILE__); ?>" method="post">
<noscript>
<p><input type="hidden" name="nojs" id="nojs" /></p>
</noscript>
<p>
<label for="name">Name: *</label>
<input type="text" name="name" id="name" value="<?php get_data("name"); ?>" /><br />
<label for="email">E-mail: *</label>
<input type="text" name="email" id="email" value="<?php get_data("email"); ?>" /><br />
<label for="url">Website URL:</label>
<input type="text" name="url" id="url" value="<?php get_data("url"); ?>" /><br />
<label for="location">Location:</label>
<input type="text" name="location" id="location" value="<?php get_data("location"); ?>" /><br />
<label for="comments">Comments: *</label>
<textarea name="comments" id="comments" rows="5" cols="20"><?php get_data("comments"); ?></textarea><br />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Send" <?php if (isset($disable) && $disable === true) echo ' disabled="disabled"'; ?> />
</p>
</form>
Before your while loop your suppose to actually perform the query with mysql_query or mysqli_query in your case mysql_query.
Your other problem is your fetching the results as an array which is index based (0...) and your using a string to access it so you should call mysql_fetch_assoc which returns an associative array which can be accessed in your current implementation
$sql = "select * from tables where email='" . $email . "'";
$result = mysql_query($sql, $connection);// this actually performs the query and returns the result to be fetched using mysql_fetch_array or it's other methods such as mysql_fetch_assoc
while($row=mysql_fetch_assoc($result)){
$email=$row['email'];
}
Also declare your $email variable outside the while loop as if no rows were returned from the database your $email variable won't exist therefore breaking your code so you should bring it to the top of the while loop and initialize it to some default value.
Uncaught ReferenceError: ajaxObj is not definednewsletter #
main.js:22onclick # index.php:541
I am trying to develop a newsletter which will be on the footer part of the every page and it will use NAME and EMAIL to suscribe. It will grab the data entered by user from HTML form and pass it to ajax for validation after usere click submit which will pass information to newsletter.php and give back message to user if they already exist or signup sucessfull message but what happened is as User click submit button it just says "Please wait.." and keeps on loading forever giving above message on chrome cousole.
I want user to be able to sign up from any page they are on without reloading page.
The problem here is
Above Error given in Chrome cousole while I try to submit the form.
Thank you for looking at my problem. Any help will be appriciated..
HTML
<?php include_once('newsletter.php'); ?>
<form name="signupform" id="signupform" method="POST" onsubmit="return false;">
<p align="center"><strong>NEWSLETTER SIGNUP :</strong>
<input id="sus_name" name="sus_name" type="text" placeholder="Enter your Name" size="15">
<input id="sus_email" name="sus_email" type="text" placeholder="Enter your Email" size="26">
<input id="optin" name="optin" type="submit" value="SUBSCRIBE" onclick="newsletter()"><br>
<span id="status"></span>
</p>
</form>
AJAX
//News Letter Validation
function newsletter(){
var u = document.getElementById("sus_name").value;
var e = document.getElementById("sus_email").value;
var m =(document.URL);
var status = document.getElementById("status");
if(u == "" || e == ""){
status.innerHTML = "Fill out all of the form data";
} else {
document.getElementById("optin").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST","(document.URL)");//Problem with this line as i want it to post to same page where url will be dynamic
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
document.getElementById("optin").style.display = "block";
} else {
window.scrollTo(0,0);
document.getElementById("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> ";
}
}
}
ajax.send("u="+u+"&e="+e);
}
}
newsletter.php
<?php
$msg_to_user = "";
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once "includes/mysqli_connect.php";
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = ereg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysql_real_escape_string($_POST['e']);
// GET USER IP ADDRESS
$ip = ereg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
if (($u != "") && ($e != "") ){
// Be sure to filter this data to deter SQL injection, filter before querying database
$name = $u;
$email = $e;
$sql = mysql_query("SELECT * FROM news_letter WHERE susc_email='$email'");
$numRows = mysql_num_rows($sql);
if (!$email) {
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">Please type an email address ' . $name . '.</font></h4>';
} else if ($numRows > 0) {
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">' . $email . ' is already in the system.</font></h4>';
} else {
$i= substr($name,0,3);
$j=rand(1000,9999);
$l= substr($email,0,3);
$k= $i.$j.$l;
$o=rand(0,9);
$m=str_replace("#","$o","$k");
$n=mysql_real_escape_string($m);
$sql_insert = mysql_query("INSERT INTO news_letter (susc_name, susc_email, susc_date, susc_code)
VALUES('$name','$email',now(),'$n')") or die (mysql_error());
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">Thanks ' . $name . ', you have been added successfully.</font></h4>';
echo "signup_success";
exit();
}
}
}
?>
So I have a problem with my registration and login php code. I have put them together in one php file called index.php and the registration works fine but when i try to login it clashes with the registration statements.
<?php
include_once("php_includes/check_login_status.php");
// If user is already logged in, header that weenis away
if($user_ok == true){
header("location: user.php?u=".$_SESSION["username"]);
exit();
}
?>
<!-- .registerphp -->
<?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
include_once ("php_includes/blowfish.php");
$cryptpass = crypt($p);
$p_hash = cryptPass($cryptpass)."$cryptpass".cryptPass($cryptpass);
// 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#pfolio.bugs3.com";
$subject = 'PFolio Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>PFolio 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.pfolio.bugs3.com/images/smalllogo.png" width="215" height="50" alt="PFolio" style="border:none; float:left;">PFolio 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 />* Username: <b>'.$u.'</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();
}
?>
<!-- .registerphp -->
<!-- .loginphp -->
<?php
// AJAX CALLS THIS LOGIN 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 AND SANITIZE
$u = mysqli_real_escape_string($db_conx, $_POST['u']);
$p = crypt($_POST['p']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// FORM DATA ERROR HANDLING
if($u == "" || $p == ""){
echo "login_failed";
exit();
} else {
// END FORM DATA ERROR HANDLING
$sql = "SELECT id, username, password FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_id = $row[0];
$db_username = $row[1];
$db_pass_str = $row[2];
if($p != $db_pass_str){
echo "login_failed";
exit();
} else {
// CREATE THEIR SESSIONS AND COOKIES
$_SESSION['userid'] = $db_id;
$_SESSION['username'] = $db_username;
$_SESSION['password'] = $db_pass_str;
setcookie("id", $db_id, strtotime( '+30 days' ), "/", "", "", TRUE);
setcookie("user", $db_username, strtotime( '+30 days' ), "/", "", "", TRUE);
setcookie("pass", $db_pass_str, strtotime( '+30 days' ), "/", "", "", TRUE);
// UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS
$sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo $db_username;
exit();
}
}
exit();
}
?>
<!-- .loginphp -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<title>P'Folio</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="css/loginstyle.css" rel="stylesheet" type="text/css">
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<!-- .registerjs -->
<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", "index.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 {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "index.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);
}
}
</script>
<!-- .registerjs -->
<!-- .loginjs -->
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function login(){
var u = _("user_name").value;
var p = _("pass_word").value;
if(u == "" || p == ""){
_("sta_tus").innerHTML = "Fill out all of the form data";
} else {
_("loginbtn").style.display = "none";
_("sta_tus").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "index.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "login_failed"){
_("sta_tus").innerHTML = "Login unsuccessful, please try again.";
_("loginbtn").style.display = "block";
} else {
window.location = "user.php?u="+ajax.responseText;
}
}
}
ajax.send("u="+u+"&p="+p);
}
}
</script>
<!-- .loginjs -->
</head>
<body>
<!-- .wrapper -->
<div class="wrapper">
<!-- .header-->
<header class="header"> <img src="images/logo.png" alt="logo" title="P'Folio"> </header>
<!-- .header-->
<!-- .login -->
<div class="login">
<form id="loginform" onsubmit="return false;">
<div><img class="h1" src="images/lh.png" alt="login%20here"/></div>
<div><img class="p1" src="images/wb.png" alt="welcome%20back"/></div>
<input type="text" id="user_name" onfocus="emptyElement('status')" maxlength="16" class="loginboxes" placeholder="Username">
<input type="password" id="pass_word" onfocus="emptyElement('status')" maxlength="100" class="loginboxes" placeholder="Password">
<br />
<button id="loginbtn" onclick="login()">Log In</button>
<p id="sta_tus"></p>
Forgot Your Password?
</form>
</div>
<!-- .login -->
<!-- .main -->
<main class="content">
<p>Are you a musician, a model, actor or actress or anyone with a talent then sign up for P'Folio.
Here on P'Folio we look to give you space to upload a portfolio for you to be noticed. </p>
</main>
<!-- .main -->
<!-- .signup -->
<div class="signup">
<form name="signupform" id="signupform" onsubmit="return false;">
<div><img class="h1" src="images/caa.png" alt="create%20account"/></div>
<div><img class="p1" src="images/ntm.png" alt="new%20to%20P'Folio"/></div>
<span id="unamestatus"></span>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16" placeholder="Username" class="registerboxes">
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88" placeholder="Email" class="registerboxes">
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="100" placeholder="Password" class="registerboxes">
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="100" placeholder="Confirm Password" class="registerboxes">
<select id="gender" onfocus="emptyElement('status')" class="registerboxes">
<option value="0" selected="selected">Choose...</option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<select id="country" onfocus="emptyElement('status')" class="registerboxes">
<?php include_once("template_country_list.php"); ?>
</select>
<div class="conditions">By clicking Sign Up,
you agree to our Terms and that
you have read our Privacy Policy ,
including our Cookie Use .</div>
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
</div>
<!-- .signup -->
<!-- .footer -->
<footer class="footer">
<div id="legal"><a class="legal" href="JavaScript:newPopup('Login/Legal/Terms.php');">Terms</a> | <a class="legal" href="JavaScript:newPopup('Login/Legal/Privacy.php');">Privacy</a></div>
<div id="font"><a class="font">P'folio © 2014</a></div>
</footer>
<!-- .footer -->
</div>
<!-- .wrapper -->
</body>
</html>
Why is my Registration and Login code not working?
For registration and also login don't use AJAX. It is better. You may use classic JavaScript for pre-checking of correct setting of username and password, but don't use AJAX for own login and registration process.
Also it is good to split both processes into different places. I have not ever seen any web where login and registration would be done from the same place - and via AJAX.
For username checking you may use order
preg_match('/^[^0-9][a-z0-9]{3,16}/i', $_POST['username']);
that checks if username does not start with number and is long at least 3 signs and not longer than 16 signs. Also it allows small letters and numbers.