FaceBook Registration Plugin Async Validate form (to check Username availbility) - php

Ok, So I have Google the hell out of this problem and the FB Advanced Registration documentation also did not help. I want to have a Facebook Registration where a user can choose(& Check availability of) his username like this:
(Screenshot of what I plan to do but have failed to do, since I cant post picturesin this question directly)
A link to Screenshot of what I wanted!
I plan to check the availability of the username from my DB in mysql using PHP, but I am stuck with this weird JSON callback thing which I have failed to understand.
My Registration Plugin looks something like this
<fb:registration
fields='[{"name":"name"},{"name":"username","description":"Username","type":"text"}]'
onvalidate="validate_async"
redirect-uri="http://mysite.com/loginFB.php"
fb_only="false"
width="530">
</fb:registration>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
function validate_async(form, cb) {
// $.getJSON('https://graph.facebook.com/' + form.username + '?callback=?',//CODE obtained from FB documentation
$.getJSON('https://mysite.com/checkUsername.php?username=' + form.username + '?callback=?',
function(response) {
if (response.error== "false") {
// Username isn't taken, let the form submit
cb();
}
cb({username: 'That username is taken, Sorry!'});
});
}
</script>
I wanted to know WHAT EXACTLY do I write the in the checkUsername.php.
Right now I have come up with the following code for checkUsername.php which does NOT work:
<?php
$conn = dbconnect(GLOBAL_Db);
$username = $_GET['username'];
$data = array();
$table = mysql_real_escape_string(GLOBAL_Db. "." . GLOBAL_Users);
$sqlCommand = "SELECT * FROM ".$table." WHERE username='$username'";
$query = mysql_query($sqlCommand) or die (mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows>0){
$data['error'] = "true";
} else {
$data['error'] = "false";
}
echo json_encode($data);
?>
This code does not give me that that "The username is taken, Sorry" Message , WHY???
I would really appreciate it if anyone could actually help me out with this getJSON function in the script , AND Also help me out with the checkUsername.php since I have a very crude knowledge of JSON, (JSONP) etc. !
Would be glad to put in more effort to explaain my problem coz this is bugging me for like a Week now!
Happy to accept some valuable help from you guys!

$username = $_GET('username');
$_GET is not a function … maybe you should familiarize yourself with some PHP basics first?
Besides that, your script logic looks a bit weird …
if($num_rows>0){
$data['error'] = "true";
} else {
$data['username'] = $row['username'];
}
If now rows are found, then you want to access the username field in a row that’s not there?
(And you’re not even quoting the username you get as a GET parameter, OMG …)
Set error to true or false depending on if there are rows or none.
And then, in your JS function, give the „username is taken”-message if error=true.

Related

PHP How to validate URL with id ungiven parameter?

I have a website where I can show a single post with view_post.php?id=1 but when I try to show a post with for example view_post.php?id= or view_post.php?id it shows nothing.
Then I tried to Log the Database Query like this:
$query = "SELECT * FROM posts WHERE id='$postIdFromUrl'";
$stmt = $db->query($query);
if (!$stmt) {
$_SESSION["test"] = $stmt;
redirect_to("Blog.php");
}
It doesnt show anything as the query is valid.
So my question is how to validate that. I tried a lot of things with e.g. URL Validation... nothing worked.
I would be very happy if someone could send me a code that can check for that.
Thanks very much in advance!
just check if id exists or its empty before u do anything
if (isset($_GET['id']) && !empty($_GET['id'])) {
//do your original code
} else {
redirect_to("Blog.php");
}

Log in script accepts anything but the one it is based off of works fine. Why?

I'm trying to make two visually similar web environments. One is supposed to be secure and the other one isn't. I figure doing things right AND wrong and having examples will help me while I'm still learning. Right now I'm doing the log in forms but while the more secure code works right, the insecure code is literally accepting everything, even blank inputs! I can't tell what the difference is that is making this happen.
This is from the more secure log in page.
// The user is logging in
} else if (isset($_POST['logsubmit'])) {
// collects value from login form
$loguser = safe_input($_POST['loguser']);
$logpass = md5($_POST['logpass']);
//This section needs encryption
$logcheck1 = mysqli_query($con,"SELECT * FROM users WHERE username ='$loguser'");
$logcheck2 = mysqli_num_rows($logcheck1);
if ($logcheck2 == 0) {
echo ('There is no record of that username being currently active');
goto logform;
}
while ($logcheck3 = mysqli_fetch_array($logcheck1)) {
if ($logpass != $logcheck3['password']) {
echo ('Incorrect password used.');
goto logform;
}
}
display:
$user = mysqli_query($con,"SELECT profile_pic FROM users WHERE username ='$loguser'");
while ($data = mysqli_fetch_array($user)) {
if ($data['profile_pic'] != NULL) {
$pic = $data['profile_pic'];
} else {
$pic = "img/blank_profile.png";
}
}
setcookie('testsiteUser',$loguser,time()+3600);
setcookie('testsitePass',$logpass,time()+3600);
echo ('<h2 id="greenborder">Hello, <a id="purpleborder"
href="userpage.php">'.$loguser.'</a>!</h2>
<img class="profile_bar" src="'.$pic.'">');
?>
<p>
<form action="<?php echo ($_SERVER['PHP_SELF'])?>" method="POST">
<input type="submit" name="logout" value="Log Out">
</form></p>
<?php
} else {
logform:
And then after the logform: marker is the log in form. There is more code above comment about the user logging in. Let me know if anyone wants to see it. I don't know if it's relevant.
This works! If I log into this with the wrong user name or password, it'll say so. If I log in right, it'll say so.
This is the code from the more insecure version.
// The user is logging in
} else if (isset($_POST['logsubmit'])) {
// collects value from login form
$loguser = /*safe_input*/($_POST['loguser']);
$logpass = md5($_POST['logpass']);
/*
//This section needs encryption
$logcheck1 = mysqli_query($con,"SELECT * FROM users WHERE username ='$loguser'");
$logcheck2 = mysqli_num_rows($logcheck1);
if ($logcheck2 == 0) {
echo ('There is no record of that username being currently active');
goto logform;
}
while ($logcheck3 = mysqli_fetch_array($logcheck1)) {
if ($logpass != $logcheck3['password']) {
echo ('Incorrect password used.');
goto logform;
}
}
*/
$logcheck = mysqli_query($con,"SELECT * FROM users WHERE username = '$loguser' AND password = '$logpass'");
mysqli_free_result($logcheck);
if ($logcheck == 0){
echo ('Incorrect username or password');
goto logform;
}
//display:
/*$user = mysqli_query($con,"SELECT profile_pic FROM users WHERE username ='$loguser'");*/
/*$userpic = $_SESSION["loguser"];
$user = mysqli_query($con,"SELECT profile_pic FROM users WHERE username ='$userpic'");
while ($data = mysqli_fetch_array($user)) {
if ($data['profile_pic'] != NULL) {
$pic = $data['profile_pic'];
} else {
$pic = "img/blank_profile.png";
}
}*/
$_SESSION["loguser"] = $loguser;
echo ('<h2 id="greenborder">Hello, <a id="purpleborder" href="userpage.php">'.$_SESSION["loguser"].'</a>!<h2><p><img class="profile_bar" src="'.$pic.'">');
?>
<p>
<form action="<?php echo ($_SERVER['PHP_SELF'])?>" method="POST">
<input type="submit" name="logout" value="Log Out">
</form></p>
<?php
} else {
logform:
A lot of this is commented out because I started by copying this from the safer code which was made first. This logs in no matter what, and whatever I put into the user name input is displayed as the account name. I don't even know if the database is being queried.
I THINK that the 2nd version is somehow passing the goto login, but I can't see why it would work in the first version but not the second version. Or if I'm missing something else completely! I'm comparing both of these side by side, trying to make sure all the brackets have mates, but I'm still learning PHP. I know goto is awful and putrid and nobody likes it, but I feel like I'm using just how it's displayed in the online PHP manual where it comes out of an if, while, and for statement.
http://php.net/manual/en/control-structures.goto.php#example-162
I'm still building both of these so I realize there may be some big flaws in the first version that aren't present in the second version. I'm really just hung up on this one thing for now. Can anyone see whatever it is I'm missing here?
Sorry if the question is too long or I committed some other faux pas. This is my first question.
Your issue is because your second "less secure" option isn't checking the number of rows.
In your second script, you have:
$logcheck = mysqli_query(....
and then you try to check it
if($logcheck == 0) {..
That's completely wrong, it'll only ever return a mysqli resource or false. Also that mysqli_free_result(); might be causing issues (as stated in the comments by onegun). Comment it out and see what happens.
Another Note
You should be careful when using goto, especially if an error were to occur, you wouldn't be able to trace it to its origin and it's actually bad coding practice to rely on it.

Check for username availability php

<?php
$con = mysqli_connect('localhost','root','[mypassword]','dbhwsource');
if(isset($_GET['username'])){
$username = $con->real_escape_string($_GET['username']);
$test = $con->query("SELECT username FROM users WHERE username='$username'");
if($test!=false) die("usererror");
}
if(isset($_GET['email'])){
$email = $con->real_escape_string($_GET['email']);
$test = $con->query("select * from users where email='$email'");
if($test!=false) die("emailerror");
}
$con->close();
echo "ok";
?>
So I'm just trying to check to see if the username / email is available or not, but all i get is "usererror" no matter what the input username is! I'm just frustrated and have searched for sample code everywhere and the code looks like there's nothing wrong with it. What am I doing wrong?
EDIT:
$test = $test->fetch_assoc();
if(!empty($test)) die("usererror");
This worked!
Since your query returns true, this line if($test!=false) die("usererror"); gets executed,
should be something like
$test = $con->query("SELECT username FROM users WHERE username='$username'");
$row_cnt = $test->num_rows;
if( $row_cnt > 0 ) {
//you already have user with this name, do something
}
$con->query returns a result object if the query was successful. This doesn't say anything about how many rows where found or whether the query matched anything, it just means the query executed successfully. Therefore your $test!=false test always succeeds; only in the case of a database error would it fail.
Do the query as SELECT COUNT(*) FROM ..., then fetch the first row of the result and see if the count is > 0.
I recently did something like this for an android app. you should really check this site out. It helped me tremendously. This is a detailed example of having a PHP API for an aplication. Specifically logging in.
To be specific though, here is a snippet from the page for the PHP
/*
* Check user is existed or not
*/
public function isUserExisted($email) {
$result = mysql_query("SELECT email from users WHERE email = '$email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
This worked for me:
$test = $test->fetch_assoc();
if(!empty($test)) die("usererror");
Your code is really not secure not optimized anybody can login with sql injection in your code.
and your code is right as you are checking thar (test != false) it means it is true that's why your code og usererror is executing
here is some tips and always use this style for security and optimization
do same for $email
third after running the query do not check if it is true or false but check again after query
if($test->username === $_GET['username']) { do something }
check sql injections on Google why i did this

Ajax + PHP Collaboration Error

NOTE: UPDATE - Please Read
Please Read, updated code, much better:
Also, I added an ajax error function and it doesn't call an error, the first time I do it, but the next time it happens, an error occurs, and the third and fourth times, and so on.
I have some code that doesn't seem to be working, and the problem is probably located in the Ajax request or the PHP receiving function, and I don't know what the problem could be.
Here is the important code, ask for any other code that could also be of help to you.
Jquery Ajax request
$(document).ready(function()
{
$("#secretcoin").mouseover(function()
{
$.ajax(
{
type: "POST",
url: "achievements.php",
data: { Home_Coin_Locator: "Yes" },
error: errorAlert
});
});
});
Receiving side, PHP, which takes this info and stores it in a database:
$achieve4 = $_POST["Home_Coin_Locator"];
$astrSQL = "SELECT * FROM Awards_Inv WHERE Username = '$username'";
$rs3 = mysql_query($astrSQL, $connection);
if ($achieve4 == "Yes")
{
while($row3 = mysql_fetch_array($rs3)){
$soar4 = $row3["Home_Coin_Locator"];
if ($soar4 == "Yes")
{
$soa4 = "Yes";
}
else
{
$soa4 = "No";
$awardSTRsql = "UPDATE Awards_Inv SET 'Home_Coin_Locator' = 'Yes' WHERE Username = '$username'";
mysql_query($awardSTRsql, $connection) or die(mysql_error());
$updatestatsSTRsql = "UPDATE User_Info SET `Coins` = Coins + 120, `Skill Points` = Skill Points + 10, `Awards` = Awards + 1 WHERE Username = '$username'";
mysql_query($updatestatsSTRsql, $connection) or die(mysql_error());
}
}
}
else
{
}
Ok, so my code might be weird, but just try to read it and see what the problem is.
I guess any other advice is also accepted, thanks for looking, and I hope you find something!
I added an error callback function and combined 3 mysql queries into 1, but the problem still exists.
Finally, read this code for info about the $connection and $username variables
$connection = mysql_connect("mysql1.000webhost.com", "username hidden", "password hidden") or die (mysql_error ());
mysql_select_db("a7347456_usersdb") or die(mysql_error());
session_start();
$username = $_SESSION["Username"];
Another factoid:
The error is that the info does not get updated to database, as far as I know.
first thing, make sure that you required the config file witch identify the $connection variable. and it will be easier if you describe what the problem exactly is.

PHP code allows logging in without correct password

I'm writing a PHP code for my website. Currently, there's some problems with my code.
Here's my code. Ignore some Malay language used, I'd tried to translate most of them.
<?php
session_start();
include "../library/inc.connectiondb.php";
$txtUser = $_POST['txtUser'];
$txtPass = $_POST['txtPass'];
if(trim($txtUser) == "") {
echo "<b>User ID</b> is empty, please fill";
include "login.php";
}
else if(strlen(trim($txtPass)) <= 5) {
echo "<b>Password</b> is less then 6 characters, please fix";
include "login.php";
}
else {
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
$qryPeriksa = mysql_query($sqlPeriksa, $sambung);
$hslPeriksa = mysql_num_rows($qryPeriksa);
if($hslPeriksa == 0) {
# If username doesn't exist
echo "<b>UserID</b> doesn't exist";
include "login.php";
}
else {
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
if($hslPassword < 1) {
# If password is incorrect
echo "<b>Password</b> is incorrect";
include "login.php";
}
else {
# If login successful
$SES_Admin = $txtUser;
session_register('SES_Admin');
echo "LOGIN SUCCESSFUL";
# Redirect to index.php
echo "<meta http-equiv='refresh' content='0; url=index.php'>";
exit;
}
}
}
?>
The problem is this code allows me to login even if the password is wrong. I'd done some searches and it still doesn't solve my problem. I'm pretty sure that the problem is at line 27 onwards.
So, if anyone has a solution, please tell me quickly. I'm writing this code for my school, and it had to be finished before next year.
Edit
Ok, I'd already placed the mysql_real_escape_string in the code just like what many people told me. I don't know how this will help, but the mysql table for this was named "admin". It had 2 fields; userID and passID. To test the code, I'd inserted the value "admin" and "12345678" into the table.
This is where your problem is:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
You see, your mysql_query is executing $sqlPeriksa which is:
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
Instead, your code should be like this:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPassword, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
Please try this out and let us know what happens.
[edit/additional] : I strongly suggest that you look into the following:
Using PDO:
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Using stored procedures:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Using PDO + stored procedures:
http://php.net/manual/en/pdo.prepared-statements.php (See example #4)
just plain troubleshoot is necessary. how many rows are returned? what are the values of userID and passID in the query that returns rows? put some breaks in and see what's going on. i don't see a problem, it but its hard to troubleshoot code posted here since it really can't be run without a db.
I don't see any reason this isn't working as you expected, I suspect the problem might be elsewhere. For example, I don't see you checking if a "SES_Admin" session is already registered. But at the very least you need to replace lines 5 and 6 with this, otherwise someone could potentially delete your entire user table, and do various other malicious things with your MySQL databases.
$txtUser = mysql_real_escape_string($_POST['txtUser']);
$txtPass = mysql_real_escape_string($_POST['txtPass']);
Please read the article on mysql_real_escape_string at http://php.net/manual/en/function.mysql-real-escape-string.php

Categories