Archive for February, 2011

HTML and PHP notes

February 10th, 2011 | Category: websites/programming

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

February 06th, 2011 | Category: websites/programming

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

Been a while…

February 03rd, 2011 | 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