I created a website using WordPress. My website provides a registration page where users can enter several information in a form.
Is it possible to disable/delete the email and username at the registration page. Is there some php file or settings page where I can modify this behavior? I don't want such information to be required at all.
Any help is appreciated.
You must have atleast one of them fields i.e. either username or email, because you cannot login with just a password.
In the following example, I have used just username to register and ignored email field and registered a user via ajax call, this code is from functions.php file.
function register() {
global $wpdb;
$username = $_POST['username'];
$password = $_POST['password'];
$userdata = array('user_login' => $username, 'user_pass' => $password);
if (isset($username) && $username != '') {
$user_id = wp_insert_user($userdata);
wp_set_current_user($user_id, $username);
wp_set_auth_cookie($user_id, true, false);
$_SESSION['registered'] = 1;
update_user_meta($user_id, 'last_login', time());
if (is_wp_error($user_id)) {
$error_string = $user_id->get_error_message();
echo $error_string;
}
echo $user_id;
}
}
Related
I'm attempted to create a login authentication system using PHP. So far I've managed to query the DB to check if a username/password given by the user matches any rows in the DB. However I have a column in the DB named "isadmin" which stores a boolean value. I want to implement a check if true/false. Depending on the result depends on which php file is loaded (included).
EDIT: I have two php files, both containing the same HTML displaying the index page of a website. However, one php file is for regular users, the other is for admin users which will contain added features. When a user enters their username and password, I want a check for the user level of that login, Once the check is done it should show the appropriate php page.
$stmt = $pdo->prepare('SELECT * FROM Reg_User WHERE username = :username AND password = :password');
$details = [
'username' => $_POST['username'],
'password' => sha1($_POST['password'])
];
unset($_POST['submit']);
$stmt->execute($details);
if ($stmt->rowCount() > 0) {
$user = $stmt->fetch();
$_SESSION['loggedin'] = $user['user_id'];
echo 'Logged in as ' . $_POST['username'];
include 'index.php';
}
else {
echo 'Sorry, your username and password could not be found Please <a href="login.html">try again
or register!</a>';
}
A simple if/else statement will do it.
if ($user["isadmin"]) {
echo "Logged in as an admin.";
#you can include your related php page here.
} else {
echo "Logged in as an user.";
#you can include your related php page here.
}
There's no sanitizing of user input in your code, this is a must in a login system, try this after your login form.
info: I don't use PDO, $con is the MYSQLI connection.
<?php
// Handle log in
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// Sanitize username input
$username = strip_tags($username);
$username = trim($username);
$username = mysqli_real_escape_string($con, $username);
$username = urldecode($username);
// Sanitize password input
$password = strip_tags($password);
$password = trim($password);
$password = mysqli_real_escape_string($con, $password);
$password = urldecode($password);
}
?>
Your site should be set to https only, if it is ignore this link: htaccess redirect to https://www and you should be providing either a secure session cookie or a secure persistent cookie for users who are able to log in successfully. The code underneath this paragraph should be at the very top of your page before any html. This example is for time related persistent https secure cookie set to 1 day after which it will expire. You could use a session cookie but I find this annoys people if they frequent your site quite often, they don't want to have to log in again the same day if they close and reopen a browser or tab.
<?php
// All this code goes right at the top of your page before anything else!
function addcookie() {
global $condition;
if ($condition == "green") {
global $nameofcookie;
setrawcookie('loggedin', $nameofcookie, strtotime('+1 day'), '/', '', isset($_SERVER["HTTPS"]), true);
echo "<script>window.location.replace('https://example.com/mypage');</script>";
}
}
?>
The above code is will set a secure cookie using a function because you only want it firing after a successful login. The name of the cookie really should be random and unique, something based on microtime would work well. Make sure it's not anything important which could identify the user!IMPORTANT: the name of the cookie for reference should be created at the time of account creation and added to the users table so you can identify users and represent their login details.
Standard security measures should also include a separate table of the ip, time, date and username of who logged in. If your site is busy the table will fill quickly so you could set a cron job to clean old records to keep the size down, in that case you will need to add a column for datetime to identify the age of records.
Handling the login...
<?php
$condition = "red";
if (isset($_POST['login'])) {
$select_login = "select * from Reg_User where username='$username' and password='$password'";
$connect_login = mysqli_query($con, $select_login);
$rows_login = mysqli_num_rows($connect_login);
if ($rows_login == 0) {
// code here to handle failed logins, I would record them and use a 3 strike method
}
// Handle successful logins, add cookie
else {
while ($row_login=mysqli_fetch_array($connect_login)) {
// Retrieve cookie name here from table
$nameofcookie=$row_login['cookie'];
$condition = "green"; // This allows you to add the cookie
addcookie();
}
}
}
?>
Retrieving the cookie to authenticate users...
<?php
if (isset($_COOKIE['loggedin'])) {
$cookie = $_COOKIE['loggedin'];
$select_authenticated_user = "select * from Reg_User where cookie='$cookie'";
$connect_authenticated_user = mysqli_query($con, $select_authenticated_user);
while ($row_authenticated_user=mysqli_fetch_array($connect_authenticated_user)) {
// Retrieve values here from table
$logged_in_user=$row_authenticated_user['username'];
$logged_in_admin=$row_authenticated_user['isadmin'];
// Resolve admin status
if ($logged_in_admin == TRUE) {
$type = "admin";
} else {
$type = "member";
}
}
// Echo statement for logged in user with admin or not status, you could change the echo to a variable name if you want to use this in a specific place on your page.
echo "Welcome $logged_in_user<br/>
Type: $type
";
}
?>
Here's a link for obtaining IP's: How to get the client IP address in PHP
I'm working on a custom system that works in parallell with my wordpress site, and the idea is that one can login to this system with the same credentials (username and password) as the ones they've made on my wordpress site.
So I already have a custom login-page for this system which, on submission, checks if the entered username and password exists in the wordpress database.
I've managed to do this, but it seems to generate a new string everytime it's run:
include_once( "../wp-config.php" );
include_once( "../wp-includes/class-phpass.php" );
$password = mysql_escape_string("password123");
$wp_hash = new PasswordHash( 8, TRUE );
echo $wp_hash->HashPassword( $password );
How can I do this?
$user = get_user_by( 'login', $username );
if ( $user && wp_check_password( $pass, $user->data->user_pass, $user->ID) )
echo "That's it";
else
echo "Nope";
you can see here
and if you define password's hash in your code;
require_once($_SERVER['DOCUMENT_ROOT']."/wp-load.php");
$password = '123456';
$hash = '$P$BpR40ssU1UobqMELuNlwzxVa4XgKNk1';
var_dump(wp_check_password($password, $hash));
note that be careful because you should define your password hash.
You can generate wordress pass hasher from here
hi i am having problems with a login script for my website i need the script to redrect the user to index.html if the login details are correct. if you could help me at all it would be greatly appreciated.. thank you...
here is my script for checking the details ==>
<?php
include('config.php');
?>
$ousername = '';
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password']))
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$ousername = stripslashes($_POST['username']);
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$password = stripslashes($_POST['password']);
}
else
{
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
}
//We get the password of the user
$req = mysql_query('select password,id from users where username="'.$username.'"');
$dn = mysql_fetch_array($req);
//We compare the submited password and the real one, and we check if the user exists
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
?>
<?php
}
else
{
//Otherwise, we say the password is incorrect.
$form = true;
$message = 'The username or password is incorrect.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
any help would be greatly appreciated.. thank you.
UPDATE: As #Dagon corrected me..
To redirect user back to index.html, you can use the following:
header('Location: http://example.com/index.html');
exit;
after successful login.
So your source code is not preferly the best to this way of login, but even in this way you should make a redirection after login.
It you can do with JavaScript, exactly i recomend you tu use jQuery API, which will help you to improve many things on your site.
So in your situation i recomend you this way of solution:
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
echo "<script>$('#idofelement2reload').load('php.php?login=1');</script>";
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
}
So if you noticed, this line
echo "<script>$('#idofelement2reload').load('php.php?login=1');</script>";
writes a line into html document which call a function to load through jQuery a file with parameter that the user is logged in.
Don`t forget to include jQueries source code in head
Use the header() function after setting the user information in $_SESSION.
// If the password is good, we don't show the form
$form = false;
// We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
header('Location: http://example.com/index.html');
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
header('Location:http://sitename.com/index.php');
?>
I'm trying to mess around with a simple log in form, that is just for fun. The content is nothing sensitive, but I'm trying to learn SESSION and such. I've created this simple login form, that works fine, but if a user clicks the "home" button which is href'd to process_login.php, they are asked to login again. I'm trying to save the username and password it in a SESSION so if they login, and hit home from any page, it will remember their log in information and not ask them to continuously log in.
I have a form.php script, that uses the POST method, with two textfields, the username and password are saved as "admin" in the process_login.php, and if they match the POST indices from the form, then i'll include content.php. In process_login.php I take the POST data and run it like so :
SESSION_start();
//var_dump($_POST);
$match_username = 'admin' ;
$match_password = 'admin';
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($username == $match_username && $password == $match_password ){
include 'content.php';
}elseif($username == "" || $password != $match_password){
echo "Please try again.";
}
if(!isset($_SESSION["logged_in"])){
//Run if not set
$_SESSION["logged_in"] = array(1 => array($username => $_POST['username'], $password => $_POST['password']));
};
};
You'll see above that I'm trying to set the SESSION information, but I know i'm not doing it correctly. Once a user logs in, everything works. But if that same user clicks on "home," from another page, it will tell them to "Please try again." I'd like to let the user stay logged in once they are logged in.
All advice is appreciated. Thank you!
Your test of $_SESSION["logged_in"] should not be inside the if(isset($_POST['submit'])) block.
if (isset($_SESSION['logged_in'])) {
include 'content.php';
exit();
}
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username == $match_username && $password == $match_password ){
$_SESSION["logged_in"] = array('username' => $_POST['username'], 'password => $_POST['password']);
include 'content.php';
exit();
} elseif($username == "" || $password != $match_password){
echo "Please try again.";
}
// Put login form here
I changed your $_SESSION["logged_in"] variable. Now it's just a one-dimensional array instead of 2-dimensional, and the keys are the words username and password -- it doesn't make much sense to use variables as keys there.
Hello fellow programmers and coders. I am developing an enhanced login script based on the already great login script by zubrag.
What i am trying to achieve: If the user is an admin, he will be logged in. If the user is a regular user, he will not be logged in.
What happens: The user gets logged in, even if he is not an admin.
Here is a snippet of the code:
// user provided password
if (isset($_POST['access_password'])) {
$login = isset($_POST['access_login']) ? $_POST['access_login'] : '';
$pass = $_POST['access_password'];
if (!USE_USERNAME && !in_array($pass, $users)
|| (USE_USERNAME && ( !array_key_exists($login, $users) || $users[$login] != $pass ) )
) {
showLoginPasswordProtect("Incorrect username or password.");
}
The Part that i am having trouble with:
elseif (array_key_exists($login, $admins)) {
showLoginPasswordProtect("User not an admin.");
}
Rest of the code:
else {
// set cookie if password was validated
setcookie("verify", md5($login.'%'.$pass), $timeout, '/');
setcookie("user", $login, 0, '/');
// Some programs (like Form1 Bilder) check $_POST array to see if parameters passed
// So need to clear password protector variables
unset($_POST['access_login']);
unset($_POST['access_password']);
unset($_POST['Submit']);
}
}
Username and password array:
$users = array(
'username' => 'password',
'administrator' => 'administrator-password'
);
Admin array:
$admins = array(
'administrator'
);
Now picture all of that together, and what would the problem be? (It's probably really easy, i'm just not a professtional coder.)
Are you sure that admins can login?
Here you are saying that if the username is in the admin array, deny the acces:
elseif (array_key_exists($login, $admins)) {
showLoginPasswordProtect("User not an admin.");
}
What you probably want to do is deny the acces for users not in the admin array:
elseif (!array_key_exists($login, $admins)) {
showLoginPasswordProtect("User not an admin.");
}