Pages

This is default featured slide 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Monday, August 27, 2012

Installing LAMP Server On Ubuntu


Install Apache

To start off we will install Apache.
1. Open up the Terminal (Applications > Accessories > Terminal).
2. Copy/Paste the following line of code into Terminal and then press enter:
sudo apt-get install apache2
3. The Terminal will then ask you for you're password, type it and then press enter.

Testing Apache

To make sure everything installed correctly we will now test Apache to ensure it is working properly.
1. Open up any web browser and then enter the following into the web address:
http://localhost/
You should see a folder entitled apache2-default/. Open it and you will see a message saying "It works!" , congrats to you!

Install PHP

In this part we will install PHP 5.
Step 1. Again open up the Terminal (Applications > Accessories > Terminal).
Step 2. Copy/Paste the following line into Terminal and press enter:
sudo apt-get install php5 libapache2-mod-php5
Step 3. In order for PHP to work and be compatible with Apache we must restart it. Type the following code in Terminal to do this:
sudo /etc/init.d/apache2 restart

Test PHP

To ensure there are no issues with PHP let's give it a quick test run.
Step 1. In the terminal copy/paste the following line:
sudo gedit /var/www/testphp.php
This will open up a file called phptest.php.
Step 2. Copy/Paste this line into the phptest file:
<?php phpinfo(); ?>
Step 3. Save and close the file.
Step 4. Now open you're web browser and type the following into the web address:
http://localhost/testphp.php

Install MySQL

To finish this guide up we will install MySQL. (Note - Out of Apache and PHP, MySQL is the most difficult to set up. I will provide some great resources for anyone having trouble at the end of this guide.)
Step 1. Once again open up the amazing Terminal and then copy/paste this line:
sudo apt-get install mysql-server
Step 2 (optional). In order for other computers on your network to view the server you have created, you must first edit the "Bind Address". Begin by opening up Terminal to edit the my.cnf file.
gksudo gedit /etc/mysql/my.cnf
Change the line
bind-address = 127.0.0.1
And change the 127.0.0.1 to your IP address.
Step 3. This is where things may start to get tricky. Begin by typing the following into Terminal:
mysql -u root
Following that copy/paste this line:
mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('yourpassword');
(Make sure to change yourpassword to a password of your choice.)
Step 4. We are now going to install a program called phpMyAdmin which is an easy tool to edit your databases. Copy/paste the following line into Terminal:
sudo apt-get install libapache2-mod-auth-mysql php5-mysql phpmyadmin
After that is installed our next task is to get PHP to work with MySQL. To do this we will need to open a file entitled php.ini. To open it type the following:
gksudo gedit /etc/php5/apache2/php.ini
Now we are going to have to uncomment the following line by taking out the semicolon (;).
Change this line:
;extension=mysql.so
To look like this:
extension=mysql.so
Now just restart Apache and you are all set!
sudo /etc/init.d/apache2 restart

Wednesday, August 22, 2012

How to Validate a Form Using PHP Part 2: Streamline Using Arrays

We’ve touched upon the basic elements of form validation and error messages in part 1 of this series, which outlines a relatively static method identifying errors and validating a form. In this edition we are going to make the elements we began with more dynamic and reduce the amount of script required to do so using arrays.

Setting Up the Form

First we’re going to want to create a form on a new .php document, mine is going to be called errorpart2.php. Below is my form complete with fields name, email, and comments.
<form id="commentform" method="post" action="errorpart2.php"> 
    <p> 
    <label for="name">Name:</label> 
    <br/> 
    <input name="name" id="name" type="text"/> 
    </p> 
    <p> 
    <label for="email">Email:</label> <br/> 
    <input name="email" id="email" type="text"/> 
    </p> 
    <p> 
    <label for="comments">Comment:</label> 
    <br/> 
    <textarea name="comments" id="comments" rows="4"></textarea> 
    </p> 
    <p> 
    <input name="submit" id="submit" type="submit" value="Submit" /> 
    </p> 
</form>  
The next step is to put in place a check to see if the form is submitted, so the script knows to validate. For those that have read part 1 of this series I had used a hidden input to pass this check, I have since done some additional research on the matter and found an alternative more secure method.
if (array_key_exists('submit',$_POST)){ 
//Form has been submitted 
}  
This method checks the $_POST array for the key ‘submit’, which is the array key for our Submit button, and would only be present if the form was submitted. We will be placing all of our validation related script within this IF statement, ensuring it only runs when required.

Laying Down Array Groundwork

We will need to define the arrays we will be using for this script, one containing all the field names on the form, one with all the mandatory fields, and one to store any errors we come across.
    // Fields that are on form  
    $expected = array('name''email''comments'); 
    // Set required fields 
    $required = array('name''comments'); 
    // Initialize array for errors 
    $errors = array();  
The $expected array serves to identify and process all  fields, mandatory or not. It also ensures that only the fields you specify are processed and prevents security issues from rogue $_POST values.


Making It Dynamic

The next part is where a big benefit of using arrays comes into play. Instead of typing out IF statements for each $_POST field, we can make use of the foreach statement to do this dynamically.
foreach ($_POST as $field => $value){ 
    // Make sure field was done correctly otherwise add error.  
 
This snippet goes through each key and the corresponding value that the $_POST array holds. This means that each field submitted will be processed, which is especially useful when dealing with long forms.
From within this foreach we now want to do two things to each variable passed through it..
1. Clean up the variable by eliminating whitespace if it is not an array. I used shorthand for this conditional statement:
// Assign to $temp and trim spaces if not array  $temp = is_array($value) ? $value : trim($value);  
2. If field is empty then make sure it is not required, otherwise add related error message to the $error array. For those unfamiliar with array_push, it can be used to append additional values into an existing array, in this case the one we defined before:
  1. // If field is empty and required, tag onto $errors array  
  2. if (empty($temp) && in_array($field, $required)) {  
  3.       array_push($errors, $field);  
  4.   
  5. }  
Once these two steps are in place, we have finished the foreach statement.

Handling the Errors

Now that we have the $error array with the names of each required field not filled out, we need to either accept the form or show the error messages.
If the form is done correctly:
if (empty($errors)){ 
        //The form is completed properly to do with as you please 
        unset($errors); 
}  
The unset(); function destroys the $errors array, so it does not cause incorrect error messages to be displayed.
To display error messages I placed the following lines of code next to the corresponding labels, only appearing when applicable:

<?php if (isset($errors) && in_array('name'$errors)){?> 
<div class="red">Please enter name</div> 
<?php } ?>  
This checks the $errors array for the specified field name , in this case ‘name’, which would only be present if an error happened. The same lines must be placed next to each field you are displaying an error for. I included the error message with my CSS styles applied, they can be found in the complete script at the bottom of this page.

Prevent Inputs from Clearing After an Error

When a user submits the form after completing some of the mandatory fields but not all, they would currently be shown an error message and the form would be cleared. This is a frustrating usability problem that can drive users away. Luckily, now that we have implemented array based validation, it is also easy to fix.
This line of code checks if there are any errors and, if there are, it inserts value = “” containing the user input submitted. This puts the value of the input to whatever the user had it as prior to the error, so they don’t have to retype anything. It is important to enclose this echo statement in literal ‘ ‘ quotes as well as wrap the $_POST[] in htmlentities. To ensure quotes and other symbols inputted do not break your page htmlentities converts some symbols to their HTML equivalent (example:  ” to &quot; ).
<input name="name" id="name" type="text"  
    <?php if (isset($errors)) { echo 'value="'.htmlentities($_POST['name']).'"'; } ?>  
/>  
The above will work for inputs, but the following tweak must be done to accommodate a textarea:
<textarea name="comments" id="comments" rows="4"><?php 
    if (isset($errors)) { echo htmlentities($_POST['comments']); } 
?></textarea>  
It is important to note that in order to avoid white space, make the <?php tags touch the textarea tags.

How to Validate a Form Using PHP Part 1: Streamline Using Arrays

Having a site visitor fill out a form is the primary way to gather information. Forms are the main line of communication with anyone that visits your site, so taking the time to make sure users fill them out correctly is key. Using PHP, we are able to ensure that all fields are properly filled out before submission, with required adjustments being called to attention through the use of error messages.

The CSS & HTML Groundwork

Let’s start off by opening up a fresh php document and putting a form within it. I have created errorpart1.php

<html>
    <head>
        <title>Form validation using PHP</title>
        <style type="text/css"><!--Styles--></style>
    </head>
    <body>
        <div id="content">
           <!--PHP and Form to go here-->
        </div>
    </body>  
</html>  
With the following styles applied to the form:

*{
    padding:0px;
    margin:0px;
}
body{
    text-align:center;
    font:11px "Lucida Grande",Arial,sans-serif;
}
#content{
    width:300px;
    text-align:left;
    margin:10px;
}
.formitem{
    width:100%;
    padding6px;
    font:11px "Lucida Grande",Arial,sans-serif;
}
h2{
    font:18px "Helvetica",Arial,sans-serif;
}
.box{
    width:100%;
    padding:10px 0px 10px 5px;
    margin-bottom8px;
    font-weight:bold;
}
.green{
    background-color:#95ca78;
    border-bottom:solid 1px #8AA000;
}
.red{
    background-color:#FDCBCA;
    border-bottom:solid 1px #E8514A;
 Next we have to construct our form, I have chosen to create a three field form, including one hidden field entitled “submitted”, which serves to check if the form has been completed.
<form action="index.php" method="POST" enctype="multipart/form-data">
    <h2>Title</h2>
    <input class="formitem" type="text" name="title"/>
    <br/><br/>
    <h2>Content</h2>
    <textarea class="formitem" name ="textentry" rows="3"></textarea>
    <input type="hidden" name="submitted" value="1">
    <br/><br/>
    <input type="submit" value="Submit"/>
</form>  

Now that we’ve laid out and styled up our page, it’s time to come in with some PHP.

The PHP and Validation

First we’ll use the hidden field (“submitted”) that we created earlier to check if the form is ready to be validated aka if they submitted it. We can do this with a simple IF statement, checking to see if submitted has a value of “1″, which it it automatically set to on form submission. This prevents error messages from popping up unless the form was actually completed and turned in.
<?php
//If form was submitted
if ($_POST['submitted']==1) {
   //Do something
}
?>
Next up we have to check each mandatory field for a value of some kind. I have decided that both the title and content fields are mandatory for this example. The below code checks for values in each field on the form and assigns them to a variable if they exist.
<?php
//If form was submitted
if ($_POST['submitted']==1) {
    if ($_POST[title]){
        $title = $_POST[title]; //If title was entered
    }
    if ($_POST[textentry]){
        $textentry = $_POST[textentry]; //If comment was entered
    }
}  
Now that we have put the values retrieved from the form into variables, we can perform a check to see if any are blank. If they have all been filled out properly, a message alerts them they completed the form properly.
//If all fields present
if ($title && $textentry){
    //Do something
    echo "<div class=\"box green\">Form completed!</div>";
}
?>  
Now for those of you that are currently questioning why I didn’t combine the last two parts into one big IF statement, hold on, it’s error message time.

At this point in the game, we want to go back to where we first assigned the $_POST variables to strings variables, appending an else to each IF statement.
if ($_POST['submitted']==1) {
    $errormsg = ""//Initialize errors
    if ($_POST[title]){
        $title = $_POST[title]; //If title was entered
    }
    else{
        $errormsg = "Please enter title";
    }
    if ($_POST[textentry]){
        $textentry = $_POST[textentry]; //If comment was entered
    }
    else{
         ($errormsg){ //If there is already an error, add next error
            $errormsg = $errormsg . " & content";
        }else{
            $errormsg = "Please enter content";
        }
    }
}  
That last section might have seemed like a lot, so let’s break it down.
First off we established the variable $errormsg, which will contain a string with all the errors we come across.
$errormsg = ""//Initialize errors  
Next we append the first IF statement for the title field, stating that if there is no value, set the  

$errormsg to store that error.
else{
    $errormsg = "Please enter title";
}  
When we check the next field, textentry, we will essentially be doing the same thing, although this time we must check if $errormsg has any errors stored from the previous IF. Should this be the case, we must append our current error message to the previous one.
else{
    if ($errormsg){ //If there is already an error, add next error
         $errormsg = $errormsg . " & content";
    }else{
         $errormsg = "Please enter content";
    }
}  
At this point your $errormsg variable should have an accurate list of error messages stored. Now it is time to alert the user of any problems.
if ($errormsg){ //If any errors display them
    echo "<div class=\"box red\">$errormsg</div>";
}  
And that’s it. You’ve created a basic form validation/alert system, good work. There are a number of other tweaks that can be added to a form validation script, so be sure to stay tuned for Part 2.




 

Sunday, August 12, 2012

Make WAMPServer Run Automatically on System Start-up

 As with all web developers, it’s always important to test your projects locally before putting it out there for the entire web community to see. One must-have developer tool for this purpose is WAMPServer. We’ve all wished it’s automatically up and running when we need it. These easy steps will help you automate WAMPServer to run on system start-up.

For those unfamiliar with WAMPServer, it is a development package that lets you run web development projects locally. WAMP stands for Windows, Apache, MySQL, PHP/Perl/Python. It’s basically four programs packaged to work as one. WAMP basically turns any Windows PC into a localized web server. The Linux counterpart is called LAMP, obviously.

Once WAMPServer is installed in your PC, you’ll be able to test your web projects before putting it into the live environment. But I always found it a hassle to manually start the service every time I need it. With these easy steps, you’ll never have to manually start WAMPServer ever again.

   From All Programs, go to the Accessories folder and select Run. A shortcut for this is Windows Key + R.

   Type services.msc and click OK. This will open the Services Management Console.
   
   In Services Management Console, look for ‘wampapache‘. The Startup Type will be set to ‘Manual’ and so we’ll need to change this to ‘Automatic‘. Right-click on it and select ‘Properties’.

    In the properties window, select ‘Automatic‘ for ‘Startup Type‘. Then, click on ‘Apply‘ and then close the property window. We’ve just set the Apache side of WAMP to run automatically on startup.

   
   Still in Services Management Console, look for ‘wampmysqld‘. We’ll also set this to automatic, so right-click on it and select ‘Properties‘.

   
    Select ‘Automatic‘ for ‘Startup Type’. Click on ‘Apply’ and then close the Properties and Services Management Console.
  
   Restart your machine/PC.
   After the restart, log back in and open a browser. Type localhost (127.0.0.1) in the address bar. localhost is the address for the local installation of WAMPServer in your PC. If the Server Configuration page for WAMPServer loads – Congratulations, you’ve just successfully automated your WAMPServer startup.