Building a CMS Part 2

Note: This post is currently undergoing review and will be updated within the next few days to reflect more recent standards and better code quality.

So if you’re following this set of tutorials you should now have your very own login system that allows users to sign up and login. However these tutorials aren’t about building a user base, so we need to add the functionality of a CMS. At the moment if a user logs in they will be presented with a blank screen which isn’t very useful at all, so now we will create a rather friendly member’s area. But before we do, let’s assess what we need in the member’s area. Well to begin with we want to be presented with a list of editable pages right? So we will need to produce a list of all of these pages from the database. With this in mind, create a file called index.php, not forgetting to add the normal document base structure, and then copy the code below into the file.

<?php require("connect.php");  session_start(); ?>
echo '<h1>Member\'s Area</h1> <ul>';
<?php
$sql = mysql_query('SELECT * FROM content');
$pages = mysql_num_rows($sql);
$pagesedit = $pages + 1;
$pageselector = 1;
echo '<a href="http://mywebsite.com/addpage.php"><li>[+] <strong>Add new page</strong></li></a>';
while($pages >= $pageselector){
$contentresult = mysql_query("SELECT * FROM content WHERE id = '".$pageselector."'");
$contentrow = mysql_fetch_array($contentresult);
echo '<a href="http://mywebsite/edit.php?page='. $contentrow['page'] .'"><li><strong>'. $contentrow['title']   .'</strong><span>Last updated on <strong>'. $contentrow['lastupdate'] .'</strong> by <strong>'. $contentrow['updater']   .'</strong></span></li></a>';
$pageselector++;
}
?>
</ul>

Now the middle bit with all the PHP might seem a little complex, but if we break it down it makes more sense. At the top we simply select all the records from our “content” table that we created earlier, and then count how many we have with the function mysql_num_rows(). Then we echo out a link to a page that we will later use to create new pages. After that we create a while loop which loops through the content of the table, and for each record, it echos a link to another page we haven’t yet created, that we will be able to edit pages of the site with. Now I know it might seem like a lot to take in, but if you take a moment to look at it logically it makes perfect sense!

Now if you were to visit that page right now you would likely get an error because we don’t have anything in our table yet. To stop this from happening we are going to create a new file called addpage.php which we will use to create pages. Now I warn you there is a lot of code for this page, so much in fact I’ve given it it’s own special type of container! But don’t worry because all will be explained!

<?php
require("connect.php");
session_start();
mysql_connect($dbhost, $dbuser, $dbpass) or die('>>Error connecting to Database<br />');
mysql_select_db($dbname) or die('>>Unable to select Database');
if(!empty($_POST['title'])){
$filename = str_replace(" ", "-",$_POST['url']);
$filename1 =  "root/folder/" . $filename . ".php"; //EDIT THIS LINE!
$filehandle = fopen($filename1, 'w') or die("Can't open file");
$blankPage = '
<?php
$currentPage = "'.$_POST[url].'";
require("connect.php");
$result = mysql_query("SELECT * FROM content WHERE page = \'$currentPage\'");
$row = mysql_fetch_array($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $row[title] ?></title>
</head>
<body>
<?php echo "<h1>" . $row[title] . "</h1>" ?>
<?php echo "<p class=\"text\">" . nl2br($row[text]) . "</p>"; ?>
</body>
</html>
';
fwrite($filehandle, $blankPage);
fclose($filehandle);
mysql_query("INSERT INTO content(page,title,text,lastupdate,updater) VALUES('$filename','".ucwords($_POST[title])."','TBC','".gmdate('d-m-y')."','$_SESSION[firstname] $_SESSION[lastname]')") or die(mysql_error());
$file = "http://mywebsite.com/".$filename.".php";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Add New Page</title>
</head>
<body>
<?php if(!empty($file)){ echo '<span class="infomsg"><a>Here is the URL for the new page: '. $file .'<br />To edit <a href="http://mywebsite.com/edit.php?page='.str_replace("/", "",$filename).'">click here</a></a></span>'; }; ?>
<form id="editor" action="addpage.php"  method="post">
<label id="top" for="title">Page Title: </label><br />
<input type="text" id="title" name="title" value="New Page" />
<br />
<br/>
<label for="text">Path to Page: </label><br /><br />
<label for="text">http://mywebsite.com/</label>
<input type="text" id="url" value="new-page" name="url" /><label for="text">.php</label>
<br />
<br />
<input id="submit" type="submit" value="Add Page" />
<br />
<br />
</form>
</div>
</div>
</body>
</html>

Now I know that’s a lot of code, but bare with me here, I’m about to go through it all with you now (again if you get it, feel free to skip). So at the top of the code we make our usual connection to our database and then there’s a load of code. For the time being skip the rest of the PHP code until you get down to the actual page entitled “Add new Page”. On this page we first have an if statement to check if a variable is empty, and if not, then we echo a message to the user so that they know where their newly created file is. Then we have a form into which users can enter a title and a URL for a new page, but what you may have noticed is that this page doesn’t post the information to another, but instead to itself – and that’s why it is so long. So once the form is submitted we can jump back to the top of the page to examine the rest of the code. After the connection we can see an “if” statement which checks to see if the form has been submitted, if it has, then it executes a large block of code.

At the top of this block of code we have 4 variables. Our $filename variable takes the URL that the user has supplied and replaces any spaces with a hyphen – this is because we don’t want page URL with spaces in them – one of my pet hates! After this we create an actual URL for the file, now it is important that you get this part right, you cannot have a URL such as “http://yoursite.com/”, instead you have to have your folder root, so if your site is inside a folder such as “public_html” then you will put “public_html/”, it’s basically the furthest back you can go on your server in terms of folders – just keep going up until you can’t go up no more! Next we create a file handle which inserts the URL into a more useful variable to be used later on. Next we have our blank page which is a generic skeleton to be used for every page of the site. Notice that the only variable that changes is the that of $currentPage, this is the variable used to communicate with the database, so it is imperative that it is correct.

Lastly we have the fwrite() function which attempts to write to a file using the URL we supply, and the information we give it with $blankPage. If the function cannot find the file specified, then it simply creates it, which is very useful indeed! Then, we close the function and insert all the information into the database, leaving the text field with simply “TBC” or to be confirmed. If you want to change the default text feel free to do so. And finally we set the value of the $file variable so that the user can be presented with the URL of the file they just created!

Phew, that was a lot of code!

Now I must warn you that if the page already exists this page wil overwrite it, so be careful when naming pages. But if everything is working visit the page and create a brand new page, call it anything you want and submit the form! After you have done this, go to the index page and you should see the page title, when it was last updated, and who it was last updated by in the list! Great stuff, but we’re not done yet, because if you click the link you are going to end up with an error because we haven’t yet created the editing page – don’t worry it’s really simple, so lets do it now. Go ahead and create a new page called edit.php and paste the following code into it.

<?php session_start(); $currentPage = $_GET['page'];
$result = mysql_query("SELECT * FROM content WHERE page = '".$currentPage."'");
$row = mysql_fetch_array($result);
if($row['title'] == ""){ echo "<script type=\"text/javascript\">window.location = \"http://yoursite.com/\"</script>"; die(); };

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Editing: <?php echo $row['title']; ?></title>
</head>
<body>
<h1>Editing Page: <?php echo $row['title'] ?></h1>
<form id="editor" action="process.php?page=<?php echo $currentPage ?>"  method="post">
<?php if($_GET['status'] == "success"){ echo "<div id=\"infomsg\"><p>Page successfully updated!</p></div>"; } ?>
<label id="top" for="title">Title: </label><br />
<input type="text" id="title" name="title" value="<?php echo $row['title'] ?>" />
<br />
<br/>
<label for="text">Text: </label><br />
<textarea name="text" id="text"><?php echo $row[text] ?></textarea>
<br />
<br />
<input id="submit" type="submit" value="Submit Changes" />
<br />
<br />
</form>
</body>
</html>

So although it may not look it, this page is really simple. At the top we connect to our database and fetch the page supplied by the URL. We then grab all the page’s information from the database and fill up some variables with that information. You may have noticed that we use Javascript this time to redirect the user if they aren’t logged in, why? Well because variety is the spice of a CMS! We then fill a text box and a text area with the values from our database. Now again this form submits to another page, and so we are going to have to create it. So create a new page named process.php and paste the following code into it.

<?php $currentPage = $_GET['page']; require("connect.php"); session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Editing</title>
</head>
<body>
<?php
$title = $_POST['title'];
$text = $_POST['text'];
if($title == "" || $text == ""){ echo "<h1>No input Recieved!</h1>"; die(); }
mysql_query("UPDATE content SET title= '$title' WHERE page='$currentPage'") or die('Unable to change Title');
mysql_query("UPDATE content SET text='$text' WHERE page='$currentPage'") or die('Unable to change Text');
mysql_query("UPDATE content SET lastupdate='". date("d-m-y")."' WHERE page='$currentPage'") or die('Unable to insert Date');
mysql_query("UPDATE content SET updater='$_SESSION[firstname] $_SESSION[lastname]' WHERE page='$currentPage'") or die('Unable to insert Name');
?>
<script type="text/javascript">
document.location = "http://yoursite.com/edit.php?page=<?php echo $currentPage ?>&status=success";
</script>
</body>
</html>

So the above is a really simple page, basically all it does is take what the user enters into the form and updates the record in the database. Notice the helpful error messages as well; using relevant error messages can help you to track down an error faster, so I defiantly recommend it. Now if the page exists, and process.php is able to update it, it should redirect users back to the editing page with a success message. If it has worked you should now see your changes reflected on the page that you were editing.

Now to finish off this part of the tutorial we are going to create the simpelest page ever that will allow you to destroy the session variables and ultimately log out. We’ll call it logout.php (unexpected eh?). Create the file and paste in the code below.

<?php session_start(); session_destroy() ?>

And that’s it for this tutorial, in the next part we’ll look at how we can allow the user to add images and links, as well as the all important styling so that it looks pretty! Stay tuned!


Posted

in

by

Comments

2 responses to “Building a CMS Part 2”

  1. xvfeng avatar

    Hey, have u work this out? I’ve meet the similar problem too.When I am adding a new page use the ‘addpage.php’ and input the title and url, and then hit add page button, it shows “Warning: fopen(localhsot/CMS/new-page.php) [function.fopen]: failed to open stream: No such file or directory in C:\xampp\htdocs\CMS\addpage.php on line 9
    Can’t open file”. I know there must be some thing wrong with the path folder, but as I am using xampp as my server, I can’t figure out how to find the right path, please help!

    1. Tom avatar

      Hey, this is simply an error with your file structure rather than the code. Have you tried visiting the folder and verifying the file does indeed exist, and that the filename matches that in your code?