Skip to content
Advertisement

Maching users from username to user_group

So im setting up a ranks system on my website. (there is probably an easier way to do it) Here is what i tried.

JavaScript

and here is my server.php file for extra info. (details included)

JavaScript

Basically i want to set certain sessions to certain groups, its the only way i can hide links from users that are either logged in/logged out or don’t have a high enough rank to visit a page.

Advertisement

Answer

How to make a simple user registration and log in form?

The first thing you should consider when making user registration portal is where and how you are going to store user accounts. For this purpose we are going to use MySQL database with the following table:

JavaScript

In this table we are going to store the username and the password hash. We also have a column that will tell us the type of the account; whether it is a normal user or an admin.

Database connection

We obviously need to connect to the database and start a session. These topic are out of scope of this answer. We are going to use PDO to connect to our database which holds our new table.

JavaScript

For a more in-depth explanation of how PDO works take a look at this article: https://phpdelusions.net/pdo

Register function

We can now create a simple function that will register a user in the database. This function will accept 3 parameters: the DB connection, username, and password.

This function will create a hash of the password, then discard this password. It is a simple example, but in real-word you would probably want to add more checks and make this more foolproof.

JavaScript

The login function

Just as we did with the registration function, we will create one function for logging in. The function will accept the same parameters, but instead of INSERT it will SELECT from the database based on the matching username.

If there is a matching record in the database and the password is verified against the stored hash then we store the user information in a session. The session will persist this information on the hard drive and it will give the user a cookie to be used when making future requests. Using that cookie PHP will open the same session each time the page is requested.

JavaScript

The full code

We can now connect all of this together and add some HTML forms. The HTML part is out of scope but you would want to keep it separate from your PHP logic. Probably in a separate file altogether.

JavaScript

This is a very simple example of how registration and logging in works in PHP. I would not recommend to use it as-is on a live site, but for learning purposes, it should demonstrate how this functionality works.

You can build on top of it and do something when the user type is different. Show more content to more privileged users.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement