Creating Your Own CMS Part 2 – Access Levels & Administrators

Posted in Coding, Coding, PHP, Tutorials4 years ago • Written by 13 Comments

Alright if you have read the first article that we worked on a while ago “Creating Your Own CMS Part 1 – Secure Login” then you should have some sort of CMS design with a secure login. Now that we can login to our CMS we will need to have an easy way to add an administrator and of course give them access to only certain parts of the CMS. But first one little thing that I decided to add in to make it easy for you to login without having to manually add an entry in phpmyadmin was to make the first login attempt double as a create user.

<?php
        //this first part checks to see if you are already logged in and if you are it redirects you
        if(isset($_SESSION['started']))
	{
		header('Location: /admin/');
		exit;
	}

        //this next is actually something that i just thought of because it is annoying to
        //have to add an entry via phpmyadmin with a md5  password (and even worse
        //when you get into much more secure passwords)
        if(isset($_SESSION['failed']))
		unset($_SESSION['failed']);
	if(isset($_SESSION['no_su']))
		unset($_SESSION['no_su']);
        //above clears out the no_su and failed session variables to clear just in case

	$su_check = $db->query("SELECT id FROM logins WHERE super_user='1' LIMIT 1");
	if(!$db->num_rows($su_check))
		$_SESSION['no_su']=true;
        if($_POST && !$_SESSION['no_su'])
	{
		//here is the login code that we used before
	}
	elseif($_POST && $_SESSION['no_su']==true)
	{
		//no_su is only set if there are no entries in the logins table
		//so this will put one in there
		$username = stripslashes($_POST['username']);
		$password = md5($_POST['password']);

		$db->query("INSERT INTO logins (username,password,date_added,super_user) VALUES('$username','$password','".time()."','1')");
		unset($_SESSION['no_su']);
	}
?>

You can see in the above query that I set the field super_user=’1′ on my insert. I did this because this should be the main/root/admin account or whatever you would like to call it. And later when we make permissions the super_user will be giving access regardless.

I do also add a little note when the login page loads so that you know you are not trying to login but you are actually setting up the main/first login account. This is accomplished by adding a block of php in the html that creates the login box like below.

<?php
	if(isset($_SESSION['failed']) && $_SESSION['failed']=='yes')
		echo '<div id="fail" class="info_div"><span class="ico_cancel">Incorrect username or password!</span></div>';
	elseif(isset($_SESSION['no_su']) && $_SESSION['no_su']==true)
		echo '<div id="fail" class="info_div"><span class="ico_cancel">SETUP SUPER USER ACCOUNT!</span></div>';
?>

As you can see above, there is also a check for a failed attempt that will output an error message if need be.

Adding And Editing Access Levels

Access levels are something that can vary greatly depending on the site and it’s requirements. A site could be managed by one person and need only one level, that being total access. Some sites will hire freelance blog writers, and these writers do not need access to anything more than the most basic levels which allow them to write and save their posts. I mean seriously, there are some real nut cases out there, just because you think you know someone doesn’t mean you should let them have access to your site. The access level control that we are going to create is pretty powerful, and very flexible, but will not be as in depth as something bigger sites would have.

The logic behind the access levels that we are going to use is going to be as simple as giving certain people access to certain php files. We can also have a setting to give them access to live content or not. First, to make it easy to keep track of the files that we want to restrict access to we are going to create an array of the “admin pages”. The beauty part of this array is it can be used for more than just access levels. We will use this array to actually build the site navigation and to restrict access. Obviously there are other ways to do this, but if we have it all in an array then when we want to add a new page to our admin we will not have to change any coding to add it to the access levels and everything else.

<?php
	$_AP = array(
		array(title=>'Dashboard',
			url=>'/admin/content/'
			),
		array(title=>'Content',
			url=>'/admin/content/content.php',
			dd=>array(
				array(title=>'Add Content',
					url=>'/admin/content/content.php?action=add'
					)
				)
			),
		array(title=>'Events',
			url=>'/admin/content/events.php',
			dd=>array(
				array(title=>'Add Event',
					url=>'/admin/content/events.php?action=add'
					)
				)
			),
		array(title=>'Venues',
			url=>'/admin/content/venues.php',
			dd=>array(
				array(title=>'Add Venue',
					url=>'/admin/content/venues.php?action=add'
					)
				)
			)
		);
?>

You can see from the array I am building my navigation. So this way, when I want to add a new page to my admin I simply start by adding a new entry to the array. When I do this it will automatically be on the page. If I have key ‘dd’ with an array nested inside of there, it becomes a drop down. There are many different ways that you could possibly structure the array, and many different things that you can add to it. Below is the code that we use to go through the array and create that navigation.

<?php
        	function create_nav($ap,$close=false)
	{
		define('LB',chr(10));
		$output;
		if(is_array($ap))
		{
			$count = count($ap);
			$i=1;
			foreach($ap as $k => $v)
			{
				$output .= '<li><a href="'.$v['url'].'">'.$v['title'].'</a>'.LB;
				if($v['dd'])
				{
					$output .= '<ul>'.LB;
					$output .= create_nav($v['dd'],true);
				}

				if($close==true && $i==$count)
					$output .= '</ul>'.LB;
				$output .= '</li>';
				$i++;
			}
		}
		return $output;
	}

        //The function is simply called like this with $_AP obviously being the array of pages
        echo create_nav($_AP);
?>

You can see that this is pretty simple, it just runs through the loop and creates an unordered list of all of the items.

Now let’s build a simple form to add and edit users and access levels

I am going to assume that you know how to build form elements (and if you don’t there are some great simple tutorials right here on 1WD). So I am going to go through the logic behind it. You will of course want a simple for to add/edit users and a form to add/edit different access levels. First, lets talk about the access levels. For the access levels we can make it as simple as a form to name the access level and an array of checkboxes, one for each page. Then say I want to create an access level “admin” I would just type “admin” into the name textbox and check all of the checkboxes which will grant them access to every tab, as you can see below.

Access Levels

Then with the add/edit administrators you will simply want to hit up the database for all of the available access levels and put them in a drop down to choose from. And lastly I will show you how to put these to use.

When someone logs into the admin we set several session variables, and the users access level will be one of them. So we can just write a function that we put in the header, to make sure that it is on every page, that will check whether that person has access to the page they are trying to access. The function could look something like this.

<?php
		function check_access(){
			GLOBAL $db;
			$al = $_SESSION['access_level'];
			$a_q = $db->query("SELECT pages FROM access_levels WHERE id='$al' LIMIT 1");
			$a = $db->fetch_assoc($a_q);//pages is just a serialized array in the database
			$allowed_pages = unserialize($a['pages']);
			$parts = explode('/',$_SERVER['REQUEST_URI'];
			$count = count($parts);
			if(!in_array($parts[$count-1],$allowed_pages)){ //if the page they want isn't in the array of pages they can have
				header('Location: /admin/');//send them home
				exit;
			}
		}
?>

And here we have a very simple version of admins and access levels that is based off of php scripts access. We can take this further in many different ways, and one would be to also allow setting “action” access per page. Like allowing users to add/edit, but not delete. And it would be very simple to implement in the function that we just coded by checking the query string for actions.

Other parts of the tutorial:

7 Written ArticlesWebsite

I am a web developer by trade but originally went to school for Information Technology - Network Engineering Technology at Purdue University. Getting into web development as a student web developer I developed a passion for it that left networking seem a bit boring. Even though I finished up my networking degree I stuck with web development lately I have been a WP7 advocate. My Blog.

13 Comments Best Comments First
  • Abhishek

    Thursday, February 10th, 2011 12:13

    2

    Nice tutorial. A live demo or access to source code (download? ) would have been better with this tutorial!

    +2
  • Martin Haško

    Sunday, February 13th, 2011 02:10

    5

    Very good guide! Please could you put somewhere the whole download? Thank you for your willingness!

    0
    • Brad Billman

      Sunday, February 13th, 2011 19:45

      6

      I will work towards getting something nicely packaged that I can share with you all. The examples I put up here I actually write as I am coding the CMS so it is not complete and does not have a lot of the more advanced features as the CMS that I actually use for most of my work. I did recently start a small site of my own just to showcase some work and have my portfolio and you can check there from time to time. bbillman.com

      Thanks to all.

      0
      • Martin Haško

        Monday, February 14th, 2011 14:36

        7

        I am from Slovakia and the fact I really liked that your work! Could you at least that what you have done these two parts to put together some whole and with the theme from nicetemplate.com put in some whole download, because I have long wondered about your own redakčnýcm system and many people like me from Slovakia and the would be at least a first step into our CMS! Thank you in advance for your willingness! : D

        0
  • Ignas

    Thursday, February 10th, 2011 14:33

    4

    What I firstly would do is to try get rid of this HTML code from PHP code! Use template engine or just have your “engine”. It means simple class which generates HTML. There you will have PHP + HTML (PHP is templating language itself), but you never get used to HTML + PHP in a normal code, not the templates. Be careful with that and please mention it in tutorials for the newbies.

    0
    • Matt

      Thursday, February 10th, 2011 17:17

      1

      Many of us have been combining php and html code together for years… I find it to be an invaluable skill as I believe it teaches the coder to understand the interaction between html and PHP much better.

      Not everything needs to be developed in a template system or a framework… I guess if your site is going to have a lot of rapid growth in size and pages it makes sense, but many, many sites just don’t fit that mold.

      0
  • Mitesh

    Thursday, February 10th, 2011 19:52

    3

    Excellent tutorial and a wonderful way to showcase your programming skills.

    I will be tuning into your other tutorials…

    Cheers!

    0
  • Tanner Ottinger

    Thursday, February 17th, 2011 06:36

    8

    Great! Can’t wait for the next one!

    0
  • Dave Kein

    Tuesday, December 6th, 2011 08:59

    13

    is it possible to integrate our custom CMS with ZenCat? It’s great article on CMS. Thanks.

    0
  • Trent

    Tuesday, September 6th, 2011 04:12

    12

    Hi, It’s nice tutorial . According to me , function create_nav is Recursive functions , if we had more item in nav, we ‘ll waste much time to load ,we should use cache to increase performance of this function. Thanks you very much.

    0
  • benj

    Monday, April 18th, 2011 15:00

    9

    Hey, could you package this up for me, give it out for free, code up a template for it, upload it to my site and then work out some SEO for it? I mean, you want to show us how it’s done, right? If you could throw together a framework for it, that would be super awesome! Kthxbye. =D

    All kidding aside, thanks for this tutorial. I’ve been looking for a decent tut about the actual nuts and bolts of coding user management. I look forward to the rest.

    0
  • Dheeraj

    Monday, July 18th, 2011 18:43

    10

    Thanks for sharing coding part. I download many ebooks on CMS developement but all are lack in coding part.I want to ask a question which language is preferable to develope CMS ASP.net or PHP ????

    0
  • Dave Kein

    Tuesday, December 6th, 2011 08:59

    13

    is it possible to integrate our custom CMS with ZenCat? It’s great article on CMS. Thanks.

    0
  • Trent

    Tuesday, September 6th, 2011 04:12

    12

    Hi, It’s nice tutorial . According to me , function create_nav is Recursive functions , if we had more item in nav, we ‘ll waste much time to load ,we should use cache to increase performance of this function. Thanks you very much.

    0
  • Dheeraj

    Monday, July 18th, 2011 18:43

    10

    Thanks for sharing coding part. I download many ebooks on CMS developement but all are lack in coding part.I want to ask a question which language is preferable to develope CMS ASP.net or PHP ????

    0
  • benj

    Monday, April 18th, 2011 15:00

    9

    Hey, could you package this up for me, give it out for free, code up a template for it, upload it to my site and then work out some SEO for it? I mean, you want to show us how it’s done, right? If you could throw together a framework for it, that would be super awesome! Kthxbye. =D

    All kidding aside, thanks for this tutorial. I’ve been looking for a decent tut about the actual nuts and bolts of coding user management. I look forward to the rest.

    0
  • Tanner Ottinger

    Thursday, February 17th, 2011 06:36

    8

    Great! Can’t wait for the next one!

    0
  • Martin Haško

    Sunday, February 13th, 2011 02:10

    5

    Very good guide! Please could you put somewhere the whole download? Thank you for your willingness!

    0
    • Brad Billman

      Sunday, February 13th, 2011 19:45

      6

      I will work towards getting something nicely packaged that I can share with you all. The examples I put up here I actually write as I am coding the CMS so it is not complete and does not have a lot of the more advanced features as the CMS that I actually use for most of my work. I did recently start a small site of my own just to showcase some work and have my portfolio and you can check there from time to time. bbillman.com

      Thanks to all.

      0
      • Martin Haško

        Monday, February 14th, 2011 14:36

        7

        I am from Slovakia and the fact I really liked that your work! Could you at least that what you have done these two parts to put together some whole and with the theme from nicetemplate.com put in some whole download, because I have long wondered about your own redakčnýcm system and many people like me from Slovakia and the would be at least a first step into our CMS! Thank you in advance for your willingness! : D

        0
  • Ignas

    Thursday, February 10th, 2011 14:33

    4

    What I firstly would do is to try get rid of this HTML code from PHP code! Use template engine or just have your “engine”. It means simple class which generates HTML. There you will have PHP + HTML (PHP is templating language itself), but you never get used to HTML + PHP in a normal code, not the templates. Be careful with that and please mention it in tutorials for the newbies.

    0
    • Matt

      Thursday, February 10th, 2011 17:17

      1

      Many of us have been combining php and html code together for years… I find it to be an invaluable skill as I believe it teaches the coder to understand the interaction between html and PHP much better.

      Not everything needs to be developed in a template system or a framework… I guess if your site is going to have a lot of rapid growth in size and pages it makes sense, but many, many sites just don’t fit that mold.

      0
  • Mitesh

    Thursday, February 10th, 2011 19:52

    3

    Excellent tutorial and a wonderful way to showcase your programming skills.

    I will be tuning into your other tutorials…

    Cheers!

    0
  • Abhishek

    Thursday, February 10th, 2011 12:13

    2

    Nice tutorial. A live demo or access to source code (download? ) would have been better with this tutorial!

    +2

Comments are closed.

54.226.116.197 - unknown - unknown - US