Thursday, January 9, 2014

Creating Simple and Beautiful buttons with CSS

The following is the CSS code to style links as buttons with rounded corners and shadow effect:

.button{
display: inline-block;
font-family:  Verdana, Geneva, sans-serif;
        font-size: 11px;
padding: 5px 10px 6px;


        width: 60px;
color: #fff;
text-decoration: none;
font-weight: bold;
line-height: 1;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
position: relative;
cursor: pointer;
-moz-box-shadow: 0 1px 3px rgba(0,0,0,0.5);
-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.5);
text-shadow: 0 -1px 1px rgba(0,0,0,0.25);
border-bottom: 1px solid rgba(0,0,0,0.25);
text-align:center;
}

The above CSS snippet will make the link look like a button with rounded corners and now we will add CSS to make buttons of different sizes.

.small_button {
     font-size: 11px;
     width:60px;
     line-height:15px;
}
.medium_button {
    font-size: 13px;
    width:80px;
    line-height:18px;
}
.large.awesome {
   font-size: 14px; 
   width:130px;
   line-height:24px;
}

The following is the CSS to create different color buttons
.blue {
      background-color: #2daebf;
}
.red {
     background-color: #e33100;
}
.magenta {
     background-color: #a9014b;
}
.orange {
    background-color: #ff5c00;
}
.yellow {
    background-color: #ffb515;
}

The following is the HTML code to create buttons using the above styles:

<a href="#" class="button red">Button</a>
<a href="#" class="button blue medium_button">Button</a>
<a href="#" class="button orange large_button">Button</a>
<a href="#" class="button yellow">Button</a>
<a href="#" class="button magenta">Button</a>


Saturday, January 4, 2014

Creating RSS Feed in PHP

RSS (Rich Site Summary), also known as Really Simple Syndication is used to publish frequently updated information in standard format. It an easy way to make the content available to various platforms. It is therefore useful to have RSS feeds for our website. In this tutorial, we will learn how to generate RSS feeds of our website’s content through PHP.

The following is the is the RSS feed structure:

<?xml version="1.0" encoding="ISO-8859-1" ?>
    <rss version="2.0">
        <channel>
            <title></title>
            <link></link>
            <description></description>
            <language></language>
            <item>
                <title></title>
                <link></link>
                <description></description>
            </item>
        </channel>
    </rss>

Now we will write a PHP program to extract data from the MySQL database and generate RSS feed.

<?php

//Function to remove unwanted characters from the string.
function clean_input($input) {
    $search = array(
        '@<script[^>]*?>.*?</script>@si',   /* Remove javascript */
        '@<[\/\!]*?[^<>]*?>@si',            /* Remove HTML tags */
        '@<style[^>]*?>.*?</style>@siU',    /* Remove style tags */
        '@<![\s\S]*?--[ \t\n\r]*>@'         /* Remove multi-line comments */
    );

    $output = preg_replace($search, '', $input);
    return $output;
?>

<?xml version="1.0" encoding="ISO-8859-1" ?>
    <rss version="2.0">
        <channel>
            <title>WEBSITE_TITLE</title>
            <link>WEBSITE_LINK</link>
            <description>DESCRIPTION_TEXT</description>
            <language>LANGUAGE_USED</language>
<?php

            $query = 'SELECT * FROM `content` ORDER BY `id` DESC';
            $rs = mysql_query($query);
               
          while($row = mysql_fetch_assoc($rs)) {
                    $post_title = clean_input($row['title']);
                   $url = clean_input($row['url']); 
    $description = clean_input($row['short_description']);

                    # Putting in the blog posts information for the user.
                    echo '<item>';
                    echo '<title>'.$post_title.'</title>';
                    echo '<link>'.$url.'</link>';
                    echo '<description><![CDATA['.$description.']]></description>';
                    echo '</item>';
                }
            }

?>
        </channel>
    </rss>


The above code gets the content from the MySQL database and displays it in RSS format.

Saturday, December 28, 2013

Using JSON in PHP

JSON (JavaScript Object Notation) is a standard format used to transmit data between a server and a web application. It is an alternative to XML. JSON string is a human-readable text consisting of attribute-value pairs. JSON is a language-independent data format and many languages support generating and parsing JSON data.

The following is the format of the JSON string:
{
                “first_name” : “Barack”,
                “last_name” : “Obama”,
                “address” :{
                                “city” : “Washington, DC”,
                                “country” : “United States of America”
},
“phone_numbers” : [
{
                “type” : ”home”,
                “number” : ”000 000-0000”
},
{
                “type” : ”office”,
                “number” : ”000 000-1111”
}
                ]
}

PHP 5.2.0 supports JSON by default and we do not need any additional installation and configuration to use JSON. If the PHP version is less than 5.2.0, we need to install JSON PECL extension and guide for installation of PECL extensions can be found at the official PHP website php.net.
There are three functions in PHP to support JSON. They are json_encode, json_decode, and json_last_error. json_decode function converts JSON string into PHP variable to use that data for further programming.  If the JSON string cannot be decoded then null will be returned.

PHP json_encode() function coverts a PHP value into a JSON string. For example, from a PHP array, it can create a JSON representation of that array.

The following is the simple PHP script that uses JSON:
<?php
//Array creation
$arr=array('PHP','MySQL','Javascript');
//Encoding the array to JSON string
$json=json_encode($arr);
echo $json;
//Decoding the JSON string back to array.
$decode=json_decode($json);
echo "<br>";
echo $decode[0];

?>

Friday, December 27, 2013

Inline vs Block elements in CSS

Most of the HTML elements have default value for display property in CSS as block or inline

The elements with default value of display property as block include <div>, <p>, <h1> to <h6>, <form> etc. The elements with this display type have the following characteristics:
  • Height, line-height, and top and bottom margins can be changed.
  • Always begin on a new line.
  • Width is 100% unless a width is specified.

The elements with default value of display property as inline include <span>, <a>, <img>, <input> etc. The elements with this display type have the following characteristics:
  • Height, line-height and top and bottom margins cannot be changed. 
  • Begin on the same line 
  • Width is based on the text/image and it cannot be changed.

The characteristics mentioned above of an element can be  changed by setting the CSS property of the element as display: inline or display: block. By changing this property value we can do achieve many options like:
  • Have a block element start on the same line 
  • Have an inline element start on a new line 
  • Change the width and height of an inline element. 

The following is the sample CSS code to make a link look like a button with 100px width:
 
a{
color:white;
text-decoration:none;
background:#00f;
padding:10px;
width:100px;
margin:10px;
text-align:center;
display:block;
}

If we remove the display:block property from the above code, the width and margin of the link cannot be modified.

Monday, December 23, 2013

Storing passwords safely in database using PHP and MySQL

Passwords of the users registered with our site should be stored as plain text, because if someone gets access to the database he will be getting the passwords of all the users.  Many people use the same password for different websites and therefore those accounts will be compromised as well. Therefore we need use some type of encryption to store passwords in the database.

Simple encryption algorithms are reversible and therefore if we use simple encryption technique to encrypt the password, the original password can be generated from the encrypted one.

Cryptographic hashing functions such as MD5 are irreversible, which makes it difficult to get the original password from the encrypted one. To validate the use at login we need to again encrypt the user entered password with MD5 and compare it with the password stored in the database at the time of user registration. The following is the code to hash the password with MD5.

<?php
$password = 'mypassword';
$hash = md5($password);
?>

It is impossible to retrieve the original password from the hashed passowd. If a user forgets his password, we need to simply generate a new one.

It is quite possible for someone to make a list of millions of hashed passwords (rainbow table) and compare the hashes to find the original passwords. Therefore the intruder can  find the original password if we use MD5. The same applies for other hashing functions like SHA-1. This hashes are also prone to brute forcing (trying out all combinations with an automated script). 

We can use a salt to encrypt the password. A salt is a string that is hashed together with the password and therefore one cannot get the original password by comparing the hashed password with the rainbow tables. The following is the code to hash the password using a salt.

<?php
$password = 'mypassword';
$salt = '12345';
$hash = md5($salt . $password);
?>

To validate the use on login we have to hash the user entered password using the same salt and compare it with password stored in the database.

Some additional tips to secure user accounts passwords are:

Limit the number of failed login attempts.
Minimum length of the password should be at least 8 characters or more.

Allow or even make mandatory to use special characters in passwords.

Friday, December 20, 2013

Sending Email through PHP

Sending email though PHP is very easy using the PHP function mail(). But we have to append the email headers for adding options like adding CC (carbon copy) and BCC (Behind Carbon Copy). The following is the code to send Email with different options.

<?php 
//Message to be send
$message = "Hi, This is a sample mail send through PHP using additional headers .";
//Subject of the message
$subject = "Test mail";

//Adding from email ID. This is required.
$headers = "From: $from\r\n";

//If the email has HTML content the following lines needs to be added to header. This is optional.
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

//If the email has different reply to email other than the from email ID.  This is optional.
$headers .= "Reply-To: $replyto\r\n";

//To send a CC of this email to another email ID. This is optional. If we want to send CC to more than one email ID, we have to add multiple email ids separated by after Cc:
$headers .= "Cc: $cc_mailid \r\n";

//To send a BCC of this email to another email ID. This is optional. If we want to send BCC to more than one email ID, we have to add multiple email ids separated by after Bcc:
$headers .= "Bcc: $bcc_mailid \r\n";

//Finally, to the send the email with the above options.
If  (mail($to, $subject, $message, $headers)
                echo "Email send successfully.";
else
                echo "There was an error while send the email.";
?>

Note: The above program will only work if your server is properly configured for e-mail.  Therefore this program may not work in your local installation. Some web servers may have the email server hosted on another machine.


Thursday, December 19, 2013

Getting content from a webpage in PHP using CURL

We can get content from a website in PHP using PHP function file_get_contents(). Below is the sample code to display the content from a website.

<?php
$content=file_get_contents('http://www.example.com');
echo $content;
?>

But some website does not allow accessing their content by anything other than web browser. Such websites block the program that is trying to access their content by checking for a User Agent string, which is sent by all browsers to websites they visit. Therefore to access this type of websites, we have to write a program that simulates being a browser. In this tutorial we will learn how to write a program that fetches the content of a web page simulating like a browser.  For this program, we use the Mod CURL (Client URL) library extension to PHP.  It only works when this extension is enabled in our server or PHP installation.

The following is an example User Agent string:
Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201
For more information and list of User Agent string you can visit www.useragentstring.com

The following is the code to get content from a website using CURL:

<?php
$url='http://www.example.org';
$user_agent='Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201';

$curl=curl_init(); //Open a session using CURL

//Setting options for CURL
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_FAILONERROR, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 8);
curl_setopt($curl, CURLOPT_TIMEOUT, 8);

$content=curl_exec($curl); //Executing the CURL
curl_close($curl); //Close session

echo $content;
?>

Note: Some websites only allow browsers to access their web pages because other programs are not permitted to access it. So please check whether you are allowed to access the content of a website before using this code to access that website.