Tutorial: PHP/mySQL Simple User Counter
Posted by Pat
Today I am going to show you how to make a simple user counter with total and unique hit statistics. This is just a simple script tutorials so you will be able to build upon it.
Let set up our database structure:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php // This is how your DB will be setup. /* CREATE TABLE IF NOT EXISTS `visitors` ( `visitor_id` int(11) NOT NULL auto_increment, `name` varchar(225) NOT NULL default '', `value` varchar(225) NOT NULL default '', PRIMARY KEY (`visitor_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; INSERT INTO `visitors` (`visitor_id`, `name`, `value`) VALUES (1, 'ip', ''), (2, 'hits', '0,0'); */ ?> |
Now to call the database in conf.inc.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <?php $db_user = ""; // Username $db_pass = ""; // Password $db_database = ""; // Database Name $db_host = ""; // Server Hostname $db_connect = mysql_connect ($db_host, $db_user, $db_pass); $db_select = mysql_select_db ($db_database); // Code to pull the results from the db. $q = mysql_query("SELECT * FROM `visitors` WHERE `name` = 'hits'"); // Finds the row with the numbers $visitor = mysql_fetch_array($q); $visitor = split(",", $visitor['value']); // Splits the query result into an array. define('SITE_HITS', $visitor['0']); // Defines a constant for all hits define('SITE_UNI_HITS', $visitor['1']); // Defines a constant for unique hits function visitor($ip) { // Function that will be put on main page. $q_ip = mysql_query("SELECT * FROM `visitors` WHERE `name` = 'ip'") or die(mysql_error()); // Finds the info for all of the ip's $r_ip = mysql_fetch_array($q_ip); // Fetches the ip array we will use later. $array_ip = split("-", $r_ip['value']); // Splits the results and turns it into an array of all the ips $q_hit = mysql_query("SELECT * FROM `visitors` WHERE `name` = 'hits'") or die(mysql_error()); // Finds the info for the hits $r_hit = mysql_fetch_array($q_hit); $hit = split(",", $r_hit['value']); // Splits the query results into an array. $hits = $hit['0']; // The total hits $uni = $hit['1']; // The unique hits if (in_array($ip, $array_ip)) { // If the users ip is in the array we defined earlier $hits++; // Adds a hit, but not a unique hit } else { $hits++; // Adds both a unique and hit because he is a new user. $uni++; $ip = $r_ip['value'] . $ip; // Adds the new ip to the ips already in the db mysql_query("UPDATE `visitors` SET `value` = '$ip' WHERE `name` = 'ip'"); // Updates the table } $hits = $hits . "," . $uni; // Combines the hits and unique hits mysql_query("UPDATE `visitors` SET `value` = '$hits' WHERE `name` = 'hits'"); // Updates the table } ?> |
Breakdown:
First we set the db info.
Next we define the hit/unique constants to display it on the stats page.
After we create the function visitors to add the users ip and hits into the db.
Now the code you would put in the index.php or the page you want the stats for.
1 2 3 4 5 | <?php include("conf.inc.php"); visitor($_SERVER["REMOTE_ADDR"]); // Use the function we defined earlier with the users ip. echo "Main page"; ?> |
Breakdown:
First we include the conf.inc.php for the db info and the functions.
Next we initiate the function visitors with the users ip.
Now for the stats.php page:
1 2 3 4 5 6 | <?php include("conf.inc.php"); echo "Total Hits: " . SITE_HITS; echo "<br />"; echo "Unique Hits: " . SITE_UNI_HITS; ?> |
And thats it, I hope you build off it. If you have any questions please feel free to post. Thanks
Tutorial: PHP/mySQL Simple IP Banning
Posted by Pat
Today I am going to show you how to create an IP ban system. This does not include an IP manager, although if I receive enough requests, I will.
To start things off we need to create the page conf.inc.php. This page will be included in all the pages and contain the ban function and database details.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?php $db_user = ""; // Username $db_pass = ""; // Password $db_database = ""; // Database Name $db_host = ""; // Server Hostname $db_connect = mysql_connect ($db_host, $db_user, $db_pass); // Connects the the database $db_select = mysql_select_db ($db_database); // Selects the DB we will be searching in. // IP Ban Check function is_banned($ip) { // Starts the is_banned function. $q = mysql_query("SELECT * FROM `ban` WHERE `ip` = '$ip'") or die(mysql_error()); // Searches the database for the users ip. $rows = mysql_num_rows($q); // Counts all the results found. if ($rows > 0) { // If more than 0 were found. $banned = true; // The user is banned. } else { $banned = false; // The user is not banned. } return $banned; } ?> |
Breakdown:
We 1st connect the the database in order to retrieve data.
Then we create the function called is_banned() to check if the users ip is in the ban list.
Now we will implement this code in index.php.
1 2 3 4 5 6 7 8 9 | <?php include("conf.inc.php"); // Include the database and function details. if (is_banned($_SERVER["REMOTE_ADDR"])) { // Start out function with the users ip. echo "Error: You have been banned from this website!"; // The user is banned. exit(); // Halts the rest of the script from performing. } else { echo "You have not been banned, congrats on not being one of the many assholes."; } ?> |
Now that script is not complex, but it is so you can build on it. I hope this was helpful to you. As always, if you have any questions, please feel free to ask.
Tutorial: PHP/mySQL Membership System
Posted by Pat
Hi, today I am going to show you how to make a simple membership system. This included, registering for an account, logging in, security for pages, and logging out.
Now shall we begin? I say yes!
Our database will be setup like the following:
1 2 3 4 5 6 7 | CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(11) NOT NULL auto_increment, `username` varchar(225) NOT NULL default '', `password` varchar(225) NOT NULL default '', `email` varchar(225) NOT NULL default '', PRIMARY KEY (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; |
Breakdown:
user_id is the default value that keeps track of users.
username is the users log in name.
password is the users log in password.
email is the users email, so in later versions of the member system, a forgot password can be added.
Our 1st bit of code will be a file named conf.inc.php. This file holds all of our mysql and function data, so we don’t have to enter it over and over :D.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php $db_user = ""; // Username $db_pass = ""; // Password $db_database = ""; // Database Name $db_host = ""; // Server Hostname $db_connect = mysql_connect ($db_host, $db_user, $db_pass); // Connects to the database. $db_select = mysql_select_db ($db_database); // Selects the database. function form($data) { // Prevents SQL Injection global $db_connect; $data = ereg_replace("[\'\")(;|`,<>]", "", $data); $data = mysql_real_escape_string(trim($data), $db_connect); return stripslashes($data); } ?> |
Breakdown:
The 1st part is all the mySQL information in order to view and insert data.
The 2nd part prevents SQL injection, so people cant gain unauthorized access.
Our next file will be register.php, it will allow users to register an account so they may login and view parts of the website that others cant.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <?php include("conf.inc.php"); // Includes the db and form info. if (!isset($_POST['submit'])) { // If the form has not been submitted. echo "<form action=\"register.php\" method=\"POST\">"; echo "<table>"; echo "<tr>"; echo "<td colspan=\"2\">Register:</td>"; echo "</tr>"; echo "<tr>"; echo "<td width=\"50%\">Username:</td><td width=\"50%\"><input name=\"username\" size=\"18\" type=\"text\" />"; echo "</tr>"; echo "<tr>"; echo "<td width=\"50%\">Password:</td><td width=\"50%\"><input name=\"password\" size=\"18\" type=\"text\" />"; echo "</tr>"; echo "<tr>"; echo "<td width=\"50%\">Email:</td><td width=\"50%\"><input name=\"email\" size=\"18\" type=\"text\" />"; echo "</tr>"; echo "<tr>"; echo "<td colspan=\"2\"><input type=\"submit\" name=\"submit\" value=\"submit\"</td>"; echo "</tr>"; echo "</table>"; echo "</form>"; } else { // The form has been submitted. $username = form($_POST['username']); $password = md5($_POST['password']); // Encrypts the password. $email = form($_POST['email']); if (($username == "") || ($password == "") || ($email == "")) { // Checks for blanks. exit("There was a field missing, please correct the form."); } $q = mysql_query("SELECT * FROM `users` WHERE username = '$username' OR email = '$email'") or die (mysql_error()); // mySQL Query $r = mysql_num_rows($q); // Checks to see if anything is in the db. if ($r > 0) { // If there are users with the same username/email. exit("That username/email is already registered!"); } else { mysql_query("INSERT INTO `users` (username,password,email) VALUES ('$username','$password','$email')") or die (mysql_error()); // Inserts the user. header("Location: login.php"); // Back to login. } } mysql_close($db_connect); // Closes the connection. ?> |
Breakdown:
We 1st include the database details and make sure the form has not been submitted. If it has not been submitted then we display the register form.
If the form is submitted, we make some variables so we can incorporate the form() function.
We then make sure that the users email or user name are not already in the database.
Then we insert the user into the database and redirect them to the login page.
The next page is login.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <?php include("conf.inc.php"); // Includes the db and form info. session_start(); // Starts the session. if ($_SESSION['logged'] == 1) { // User is already logged in. header("Location: index.php"); // Goes to main page. exit(); // Stops the rest of the script. } else { if (!isset($_POST['submit'])) { // The form has not been submitted. echo "<form action=\"login.php\" method=\"POST\">"; echo "<table>"; echo "<tr>"; echo "<td colspan=\"2\">Login:</td>"; echo "</tr>"; echo "<tr>"; echo "<td width=\"50%\">Username:</td><td width=\"50%\"><input name=\"username\" size=\"18\" type=\"text\" />"; echo "</tr>"; echo "<tr>"; echo "<td width=\"50%\">Password:</td><td width=\"50%\"><input name=\"password\" size=\"18\" type=\"text\" />"; echo "</tr>"; echo "<tr>"; echo "<td colspan=\"2\"><input type=\"submit\" name=\"submit\" value=\"submit\"</td>"; echo "</tr>"; echo "</table>"; echo "</form>"; } else { $username = form($_POST['username']); $password = md5($_POST['password']); // Encrypts the password. $q = mysql_query("SELECT * FROM `users` WHERE username = '$username' AND password = '$password'") or die (mysql_error()); // mySQL query $r = mysql_num_rows($q); // Checks to see if anything is in the db. if ($r == 1) { // There is something in the db. The username/password match up. $_SESSION['logged'] = 1; // Sets the session. header("Location: index.php"); // Goes to main page. exit(); // Stops the rest of the script. } else { // Invalid username/password. exit("Incorrect username/password!"); // Stops the script with an error message. } } } mysql_close($db_connect); // Closes the connection. ?> |
Breakdown:
1st we include the db and function file, and start the session, telling the browser that sessions will be used.
We then make sure the form has not been submitted in order to show the login form.
If the form has been submitted we make 2 variables for user name and password. We encrypt the password with md5() so it is a bit more secure. (To all those who are experts in PHP, you would normally salt a password to make it harder to crack, but for beginners stick with md5())
We then have a query checking the database if any users match the use rname and password, and if there are matches it will be counted in $r.
If there are matches we set a login session.
Now we will make logout.php.
1 2 3 4 | <?php session_unset(); // Destroys the session. header("Location: login.php"); // Goes back to login. ?> |
Breakdown:
We destroy all sessions and forward the user to the login page.
And last but not least, the page where you want only logged in users to view.
1 2 3 4 5 6 7 8 9 10 11 | <?php include("conf.inc.php"); // Includes the db and form info. session_start(); // Starts the session. if ($_SESSION['logged'] != 1) { // There was no session found! header("Location: login.php"); // Goes to login page. exit(); // Stops the rest of the script. } echo "This is the main page!"; echo "<br />"; echo "<a href=\"logout.php\">Logout?</a>" ?> |
Breakdown:
We include the config page.
Check to see if the logged in session is set, otherwise forward user to login page.
Allow the user to log out if needed.
Well thats the basic member system, I will add as people request more. If you have any questions please feel free to comment or contact me, I am more than happy to help!