I want to check the username availability while users register. I am working on the front end. The backend code was given to me.
These are the php code in signup.php
if (isset($_GET['chkusername']))
JSON_username_avail($_GET['chkusername']);
function JSON_username_avail($username) {
$ret = array();
print json_encode(validate_username($username, $ret));
die();
}
function validate_username($username, & $retval_arr) {
if ($username == NULL)
$retval_arr['E_UserName'] = "NULL_USERNAME";
else if (!username_validation($username))
$retval_arr['E_UserName'] = "INVALID_USERNAME";
else if (!data_not_exists("user", "username", $username, TRUE))
$retval_arr['E_UserName'] = "USERNAME_EXISTS";
return $retval_arr;
}
function username_validation($user) {
$username = str_split($user);
foreach($username as $i) {
$i = ord($i);
if ($i >= 48 and $i <= 57)
continue;
if ($i >= 65 and $i <= 90)
continue;
if ($i >= 97 and $i <= 122)
continue;
return FALSE;
}
return TRUE;
}
function data_not_exists($table, $field, $data, $CSense = FALSE) {
$conn = connect_db();
$data = filter_var($data, FILTER_SANITIZE_STRING);
if ($CSense == TRUE)
$sql = "SELECT * FROM ".$table.
" WHERE ".$field.
"='".$data.
"'";
else
$sql = "SELECT * FROM ".$table.
" WHERE upper(".$field.
")='".$data.
"'";
$result = mysqli_query($conn, $sql);
switch ($result - > num_rows) {
case 0:
return TRUE;
break;
case 1:
return FALSE;
break;
default:
die("500 Internal Server Error: 122");
} //switch
}
Now I dont know that much of php. I created a javascript function to send the username to the signup.php page for validation.
Here is my function
function submit_form() {
var u = document.getElementById("username").value;
$.post("signup.php", {
"chkusername": u
},
function (data) {
var x = data; //here i dont know how to get the return string. Whether it is NULL_USERNAME OR INVALID_USERNAME OR USERNAME_EXISTS.
}, "json");
}
here i am getting the value of x as [object Object].
But i need to store the return message in variable x. I want to know whether it is NULL_USERNAME OR INVALID_USERNAME OR USERNAME_EXISTS. Kindly help me with that.
The username is POSTed but in the PHP you try to access it with $_GET, change to:
if (isset($_POST['chkusername']))
JSON_username_avail($_POST['chkusername']);
Also your validation logic doesn't look right, what if the username is valid and available? I would add an else clause and set a success variable:
function JSON_username_avail($username) {
$ret = array();
print json_encode(validate_username($username));
die();
}
function validate_username($username) {
$retval_arr = array('success' => false, 'message' => '');
if ($username == NULL)
$retval_arr['message'] = "NULL_USERNAME";
else if (!username_validation($username))
$retval_arr['message'] = "INVALID_USERNAME";
else if (!data_not_exists("user", "username", $username, TRUE))
$retval_arr['msessage'] = "USERNAME_EXISTS";
else
$retval_arr['success'] = true;
return $retval_arr;
}
and the ajax:
if(!data.success){
console.log(data.message);
} else {
// valid and available
}
Try,
function(data){
var x = data.E_UserName;
}, "json");
also change your request to GET as per MrCode's answer
function submit_form() {
var u = document.getElementById("username").value;
$.get("signup.php", {
"chkusername": u
},
function (data) {
var x = data.E_UserName
}, "json");
}
Related
I made this function to check for expected request variables. It was working great until I realized that if two values (Not keys) were the same, it would return a positive number as though a key was missing. Consider the following code:
function requestCheck($expectedAr)
{
if(isset($_GET) && isset($_POST))
{
$requestAr = array_unique(array_merge($_GET, $_POST));
}elseif(isset($_GET)){
$requestAr = $_GET;
}elseif(isset($_POST)){
$requestAr = $_POST;
}else{
$requestAr = array();
}
$diffAr = array_diff_key(array_flip($expectedAr),$requestAr);
if(count($diffAr) > 0)
{
returnError("Missing variables: ".implode(',',array_flip($diffAr)).".");
}else {
return $requestAr;
}
}
$requestAr = requestCheck(['name','password']);
if 'name' and 'password' both hold the same value, it will run returnError(). Not seeing why.
Here's a dump of $_POST:
array (
'poolName' => 'xpool',
'userPrefix' => 'xpool'
)
array_unique will strip unique values so you'll end up with either name or password but not both.
Solution:
function requestCheck($expectedAr) {
if(isset($_GET) && isset($_POST)) {
$requestAr = $_REQUEST;
}elseif(isset($_GET)) {
$requestAr = $_GET;
}elseif(isset($_POST)) {
$requestAr = $_POST;
}else{
$requestAr = array();
}
$diffAr = array_diff_key(array_flip($expectedAr),$requestAr);
if(count($diffAr) > 0)
{
returnError("Missing variables: ".implode(',',array_flip($diffAr)).".");
}else {
return $requestAr;
}
}
$requestAr = requestCheck(['name','password']);
I think it's safe to also do the following:
function requestCheck($expectedAr) {
$requestAr = isset($_REQUEST) && is_array($_REQUEST)?$_REQUEST:array();
$diffAr = array_diff_key(array_flip($expectedAr),$requestAr);
if(count($diffAr) > 0) {
returnError("Missing variables: ".implode(',',array_flip($diffAr)).".");
}else {
return $requestAr;
}
}
$requestAr = requestCheck(['name','password']);
I have never done combining ajax and session before. So far i have done something like this.
var sessionvar;
$.ajaxSetup({cache: false})
$.get('test.php' ,function (data) {
sessionvar = data;
alert(sessionvar);
var checkedCbs = $('sessionvar:checked');
if (checkedCbs.length === 4) {
alert("You can only select 3 books");
this.checked = false;
}
});
I want to try set the limitations based on session. Inside the test.php i have something like this
<?php
session_start();
if(isset($_POST['sBorrow']) && $_POST['action']){
if(isset($_SESSION['sBorrow']) && is_array($_SESSION['sBorrow'])){
$sborrow = $_POST['sBorrow'];
$set = $_SESSION['sBorrow'];
}
else{
$set = array();
}
if($_POST['action'] == "SET"){
array_push($set, $_POST['sBorrow']);
$_SESSION['sBorrow'] = $set;
}
else if($_POST['action'] == "UNSET"){
$unset = $_SESSION['sBorrow'];
if(($key = array_search($_POST['sBorrow'], $unset)) !== false) {
unset($unset[$key]);
$_SESSION['sBorrow'] = $unset;
}
}
}
//session_destroy();
if(isset($_SESSION['sBorrow'])){
$countses = count($_SESSION['sBorrow']);
echo $countses;
}
// nothing requested, so return all values
print json_encode($_SESSION);
?>
Inside these i have create some array to store something. Never mind that, i just want to know how to run an ajax with session. Im not sure if my codes is right for implementing that.
I'm working on a loader that will load a file once the user authenticated correctly, but before I want to start my file stream I want to check their HWID to check so it matches the HWID on the database and I have managed to do it and I do it like this:
function validate_Hwid(){
global $db, $encryptionEngine;
if (isset($_GET['username']) && isset($_GET['hwid'])) {
$username = $encryptionEngine->init($_GET['username'],"decrypt");
$hwid = $encryptionEngine->init($_GET['hwid'],"decrypt");
$query = $db->simple_select("users", "*", "LOWER(username)='".$db->escape_string(my_strtolower($username))."'", array('limit' => 1));
$user = $db->fetch_array($query);
if ($hwid == $user['hwid']) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
but I have a problem, if the user never logged in before the HWID on the DB will be null, how can I change so if HWID on the user is null, than insert the string I provide?
if ($user['hwid'] == null)
{
// insert and call func again
} elseif ($hwid == $user['hwid']) {
return 1;
} else {
return 0;
}
I have form with client-side verification by jQuery, which works good. But now for security reasons I want to add also server-side verification (php) for users without JavaScript. I created few functions and array "errors", where errors are logged. After submit I want run the verification. If no errors are logged, continue, if there are errors exit the script. But that part doesn't work, it always continue. My script:
if (isset($_POST['submit'])) {
require_once 'verify_form.php';
$errors = array(
'username' => null,
'password1' => null,
'password2' => null,
'email1' => null,
'email2' => null,
'age' => null
);
validate_all($errors);
if(empty($errors['username']) && empty($errors['password1']) && empty($errors['password2']) && empty($errors['email1']) && empty($errors['email2']) && empty($errors['age'])) {
//do something
} else {
$_SESSION['errorsArray'] = $errors;
header('Location: /registracia');
exit;
}
}
verify_form.php
<?php
function validate_all($errors)
{
validUsername($errors);
validPassword1($errors);
validPassword2($errors);
validEmail1($errors);
validEmail2($errors);
validAge($errors);
}
function validUsername($errors)
{
include 'config.php';
$username=$_POST['usernameReg'];
if (strlen($username) < 3 || strlen($username) > 16) {
$errors['username'] = "Zadajte uživateľské meno v rozmedzí 3 - 16 znakov.";
}
$query = "SELECT * FROM `users` WHERE `username` = '$username'";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
if (mysqli_num_rows($result) > 1) {
$errors['username'] = "Toto uživateľské meno už niekto používa.";
}
}
function validPassword1($errors)
{
$password1=$_POST['password1Reg'];
$regex = '/^([a-zA-Z]|[0-9]|[-]|[_]|[/]|[.])+([a-zA-Z]|[0-9]|[-]|[_]|[/]|[.])+([a-zA-Z]|[0-9]|[-]|[_]|[/]|[.])$/';
if (!preg_match($regex, $password1)) {
$errors['password1'] = 'Vaše heslo obsahuje nepovolené znaky.';
}
if (strlen($password1) < 6) {
$errors['password1'] = 'Heslo musí obsahovať minimálne 6 znakov.';
}
}
function validPassword2($errors)
{
$password2=$_POST['password2'];
if ($password1 != $password2) {
$errors['password2'] = 'Zadané heslá sa nezhodujú.';
}
}
function validEmail1($errors)
{
include 'config.php';
$email1=$_POST['email1'];
$regex = "/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/";
if (!preg_match($regex, $email1)) {
$errors['email1'] = 'Neplatná e-mailová adresa.';
}
$query = "SELECT * FROM `users` WHERE `email` = '$email1'";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
if (mysqli_num_rows($result) > 1) {
$errors['email1'] = "Tento e-mail už niekto používa.";
}
}
function validEmail2($errors)
{
$email2=$_POST['email2'];
if ($email1 != $email2) {
$errors['email2'] = 'Zadané e-maily sa nezhodujú.';
}
}
function validAge($errors)
{
$age=$_POST['age'];
$regex = "/^([0-9]|[0-9][0-9])$/";
if (!preg_match($regex, $age)) {
$errors['age'] = 'Vek musí byť číslo v rozsahu od 0-99.';
}
}
?>
Why the script always continue?
You're passing the $errors array into the validUsername() function. The function doesn't actually receive the original array, but instead it gets a copy of it. You're modifying the copy, but the original is never modified. Here's a smaller example to show you how this works:
function addCheese(Array $arr)
{
$arr[] = 'cheese';
}
$a = array();
addCheese($a);
var_dump($a);
// Outputs:
// array(0) {
// }
One way to fix this would be to modify each validation function to return the modified array:
function validSomething($errors)
{
// ... do validation checks
return $errors;
}
... and then assign the updated version to the external value:
function validate_all($errors)
{
$errors = validUsername($errors);
$errors = validPassword1($errors);
$errors = validPassword2($errors);
$errors = validEmail1($errors);
$errors = validEmail2($errors);
$errors = validAge($errors);
return $errors;
}
Alternatively you could return the local array of errors and assemble them together, or just pass by reference (although this might cause other problems later on).
I'd strongly recommend using some sort of framework to do your validation: this will save you a lot of time in the long run.
function validEmail2($errors) doesn't make sence... $email1 is not defined and will always be != $_POST['email2']
You need to give the valid functions pointers to $errors. For example
function validUsername(&$errors)
I have this script that sends via $.post some information
$("#clickme").click(function(e){
var selected = $(".img input:checked").map(function(i,el){return el.name;}).get();
var prelucrare = selected.join(";")
$.post('test.php', {
rezultat: prelucrare,
},
function(data){
$('#rez').html(data)
});
});`
And the PHP file that handles the $.post
<?php
require_once '../config.php';
If(isSet($_POST['rezultat'])) {
$d = explode(';', $_POST['rezultat']);
foreach($d as $numar_inregistrare){
$SQL = "DELETE FROM galerie_foto WHERE numar_inregistrare = '$numar_inregistrare'";
$rezultat = mysql_query($SQL) or die(mysql_error());
return true;
}
} else {
exit;
}
?>
I have two questions:
1. How can I make the js script do a thing if the return value is true and an other thing if the return value is false ? Something like this ?
$.post('test.php', {
rezultat: prelucrare,
success: function(msg){
valid = (msg == 1) ? true : false;
if(!valid) {
$("#valid_input").html("Please enter valid info");
} else {
$("#valid_input").html("");
}
}
)};
My other question is about the returning result, because I'm in a loop if there are 3 things in the array the result will be truetruetrue instead of just one true, what can I make to get just one true ?
You can use "return" only in functions and methods. To print "true" or "false" once, in the foreach loop you can break out or in your case just exit with 'false' if there's an error. You'll have something like this:
foreach($d as $numar_inregistrare){
$SQL = "DELETE FROM galerie_foto WHERE numar_inregistrare = '$numar_inregistrare'";
$rezultat = mysql_query($SQL);
if (!$rezultat) {
exit('false');
}
}
echo 'true';
....