Jump to content

GumbiRo

Members
  • Posts

    19
  • Joined

  • Last visited

GumbiRo's Achievements

Newbie

Newbie (1/5)

0

Reputation

  1. Thank you good sir! So the final part of the code would be like this? $sql = "SELECT 1 FROM members WHERE username = '" . mysqli_real_escape_string($mysqli,$username) . "'"; if(!$result = $mysqli->query($sql)){ die('There was an error running the query [' . $db->error . ']'); } while($row = $result->fetch_assoc()){ $counter = $counter + 1; } if($result->num_rows > 0 ) { $ready = false; } else { $ready = true; } I know im a pain, but for now this code seems to be working. Just to check if the user inputed an existent username. Would you find this as sloppy code? If so, what changes would you make? Im not asking you just to say for me to change it, but to use it in the future. What weaknesses would you believe the code has? Thank you very much for your time and patience(everyone)!
  2. Bare with me, Im auto-learning because no one around here knows about php....So Im trying to do this by the books I find and online resources. :/ thats why I come to you guys!
  3. Ok, I took your advice and headed to the php archives. From what I can tell. These could be a simpler way of doing it but Im getting it wrong. //Query the DB $sql = mysqli_query("SELECT 1 FROM members WHERE username = " . mysqli_real_escape_string($mysqli,$username)); if(!$result = $mysqli->query($sql)){ die('There was an error running the query [' . $db->error . ']'); } if (mysqli_num_rows($result) > 0) { $ready = false; } else { $ready = true; } But now Im getting this error: Warning: mysqli_query() expects at least 2 parameters, 1 given... Which I believe leads to : Warning: mysqli::query() [mysqli.query]: Empty query So...which would be the second parameter?
  4. Ok, here's what happens. User presses button submit on a form and here's what happens: <?php // Include database connection and functions here. include 'db_connect.php'; include 'functions.php'; $username = $_POST['username']; ///Here is the added code just to check if the db doesn't have the same username. $ready = false; $result = $mysqli->prepare("SELECT 1 FROM members WHERE username = " . mysqli_real_escape_string($mysqli,$username)); if ($result && mysql_num_rows($result) > 0) { $ready = false; } else { $ready = true; } //I added this if ready, to check if the username isn't taken then its ready to post it if($ready) { ///From here, the code works fine if I take the previous code.(select from... //Working code. // The hashed password from the form $password = $_POST['p']; // Create a random salt $random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true)); // Create salted password (Careful with the chilli) $password = hash('sha512', $password.$random_salt); $username = $_POST['username']; $email = $_POST['email']; if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) { $insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt); // Execute the prepared query. $insert_stmt->execute(); header("Location: '..\..\..\?success=1'"); } else { header("Location: '..\..\..\?registrationfailed=1'"); } ///Added this else just to check if ready is false. }else { header("Location: '..\..\..\?registrationfailed=2'"); } ?> Here's the complete code of the file. There's some comments explaining what I want to accomplish! Thank you for your time!
  5. Yeah replied without looking thoroughly with my glasses on sorry! But now I've gt this error: Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given on line 11. Which is this: $result = $mysqli->prepare("SELECT 1 FROM members WHERE username = " . mysqli_real_escape_string($username)); I solved it by doing ..... mysqli_real_escape_string($mysqli, $username)); But It isn't finding any of the results as the code was meant to search for the same value as the one the user inputed.... From what you see, does the code look correct to you?
  6. Oh ok I didn't quite get that from you. Ok, so what do you suggest I change this to? $result = mysql_query("SELECT 1 FROM members WHERE username = " . mysql_real_escape_string($username)); Omg...I just saw my error, I thought I was using mysqli.... hahaha Let me change it and I'll get back to you in a second.
  7. ...I thought I did...? $result = mysql_query("SELECT 1 FROM members WHERE username = " . mysql_real_escape_string($username)); But that doesn't solve my problem....
  8. Hello everyone, this is a quick question. Im trying to look for input that the user made and validate if there's a duplicate or not. so: Steps: 1.check user input. 2.Check database for duplicate. 3.Return false/true. Here's what I tried to do... include 'db_connect.php' $username = $_POST['username']; $result = mysql_query("SELECT 1 FROM members WHERE username = " . mysql_real_escape_string($username)); if ($result && mysql_num_rows($result) > 0) { $ready = false; } else { $ready = true; } Here's what Im getting: Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'adminUser'@'localhost' (using password: NO) in/home1/../../../../sec_reg.php on line 9 Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home1/../../../../sec_reg.php on line 9 $result=my.... is line 9. Now, what I find weird is that in the SAME file I've got this: if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email) VALUES (?, ?)")) { ..Some code here } And before I added the code with the warning the mysqli->prepare didn't have any problems. What could be happening? **Yes...I checked that db_connect.php was correct.
  9. Ok, would you apply the JS i showed to solve this? I would like to add an image depending on whether the users input is valid or not. (Showing a tick as valid or an X as invalid next to the input.) (as default an X) but for now I have no clue whatsoever I haven't got my hands into Ajax, so I guess there's a roadblock. Any tips/tutorials on how I could solve this?(Im not that trustful on JS accessing the databases if thats where you're going with this, I guess it could be harmful? my_bad_email_foo() would be the function that sends the 'X' next to the input and a small message.(which im clueless on how to add the image for the friendlyness...) Sorry for the lack of explanation on this one haha, I guess I solved this on my own JS (check if the password matches the second one, but now that you mention it, making the user use letters & numbers ain't a bad idea to implement. **Thanks for the correction I missed that one.
  10. Hello everyone! I would love your feedback/help/advice/tips on this situations. Im currently creating a form to "register" on a database but I wanted to do what could be the 'best' practice when doing this. What Im looking at is 4 possible problems: 1.-User not adding anything on the input, thus submitting null values. 2.-User submiting a user that already exists in the database. 3.-Regex validation, I guess. 4.- Password verification. Here's the form: <form action="sec_register.php" name="registration_form" method="post"> Name: <input type="text" name="name" id="username"><br> E-mail: <input type="text" name="email" id="email"><br> Password: <input type="text" name="password" id="password"><br> Re-Type Password: <input type="text" name="repassword" id="repassword"><br> <button type="submit" class="btn" onclick="registerUser(this.form, this.form.password);">Register</button></form> My thought-process to solving this problems is this:(accordingly for each problem I previously stated) 1.Make the submit button disabled if any of the inputs is null/empty. 2.Check the username && email to see if there's the same mail/username used. 3.Regex Validation. 4.Password verification. Now, I had a regex validation but it goes before submitting. The advice Internet has given me is to do validations server side and not browser side because if security. But I've got a couple of functions on js to help out(against advice, so that's why I come to you :[ ) function formValidation(form, password) { // Get fields. var validate_name = document.getElementById("username"); var validate_mail = document.getElementById("mail"); var validate_password = document.getElementById("password"); var validate_repassword = document.getElementById("repassword"); var form_is_empty = TRUE; var form_is_valid = FALSE; if(validate_name == null) { //Exit and tell user name is empty form_is_empty = true; } else { if(validate_mail == null) { //Exit and tell mail is empty form_is_empty = true; } else { if(validate_password == null){ //Tell user password is empty form_is_empty = true; } else { form_is_empty = false; } if(form_is_empty != true){ if(validate_password == validate_repassword){ //Continue with validation } else { ///Disable button and send a message to user that it's not the same password. return false; } //Im clueless on how to add the php part on checking if the username is already chosen. //I need your help on that one. //But if the username/mail hasn't been used then form_is_valid = true; if(form_is_valid) { register_the_user(username,email,password); } I tried it formally but didn't work out. I also thought about doing a switch statement function in which is triggered by onChange on each input. What do you guys think, can you help me out with the solutions? Either way thank you for your help and time, much appreciated!
  11. Thank you very much david. This was the issue, Im now working on seeing if the script is correct, because for some reason the match isn't happening, but I guess Its up to me to check that out! Have a good one and thank you for your time!
  12. Ok I believe my problem here is this, (...I obviously don't know how to fix this): Cannot send session cache limiter - headers already sent (output started at /home1/login/db_connect.php:14) in/home1/login/functions.php on line 13 I've got 2 things: db_connect && process_login. As Im creating a session on functions.php This part of functions.php mainly: function sec_session_start() { $session_name = 'sec_session_id'; // Set a custom session name $secure = false; // Set to true if using https. $httponly = true; // This stops javascript being able to access the session id. ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies. $cookieParams = session_get_cookie_params(); // Gets current cookies params. session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly); session_name($session_name); // Sets the session name to the one set above. session_start(); // Start the php session session_regenerate_id(true); // regenerated the session, delete the old one. } I get errors on session_start and session_regenerate And I also get this error: Warning: Cannot modify header information - headers already sent by (output started at /home1/login/db_connect.php:14) in/home1/login/process_login.php on line 17 <?php include 'db_connect.php'; include 'functions.php'; sec_session_start(); // Our custom secure way of starting a php session. if(isset($_POST['email'], $_POST['p'])) { $email = $_POST['email']; $password = $_POST['p']; // The hashed password. if(login($email, $password, $mysqli) == true) { // Login success header("Location: '..\..\..\logged_success.php"); } else { // Login failed header("Location: '..\..\..\?error=1"); } } else { // The correct POST variables were not sent to this page. echo 'Invalid Request'; } ;?> Which is the header("Location: '..\.....") Im going mad! I don't know what to do. Thank you guys for your time.
  13. And what do you recommend me doing? as Of what you see on the files, what would you do to solve this? 1.Should the login.php have the php code where it is, or should I move it top. 2. Should I remove session_start from the process_login.php? Thanks for your time SocialCloud
  14. Hello everyone! Im learning how to create a "secure" way to login... But for the moment Im stuck with a couple of things. Here's the files. I'll be explaining what's wrong in each part... Here's my login.php Casual form that asks a user to login. *According to the lesson, the <?php is after the body, but for best practice I've seen that people put every session starting before the head. The lesson didn't explain why it should be where it is now. (after body) If you guys could tell me I'd be grateful! <html> <head><title>Log In</title> <script type="text/javascript" src="sha526.js"></script> <script type="text/javascript" src="forms.js"></script> </head> <body> <?php if(isset($_GET['error'])) { echo 'Error logging in.'; } else { //Include database connection and functions here include 'functions.php'; include 'db_connect.php'; sec_session_start(); if(login_check($mysqli) == true) { //Add your protected content here. } else { echo "You're not authorized, <br/> Please login."; } } ?> <form action = "process_login.php" method="post" name="login_form"> Email: <input type="text" name="email" /> <br /> Password: <input type="password" name="password" id="password" /> <br /> <input type="submit" value="Login" onclick="formhash(this.form,this.form.password);" /> </form> </body> </html> When I try to login. I get sent an unknown error, there's nothing displayed on my browser but the error the hosting site sends when you're seeing a file it doesn't exist. Here's process_login.php <?php include 'db_connect.php'; include 'functions.php'; sec_session_start(); // Custom way of starting session if(isset($_POST['email'], $_POST['p'])) { $email = $_POST['email']; $password = $_POST['p']; //Hashed password if(login($email, $password, $mysqli) == true) { //Login Success echo 'Success, You have Logged In.'; } else { //Login Failed header('Locaction ./login.php?error=1'); } } else { //The correct POST variables were not sent to this page echo 'Invalid Request'; } include 'functions.php'; sec_session_start(); //Unset all session values $_SESSION = array(); //Get session parameters $params = session_get_cookie_params(); // Delete actual cookie setcookie(session_name(), '', time() - 42000 , $params["path"], $params["domain"], $params["secure"], $params["httpOnly"]); //Destroy Session session_destroy(); header('Location: ./'); //Hashed pass from the form $password = $_POST['p']; //Create a random salt $random_salt = hash('sha526', uniqid(mt_rand(1, mt_getrandmax()), true)); //Created salted password (Careful not to overseason) $password = hash('sha512', $password.$random_salt); //Add insert to database script here. //Make sure you use prepared statements if($insert_stmt = $mysqli->prepare("INSERT INTO users (username, email, password, salt) VALUES (?, ?, ?, ?)" )) { $insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt); //Executed the prepared query $insert_stmt->execute(); } ?> Another error that I have is that It's telling me Im initiating session with the browser constantly, and that I should only do it once. but here's the file 'functions.php' which starts_session besides login.php... How could I fix this? <?php function sec_session_start() { $session_name = 'sec_session_id'; //Set custom session name $secure = false; //Set to true if using https $httpOnly = true; //This stops javascript frm accesing the session_id ini_set('session.use_only_cookies', 1); //Forces Session to use cookies. $cookieParams = session_get_cookie_params(); //Get cookie parameters session_set_cookie_params($cookieParams["lifetime"], $cookieParams["Path"], $cookieParams["domain"], $secure, $httpOnly); session_name($session_name); session_start(); //Start php session session_regenerate_id(); // regenerate the session, delete the old one. } function login($email, $password,$mysqli) //Using prepared statements means the SQL injection is not possible. { if($stmt = $mysqli->prepare("SELECT id, username, password, salt FROM users WHERE email = ? LIMIT 1")) { $stmt->bind_param('s', $email); //Bind email to parameter $stmt->execute(); //Execute QUERY $stmt->store_result(); $stmt->bind_result($user_id, $username, $db_password, $salt); //Get variables from result $stmt->fetch(); $password = hash('sha512', password.$salt); //Hash the password with the unique salt } if($stmt->num_rows == 1) { //IF user exist //Check if account is locked from too many attempts. if(checkbrute($user_id, $msqli) == true) { //Account is locked. echo 'Account is Locked.'; //To-Do: Add function to send mail to unlock account. return false; } else { if($db_password == $password) { //Check if the password the user entered is the same as the password in the database. //Password is correct! } } } } function checkbrute($user_id, $msqli) { //Get timestamp f current time. $now = time; //All login attempts are counted from the last 2 hours. $valid_attempts = $now - (2 * 60 * 60); if($stmt = $mysqli->prepare("SELECT time FROM login_attempts WHERE user_id = ? AND time > '$valid_attempts'")){ $stmt->bind_param('i',$user_id); //Execute the prepared query $stmt->execute(); $stmt->store_result(); //IF the statement has more than 5 failed logins if($stmt->num_rows > 5){ return true; } else { return false; } } } function login_check($mysqli) { //Check if all variables are set if(isset($_SESSION['user_id'],$_SESSION['username'],$_SESSION['login_string'])){ $user_id = $_SESSION['user_id']; $login_string = $_SESSION['login_string']; $username = $_SESSION['username']; $user_browser = $_SERVER['HTTP_USER_AGENT']; // Get user-agent string of user if($stmt = $mysqli->prepare("SELECT password FROM users WHERE id = ? LIMIT 1")) { $stmt->bind_param('i',$user_id); //Bind user id to parameter. $stmt->execute(); //Execute query $stmt->store_result(); if($stmt->num_rows == 1) { //IF user exists $stmt->bind_result($password); //Get variables from result $stmt->fetch(); $login_check = hash('sha512', $password.$user_browser); if($login_check == $login_string) { //Logged In return true; } } } } } ?> And here's db_connect.php just in case you need it, but I don't think you do. <?php $servername="localhost"; $username="userName"; $db_pass = "QkJ93OpLLlkmNoYgD"; $db_name = 'db_users_login'; $mysqli = new mysqli($servername,$username,$db_pass,$db_name); ?> Thank you for your time and if you have any suggestions Im all ears!
  15. Thank you, I've implemented mysql_real_escape... As for sake of research, do you guys know where I could find information about XSS(cross site scripting) what it is and how to prevent it? On a small question, where would I go If I would want the browser to hide information (on the url bar) of what I inputed on the form? Thank everyone for your time, you have been most helpful!
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.