Mar 15

CMS

So I have decided to create a CMS. Content Management System. Ok, I have been trying to come up with a content management system for some time and have just ended up running in circles. I have made about 4 different versions of a mod_rewrite type template and page separate system for my various websites. I think it’s time I listed out some goals.

CMS Goals:

The System Must:

  • Be OOPhp
  • Support MVC type architecture
  • Have a Database Abstraction layer in the Model that supports serialization for database-less (or at least sqlite) setups.
  • Support Templates
  • Support Manual Page Creation
  • Support XML type page creation
  • Support Php in pages.
  • Support non mod_rewrite installations.
  • Provide sitemap and rss feed.

The CMS should have (but may not in beta):

  • a dashboard

The CMS would be nice if it had:

  • a js dropdown style dashboard.
  • calendar support

 

List of notes:

VIEW       -> Templates
CONTROLLER -> Pages
MODEL      -> Abstract -> DB or Serialized Data Objects

Need to have a repo for universal functions outside of an object.
Needs to have a page data object that holds general data about each page. Autobuilt for manually created pages.

CMS Object controls all:


Controller Object deals with client pages/code as well as model calls

View  Object controls templating


Model Object controls access to saved data


Helper Object gives other Objects the ability to add multi controller/view code


System Object deals with UI and other system level stuff

PAGE


CONTROLLER

VIEW

Use a common template grabber

HELPER

 

Comments are off for this post

Mar 12

RSS and PHP

Guess, what? It’s time for another post on php. This time our subject is RSS. First off, what is rss? I will skip the wikipedia definition and say that rss is a type of simple xml that search engines, web browsers and programs use to poll your site for news updates. RSS feeds are formatted in the XML format, meaning the layout of the file is very similar to html. If you are using firefox to view this webpage, the little orange square in the address bar is an example of an RSS feed. Let’s take a look at some example rss:

<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
 <channel>
  <title>Teslamad News Feed</title>
  <description>All things Teslamad</description>
  <link>http://www.teslmad.com</link>
  <pubDate>Mon, 02 Feb 2011 16:45:00 +0700 </pubDate>
  <item>
   <title>2.5W white laser</title>
   <description>New page added about our most recent adventure with the 2.5W white laser....</description>
   <link>http://www.teslamad.com/lasers/white25w</link>
   <pubDate>Tue, 22 Feb 2011 00:00:00 -0500</pubDate>
  </item>
  <item>
   <title>different event</title>
   <description>description</description>
   <link>http://www.example.com/news</link>
   <pubDate>Tue, 24 Feb 2011 11:18:23 -0500</pubDate>
  </item>
 </channel>
</rss>

So what is this? It is an RSS feed with two items. Each item is considered to be a different news post, it has its own publication date, title, description, and link to a page that has the whole story. Cool, huh?

What if we had a news bar on our webpage that we update weekly? If we wanted to add RSS we would need to either update each by hand, or write some php to handle both. I would like to evaluate both outcomes of this idea separately. First we will look at making each feed item directly in php and using some echo commands to output rss type formatting when a client wants the news in RSS. Then we will look at making an RSS feed and using the simpleXML extension, parse the file into php code for use in our html newsfeed output. I like the second method from a server time standpoint. The RSS feed is usually going to get more access than any given page in a medium or small site, so it makes sense to have it a flat file. That said, a large site with many users may prefer the php side due to the ease of using a database. For example, both WordPress and Drupal use a (much more detailed) version of the first method that we shall see. Their implementation uses a database to store each news item rather than storing them directly in a php file and format like I am about to show.

So first we shall look at the php to rss approach:

<?php
class Rss{
 public $title;
 public $description;
 public $link;
 public $pubDate;
 public $items = array();

 public function __construct($title,$description,$link,$pubDate){
  $this->title = $title;
  $this->description = $description;
  $this->link = $link;
  $this->pubDate = new DateTime($pubDate);
 }
 public function addItem($item){
  if(is_object($item))
   $this->items[] = $item;
 }
 public function asXML(){
  $output.= '<?xml version="1.0" encoding="UTF-8" ?>'."\r\n";
  $output.= '<rss version="2.0">'."\r\n";
  $output.= '<channel>'."\r\n";
  $output.= '<title>'.$this->title.'</title>'."\r\n";
  $output.= '<description>'.$this->description.'</description>'."\r\n";
  $output.= '<link>'.$this->link.'</link>'."\r\n";
  $output.= '<pubDate>'.$this->pubDate->format('D, d M Y H:i:s O').'</pubDate>'."\r\n";
  foreach($this->items as $feed)
   $output.= $feed->asXML();
  $output.=  '</channel>'."\r\n";
  $output.=  '</rss>'."\r\n";
  return $output;
 }
}
class feed{
 public $title;
 public $description;
 public $link;
 public $pubDate; 

 public function  __construct($pubDate,$description,$link,$title = null) {
  $this->description = $description;
  $this->link = $link;
  $this->pubDate = new DateTime($pubDate);
  if($title)
   $this->title = $title;
  else
   $this->title = substr($description,0,30).'...';
 }
 public function asXML(){
  $output.= '<item>'."\r\n";
  $output.= '<title>'.$this->title.'</title>'."\r\n";
  $output.= '<description>'.$this->description.'</description>'."\r\n";
  $output.= '<link>'.$this->link.'</link>'."\r\n";
  $output.= '<pubDate>'.$this->pubDate->format('D, d M Y H:i:s O').'</pubDate>'."\r\n";
  $output.= '</item>'."\r\n";
  return $output;
 }
}
function newsfeed(){
 $rss = new Rss('Teslamad News Feed','All things teslamad','http://www.teslamad.com','3/11/11');
 $rss->addItem(new feed('02/22/2011','New page added about our most recent adventure with the 2.5W white laser.','http://www.teslamad.com/lasers/white25w'));
 $rss->addItem(new feed('02/03/2011','Finally adjusted the size of the videos embeded throughout the site. Enjoy','http://www.teslamad.com/faraday/faraday'));
 $rss->addItem(new feed('01/05/2011','Just added a new video to the faraday page. The left sleeve is almost complete!','http://www.teslamad.com/faraday/faraday'));
 $rss->addItem(new feed('01/01/2011','HAPPY NEW YEAR',null));
 $rss->addItem(new feed('12/10/2010','The faraday suit page is now up and running and I finally started the video series of the contruction  progress.','http://www.teslamad.com/faraday/faraday'));
 echo $rss->asXML();
}
newsfeed();
?>

Ok, now what on earth did we just do? In short, we just took five lines of php input and used them to create an RSS feed (page). The feed objects are the actual news updates and they are all considered elements in our Rss object. Finally, we use the asXML function call to get the RSS output. The call is made to the Rss object which in turn calls the asXML function of each of the feed objects. The output is xml in the RSS format. If we wanted to add another post to our newsfeed, we would follow the same pattern in the php script in the newsfeed() function:

$rss->addItem(new feed('date','description','link','title'));

This allows us to make a php object into an RSS newsfeed. But what about our html side?  This code does not make our php news sidebar work. We need to add some functions to our code in respect to html so we can output a useful html newsfeed.

<?php
class Rss{
 public $title;
 public $description;
 public $link;
 public $pubDate;
 public $items = array();

 public function __construct($title,$description,$link,$pubDate){
  $this->title = $title;
  $this->description = $description;
  $this->link = $link;
  $this->pubDate = new DateTime($pubDate);
 }
 public function addItem($item){
  if(is_object($item))
   $this->items[] = $item;
 }
 public function asXML(){
  $output.= '<?xml version="1.0" encoding="UTF-8" ?>'."\r\n";
  $output.= '<rss version="2.0">'."\r\n";
  $output.= '<channel>'."\r\n";
  $output.= '<title>'.$this->title.'</title>'."\r\n";
  $output.= '<description>'.$this->description.'</description>'."\r\n";
  $output.= '<link>'.$this->link.'</link>'."\r\n";
  $output.= '<pubDate>'.$this->pubDate->format('D, d M Y H:i:s O').'</pubDate>'."\r\n";
  foreach($this->items as $feed)
   $output.= $feed->asXML();
  $output.=  '</channel>'."\r\n";
  $output.=  '</rss>'."\r\n";
  return $output;
 }
 public function asHTML(){
  $output.= '<h1>'.$this->title.'</h1>';
  foreach($this->items as $feed)
   $output.= $feed->asHTML();
  return $output;
 }
}
class feed{
 public $title;
 public $description;
 public $link;
 public $pubDate;

 public function  __construct($pubDate,$description,$link,$title = null) {
  $this->description = $description;
  $this->link = $link;
  $this->pubDate = new DateTime($pubDate);
  if($title)
   $this->title = $title;
  else
   $this->title = substr($description,0,30).'...';
 }
 public function asXML(){
  $output.= '<item>'."\r\n";
  $output.= '<title>'.$this->title.'</title>'."\r\n";
  $output.= '<description>'.$this->description.'</description>'."\r\n";
  $output.= '<link>'.$this->link.'</link>'."\r\n";
  $output.= '<pubDate>'.$this->pubDate->format('D, d M Y H:i:s O').'</pubDate>'."\r\n";
  $output.= '</item>'."\r\n";
  return $output;
 }
 public function asHTML(){
  $output.= '<span>'.$this->pubDate->format('M/j/Y').'</span>'."\r\n";
  $output.= '<p>'.$this->title.'<br />'."\r\n";
  $output.= '<a href="'.$this->link.'">'.$this->link.'</a></p>'."\r\n";
  $output.= '<hr><br />'."\r\n";
  return $output;
 }
}
function newsfeed($type){
 $rss = new Rss('Teslamad News Feed','All things teslamad','http://www.teslamad.com','3/11/11');
 $rss->addItem(new feed('02/22/2011','New page added about our most recent adventure with the 2.5W white laser.','http://www.teslamad.com/lasers/white25w.html'));
 $rss->addItem(new feed('02/03/2011','Finally adjusted the size of the videos embeded throughout the site. Enjoy','http://www.teslamad.com/faraday/faraday.html'));
 $rss->addItem(new feed('01/05/2011','Just added a new video to the faraday page. The left sleeve is almost complete!','http://www.teslamad.com/faraday/faraday.html'));
 $rss->addItem(new feed('01/01/2011','HAPPY NEW YEAR',null));
 $rss->addItem(new feed('12/10/2010','The faraday suit page is now up and running and I finally started the video series of the contruction progress.','http://www.teslamad.com/faraday/faraday.html'));
 if($type == 'XML')
  echo $rss->asXML();
 else
  echo $rss->asHTML();
}
newsfeed('HTML');
?>

This addition to our code makes it possible for us to add our news page to the site and output an rss feed with the same code. Yay! What I love is all we did is add two functions to the classes and we increased functionality. Some of you may have noticed the use of the Datetime object, if you would like to know more about it, check out the php.net page on it and rejoice. I wish it had been around 6 years ago.

Moving on, let’s look at the RSS to php newsfeed option, the code is intentionally similar, but we are going to use an existing rss file that is static. This file is loaded using the simplexml_load_file command which creates a new simpleXML object. Let’s take a look at our rss input:

<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
 <title>Teslamad News Feed</title>
 <description>All things Teslamad</description>
 <link>http://www.sfskies.com/files/CMS3/</link>
 <pubDate>Mon, 02 Feb 2011 16:45:00 +0700 </pubDate>
 <item>
  <title>New page added about our most recent adventure with the 2.5W white laser....</title>
  <description>New page added about our most recent adventure with the 2.5W white laser....</description>
  <link>http://www.sfskies.com/files/CMS3/index.php?q=lasers/white25w</link>
  <pubDate>Tue, 22 Feb 2011 00:00:00 -0500</pubDate>
 </item>
 <item>
  <title>Finally adjusted the size of the videos embeded throughout the site. Enjoy...</title>
  <description>Finally adjusted the size of the videos embeded throughout the site. Enjoy...</description>
  <link>http://www.sfskies.com/files/CMS3/index.php?q=faraday/faraday</link>
  <pubDate>Thu, 03 Feb 2011 00:00:00 -0500</pubDate>
 </item>
 <item>
  <title>Just added a new video to the faraday page. The left sleeve is almost complete!...</title>
  <description>Just added a new video to the faraday page. The left sleeve is almost complete!...</description>
  <link>http://www.sfskies.com/files/CMS3/index.php?q=faraday/faraday</link>
  <pubDate>Wed, 05 Jan 2011 00:00:00 -0500</pubDate>
 </item>
 <item>
  <title>HAPPY NEW YEAR...</title>
  <description>HAPPY NEW YEAR...</description>
  <link>http://www.sfskies.com/files/CMS3/index.php?q=</link>
  <pubDate>Sat, 01 Jan 2011 00:00:00 -0500</pubDate>
 </item>
 <item>
  <title>The faraday suit page is now up and running and I finally started the video series of the contructio...</title>
  <description>The faraday suit page is now up and running and I finally started the video series of the contructio...</description>
  <link>http://www.sfskies.com/files/CMS3/index.php?q=faraday/faraday</link>
  <pubDate>Fri, 10 Dec 2010 00:00:00 -0500</pubDate>
 </item>
</channel>
</rss>

Now that we have our input, let’s take a look at the php:

<?php
class rss{
 public $title;
 public $description;
 public $link;
 public $lastBuildDate;
 public $pubDate;
 public $items = array();

 public function __construct($file){
  $xml                 = simplexml_load_file($file);
  $this->title         = $xml->channel->title;
  $this->description   = $xml->channel->description;
  $this->link          = $xml->channel->link;
  $this->lastBuildDate = $xml->channel->lastBuildDate;
  $this->pubDate       = $xml->channel->pubDate;

  foreach($xml->channel->item as $feed)
   $this->items[] = new feed($feed);
 }
 public function asHTML(){
  $output.= '<h1>'.$this->title.'</h1>';
  foreach($this->items as $item)
   $output.= $item->asHTML();
  return $output;
 }
}
class feed{
 public $title;
 public $description;
 public $link;
 public $guid;
 public $pubDate;

 public function __construct($feed){
  $this->title       = $feed->title;
  $this->description = $feed->description;
  $this->link        = $feed->link;
  $this->guid        = $feed->guid;
  $this->pubDate     = new DateTime($feed->pubDate);
 }
 public function asHTML(){
  $output.= '<span>'.$this->pubDate->format('M/j/Y').'</span>'."\r\n";
  $output.= '<p>'.$this->title.'<br />'."\r\n";
  $output.= '<a href="'.$this->link.'">'.$this->link.'</a></p>'."\r\n";
  $output.= '<hr><br />'."\r\n";
  return $output;
 }
}
$rss = new rss('teslamad.rss');
echo $rss->asHTML();
?>

So our rss to newsfeed code uses very similar elements to the php to rss method, but they differ in the source of the data. In the first example, the data is written in php, in the second, the php gets the data from an rss file. It just depends on the designer’s use and comfort level with each method.

Comments are off for this post

Feb 10

HTML and PHP notes

Someone told me that he still has trouble with html and php is no better. I thought that I might make his life easier by pointing out some useful tips and tricks for both as well as css. I may add some javascript, but it adds a level I am not fluent in yet.

Common HTML tags and functional php uses. Note: this assumes that you have figured out basic html and are up to using css and php (server side) for your uses.

<form action="" method="">

The form tag is a must when you want data sent to your php script. If used with the <input …> tag it allows you to send data from the user’s browser to your php script. here are two types of data sent to php from the browser, GET and POST. GET is easy to understand as you have probably seen it. An example of a get post is the following.

Get Example:

index.php?color=blue&season=spring&year=2011

In this example php could get these values back from the html submission by using the following:

$php_color = $_GET['color'];
$my_season = $_GET['season'];
$the_yr = $_GET['year'];

So we took html input and drew it into php for our use. Input is half the battle the other half is output. Before we get to output, I want to point out the difference between GET and POST. GET has the advantage of allowing access to links. For example:

<a href="index.php?variable=something">click</a>

This would actually work even with the form tag. But while this is used commonly it can be dangerous if used destructively. If you set up a function that deletes a file using GET, any computer could delete it with something like this:

 <a href="index.php?action=delete&file=system">click</a>

So it became clear that we needed a way to send data that was not easily abused by hackers and automated systems. This method is called POST. Post data is at least a little more secure and does not show in the browser bar when submitted. In html, post data is submitted when using the form tag like this:

<form method="post" action="some_php_page.php">
<input type="text" name="stuff" />
<input type="submit" value="Submit Stuff" />
</form>

The above code gets a variable called “stuff” that can be accessed by php using:

$_POST[''];

In this case that means:

$_POST['stuff'];

The tags that actually submit data from html to php are the following:
note: nothing is valid unless inside the <form> tag.

<input ...> used for lots of things
<select> Used for drop down lists
<textarea> used for large pieces of text

Now that we know the html players, we should figure out how they interact with php. Let’s say we have created a form for submitting contact information to a technical service. We have the html below.

<form method="post" action="contact.php">
Name: <input type="text" name="name" />
Email: <input type="text" name="email" />
Concern:
<select name="concern">
  <option value="tech">Technical Problems</option>
  <option value="prod">Product Information Request</option>
  <option value="jobs">Employment Information</option>
</select>
Details:
<textarea name="details"></textarea>
<input type="submit" value="Submit" />
</form>

Now we have our html form, we need to create some php to catch the submitted data.We have four pieces of data, name, email, concern, and details. In this case, all are strings, and have the potential for characters that annoy php, like ?!;[]()=+-<>, etc. But we still need to have them for basic language. So we are going to use the filter_input function instead of just using $_POST['name']. We will also be using Object Oriented Php for this example. We are also going to contain the html, php and object in one page. While doing it this way may not make sense for larger projects, it helps understanding in the small scale. Since we have also done all this work toward error checking, we might as well also return that data to the person using the form.

<html>
<head>
<title>Our Company - Contact</title>
<style>
ul.error{
 border: 1px solid red;
 margin: 10px;
 width:300px;
}
li.error{}
input.error {border: 1px solid red;}
textarea.error {
 border: 1px solid red;
}
</style>
</head>
<body>
<?php
class ContactForm{
 public $name;
 public $email;
 public $concern;
 public $details;
 public $errors = array();
 public $destination;
 public function __construct(){
  $this->name = filter_input(INPUT_POST,'name',FILTER_SANITIZE_STRING);
  $this->email = filter_input(INPUT_POST,'email',FILTER_SANITIZE_EMAIL);
  $this->concern = filter_input(INPUT_POST,'concern',FILTER_SANITIZE_STRING);
  $this->details = filter_input(INPUT_POST,'details',FILTER_SANITIZE_STRING);
  if($this->concern == 'tech')
   $this->destination = 'technical_support@ourcompany.com';
  else if($this->concern == 'prod')
   $this->destination = 'product_support@ourcompany.com';
  else if($this->concern == 'jobs')
   $this->destination = 'employment@ourcompany.com';
  else
   $this->destination = 'hacking@ourcompany.com';
 }
 public function validate(){
  $valid = true;
  if(strlen($this->name)<1){
   $this->errors['name'] = 'Name field is blank';
   $valid = false;
  }
  if(strlen($this->email)<1){
   $this->errors['email'] = 'Email field is invalid';
   $valid = false;
  }
  if(strlen($this->details)<20){
   $this->errors['details'] = 'Details field must have at least 20 characters';
   $valid = false;
  }
  if(!preg_match("/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/",$this->email)){
   $this->errors['email'] = 'Invalid Email';
   $valid = false;    
  }
 }
 public function send(){
  if(!$this->errors){
   $to = $this->destination;
   $subject = $this->concern;
   $message = $this->details;
   $headers = 'From: '.$this->email."\r\n" .
   'Reply-To: '.$this->email."\r\n" .
   'X-Mailer: PHP/' . phpversion();
   if(mail($to,$subject,$message,$headers))
    echo 'Message sent, thank you';
   else{
    echo 'Message not sent, please try again';
    $this->display();
   }
  }
  else
   $this->display();
 }
 public function errors(){
  if(!empty($this->errors)){
   $output = '<ul>';
   foreach($this->errors as $error)
   $output.= '<li>'.$error.'</li>';
   $output.= '</ul>';
   return $output;
  }
 }
 public function display(){
  echo $this->errors();
 ?>
 <form method="post" action="contact.php">
 <p>Name: <input type="text" name="name" value="<?php echo $this->name; ?>" <?php echo ($this->errors['name']?'class="error" ':''); ?>/></p>
 <p>Email: <input type="text" name="email" value="<?php echo $this->email; ?>" <?php echo ($this->errors['email']?'class="error" ':''); ?>/></p>
 <p>Concern:
 <select name="concern">
 <option value="tech"<?php echo ($this->concern == 'tech'?' selected="selected"':''); ?>>Technical Problems</option>
 <option value="prod"<?php echo ($this->concern == 'prod'?' selected="selected"':''); ?>>Product Information Request</option>
 <option value="jobs"<?php echo ($this->concern == 'jobs'?' selected="selected"':''); ?>>Employment Information</option>
 </select>
 </p>
 <p>Details:<br />
 <textarea name="details" <?php echo ($this->errors['details']?'class="error" ':''); ?>><?php echo $this->details; ?></textarea>
 </p>
 <p>
 <input type="submit" value="Submit" />
 </form>
 <?php
 }
}
$contact = new ContactForm();
if($_POST){
 $contact->validate();
 $contact->send();
}
else
 $contact->display();
?>
</body>
</html>

So we just did a lot, we just took our html form and added a php class, then sprinkled php in amongst our form as well as containing it in our html page. This approach may not be the way to accomplish larger projects, but it does mean that all the script and html is in one place, a lot less hunting when debugging. The object gets the data from the form when submitted, then we validate the sent data to make sure that the client filled out all the fields. If they have, we send the email to the associated email. We used the strlen command to count the number of characters in our variable, the mail command to send an email, the filter_input command to reduce the chance of hacking, and the ternary operator ({condition}?{value_if_true}:{value_if_false}) because it is a lot shorter than if..else. We also used the preg_match command to at least halfway validate the email address. While I was researching the subject of email validation, I came upon an article that stated this will not handle email addresses with “abc\@xyz@domian.net” which is technically a valid email address. But it will work fine for most mail addresses. Please be nice and replace the email addresses listed above with something that you can recieve email at. The people at ourcompany.com will appreciate it. That’s it for this post, let me know if you have questions.

Comments are off for this post

Feb 6

So was recently talking to a friend of mine and he is getting into php, I recommended getting familiar with Object Oriented PHP. I started thinking about all the reasons I prefer it over the procedural style of programming. I realized that for a new user, it seems like more code and more work to even bother with adding objects. Most of the time they want to get what they are doing done and never look back. I know, I used to program exactly like that. Now I have spent a lot of time fixing all the code I made badly five or six years ago. It gets annoying but doing that little extra in the first place saves a lot of fixes later.

On to my intro and reasoning for OOPhp

So a common situation I have run into with procedural programming that causes problems is the overuse of simple functions. One day you make this great little function called display(). The next week you make a new display() function that has slightly different code and you want to use it as well in the same script. So you rename the old display display_old(). This fixes the problem for now, and you only have to go through and fix it here or there. Life is good and it works, that’s what matters.

Except it doesn’t. The next time you make another display() and run into the same issue, all three are used to produce nearly the same result, but each page they are used on needs slight differences. Now you realize that you have written the same code three times and used it three different ways in three different pages. This problem multiplies when you start trying to do updates or other changes to your scripts. We are left with the choice of either keeping each page completely separate, or doing three functions in one require with names like display(), display_page2(), display_old(). It gets ugly quick.

This is one of the cool things about OOPhp, you can use the same object in many different ways while still calling the same function.

Here is an example of an Object that has a display method (function). We can contain both variables and methods in one object. So our code that is slightly different can be contained inside the object rather than having to have multiple functions.

classes/page.php
<?php
class Page {
    public $css;
    public $body;
    public $title;
    public function display(){
        echo '<html>';
        echo '<head>';
        echo '</title>'.$this->title.'</title>';
        echo $this->css;
        echo '</head><body>';
        echo $this->body;
        echo '</body></html>';
    }
}
?>

Now that we have our object, let’s use it to create three different pages.

index1.php
<?php
include 'classes/page.php';
$page = new Page();
$page->css = 'some css file';
$page->title = 'Page 1';
$page->body = 'This is page 1';
$page->display();
?>
index2.php
<?php
include 'classes/page.php';
$page = new Page();
$page->css = 'some different css file';
$page->title = 'Page2';
$page->body = 'This is page 2, it uses the same class as page 1 so it can use the same function, but this will be the output now';
$page->display();
?>

Now that we have an example of what we can do with our object, let’s try out a little more advanced use. Let’s say that the object itself can determine the content to display based on input from the browser. So rather than having a couple static pages, we have one page that takes care of the formatting and such, then what is different between pages is contained in the object.

Again we start with the class. Remember that the class is what we call the code used to create the object.

classes/page.php
<?php
class Page{
    public $css;
    public $title;
    public $body;
    public __construct(){
        $page_name = filter_input(INPUT_GET,'q',FILTER_SANITIZE_STRING);
        if(file_exists('pages/'.$page_name.'.php'))
            require   'pages/'.$page_name.'.php';
        else
            $this->body = 'unable to find page';
    }
    public function display(){
        require 'templates/index.php';
    }
}
?>
pages/page1.php
<?php
$this->css = '';
$this->title = 'Page 1';
$this->content = 'This is the content of page one';
?>
pages/page2.php
<?php
$this->css = '';
$this->title = 'Page 2';
$this->content = 'This is the content of page two';
?>
templates/index.php
<html>
<head>
<title><?php echo $this->title; ?></title>
<?php echo $this->css; ?>
</head>
<body>
<a href="index.php?q=page1">Page 1</a> | <a href="index.php?q=page2">Page 2</a>
<?php echo $this->body; ?>
</body>
</html>

index.php
<?php
require 'classes/page.php';
$page = new Page();
$page->display();
?>

So now we have done a lot, we filtered the input from the browser with the filter_input() command, created different pages using the same object, and are now using a template to format the look and feel of each page in one place. We have also used PHPs object constructor method called __construct(). This method is automatically called when we used the $page = new Page().  The OOPhp style of wrapping up our code into a reusable package is one of its main advantages. It allows you to treat different situations accordingly without having to write out the code all over again. It also helps in the debugging department later on when you have only one class to pound away at to get right rather than 50 functions.

I have put together my two examples below in a zip file if you want to try them out.

OOPhp
Comments are off for this post

Feb 3

Been a while…

Category: Uncategorized

Figured I would check in on my website, maybe dust off the cobwebs, clean the floors. Nah, I’ll be back later.

That said, I would like to update everbody on the last 6 months.

I graduated from unm with an EE.

I am helping build a large solar power system that could be the largest private installation in santa fe county.

I spent most of January in South America, and 10 days of that on a motorcycle.

I want to make a quick javascript calculator for solar power on my blog, but it may be a while.

I am doing a lot of object oriented php recently. I might put out some alpha code of what I am doing for whoever wants to play with it.

later,

JB

Comments are off for this post

Aug 6

Respect

Category: Uncategorized

Recently I have been assaulted with the phrase “I am surprised that no one has shot Obama”. I find it unamerican that any American citizen would make such a statement. I was not (nor ever a fan of) George W Bush yet I never stated that I “was not surprised someone had killed him”. Those words are actually considered a terrorist statement according to the definition of the word “terrorist”. I find it not only unamerican, but also irreligious that any person in this (mostly Christian, Hebrew,¬† Muslim) country would ever endorse the murder of any person, let alone a person from their own country. That is unethical, irresponsible and reprehensible.

Why do we have the right to condemn the person that WAS VOTED INTO OFFICE TO DEATH because of his race/politics/choices? As Americans we have the right to vote him out of office, that it IT. THOU SHALT NOT KILL or have you forgotten your studies? Any responsible citizen should dispute the comments involving the death of the president, it was not put up with in the days of your parents, it should not be put up with now. They respected their elders, but they also had to make hard decisions, we do too, don’t give up on your point of view because your elders don’t respect the president. They should be citizens too, even if they don’t agree with him.

Comments are off for this post

Feb 24

just an update

Category: Uncategorized

So I am in my senior year of college towards an electrical engineering degree, my focus will be in control systems and my track is in computer operation. I feel like I know enough to learn more. One of the advantages of have suffered through all those math and physics classes is the unique perspective you have on the world. Things are less trivial and more integral. When you look at a device, you can see it for what it is, what it is made of, and what composes those parts. You can also understand the digital logic used to give a user the result based on a series of inputs, and how those inputs work on a fundamental level. We have learned rules for input and output, frequency and sampling, control and instability, good and bad. I have about 11 weeks to go before I am done. I am very worried about what comes next. What changes my life will take. What should I do?

Comments are off for this post

Nov 19

Routers and DNS and Firewalls! Oh My!

Category: Uncategorized

Back in the day when the internet was safe… who am I kidding? It’s the Internet! Wild animals and bored hackers have been roaming the net since kurt cobain was still alive. Be afraid, be very afraid. So how can we cruise the internet jungle without getting attacked by trojan lions, tiger worms, or malware bears? The honest answer is we can’t, and we are even more vulnerable when we are in charge of the safety of others. Allowing your public (or even private) wifi to be accessed by friends, family, or customers can put your computer and your network at risk of damage, data loss, and even identity theft.¬† Is there a perfect way to secure it? Sure, unplug your computer from the wall, the internet, and turn off then wifi, then stick a big, angry magnet on the hard drive. Granted, this approach will make your computer a great paperweight, but not very operational. Access to the internet comes with many advantages and many pitfalls. The Internet should contain a warning from the Surgeon General. We all want wifi, so what can we do to make is safer for our clients and ourselves?

Encrypt it. Yes I know you have all heard this about a million times, but it is the first and best way to protect your privacy and long term sanity. Wireless antennas broadcast information in a 360 degree pattern from the base station, then means that when your wifi is near your neighbor’s window, he has just as good reception as you do. Encrypt access to your wireless, starting with a MAC block is a start, it would be best to also use WPA2 encryption as it has been proven that WEP encryption takes about 45 seconds to crack if you know the right tools. If you allow customers to acces your wifi, passwords and MAC addition can make using your wifi more trouble than it is worth. For these types of networks, I suggest obtaining a router or AP that offers wireless client isolation, this at least will prevent a wifi user on your network from easily attacking another user. Also, make sure that the business network is separate from the customer wifi, as this could give your customers access to all the business financial documents. When I say seperate, I mean behind a firewall that does not allow any access between the two.

Use a better router. I have found that an old computer with a P3 or comparable processor can be made into a very powerful router. Free software like PfSense, IPCop, or Clarkconnect, are designed to act as a firewall/router/server geared toward the professional or hobbyist that is willing to learn a little about what makes a good service. Computer based routers make things a lot more controllable because you can add software to meet your needs, and offer stateful packet inspection (SPI). Another advantage is the firewall configuration options, I use PfSense and have more options than I can think of using.

Block certain services. One of the more useful services that good routers provide is port blocking, I know that some of the better linksys routers offer the same service, but I have found that if you have more than about 5 people using it at once, it can overwhelm the router and leave it ‘bricked’. I block ports 6667-6999 because these are the standard bittorrent ports, while I have no personal issue with bittorrent, I have a legal problem with getting sued over a customer downloading music illegally. Also, someone using your wifi for bittorrent will end up bogging down your surfing as well as put you at risk. I also block 53 with the exception of the openDNS servers so users can’t easily bypass my content filtering. Which brings up our next subject.

Use a DNS server that offers content filtering. The reason for this is twofold, it provides you with details about what services your users are surfing, which might affect advertising, and it prevents unwanted activity from affecting your network or your users. I use a free service provided by openDNS.com that gives me a choice of 50 different block options and allows me to blacklist or whitelist sites as I see fit. An infected computer behind a firewall makes the firewall pretty much useless as the infected computer is already past the firewall, a malicious program accidentally found on an unsavory website can be the cause, so rather than wait until it is too late, I try to prevent my users from visiting sites that could be a potential risk.

There is no real way to make the internet safe and completely accessible, it is a constant balance between accessibility and security, one that never seems balanced to everyone. As long as the steps you take are reasonable, they are steps that you can defend when you do have a grumpy user, very few of us get it right the first time.

Ta!

Comments are off for this post

Sep 17

Socialism

Category: Uncategorized

Socialism as defined by Merriam Webster:any of various economic and political theories advocating collective or governmental ownership and administration of the means of production and distribution of goods.

Example: Social Security.
Example: Welfare.
Example: Medicare.

Anyone who takes part in these programs benefits from government spending on its own people. So I ask, who out there who partakes in these programs voluntarily thinks that socialized medicine is a bad idea? In the long run it will lower medicare costs, reduce employee downtime, and make a more rugged society in general. Social security, Medicare, and Welfare are no less “socialist” than programs America has in place today. I urge any persons who are serious about denying social medicine a chance, to look at the programs they take advantage of and ask themselves why it is fundamentally different. If you still think it is wrong, stop signing that welfare or social security check, and stop letting medicare cover your medicine.

2,000,000 / 304,059,724 = 0.00658 = 0.658% Faux news
70,000 / 304,059,724 = 0.00023 = 0.023% Reality

Comments are off for this post

Aug 27

The list

Category: school

What I need to graduate UNM with a Bachelors Degree in Electrical Engineering:

ECE321L Electronics I
ECE322L Electronics II
ECE344L Microprocessors
ECE419 Senior Design I
ECE420 Senior Design II
ECE445 Introduction to Control Systems
ECE446 Design of feedback Control Systems

ME481 Digital Control of Mechanical Systems

CE304 Statics and Dynamics

This Semester (Fall 2009):
ECE 321L
ECE 419
ECE 445
CE 304

Next Semester (Spring 2010):
ECE 322L
ECE 344L
ECE 420
ECE 446
ME 481

My focus will be in control systems and my technical electives were computer science based.
Wish me luck.

Comments are off for this post

Next Page »