Archive

Archive for the ‘PHP Tutorial’ Category

File Handling in PHP

Comments Off

File handling in PHP is very easy and effective. Not only files, we can open urls also using php’s file functions.

Few important file functions in php are:

  • file();
  • file_get_contents();
  • file_put_contents();
  • fopen();
  • fclose();
  • fread();
  • file_exists();
  • delete();
  • filesize();
  • fwrite();
  • is_dir();
  • is_writable()

A simple program to read a file content;
$fp = fopen("test.txt","r+");
$contents = fread($fp);
flcose($fp);

A simple PHP program to write into a file;

$fp = fopen("test_new.txt","w");
fwrite($fp,$content);
fclose($fp);

PHP Tutorial

PHP Cookie

Comments Off

Cookies are similar to sessions, the main difference is cookie will be maintained in visitor’s browser.

How to set a cookie in PHP?

In php you can use setcookie function to set a cookie. Here is the syntax to set cookie in php.

setcookie(cookiname,cookievalue,expirytime,path);

If you want to set a login user cookie for 2 hours, you can set like:

setcookie(’user’,'value’,time()+2*60*60);

Normally you can store upto 4KB of cookie data in visitor’s browser.

How to destroy a cookie?

you can destroy or clear a cookie by setting a past time as expiry time to that cookie. To destroy the above set cookie, we can use like:

setcookie(’user’,”,time()-100);

PHP Tutorial

Introduction to PHP

Comments Off

PHP stands for “Hypertext Preprocessor” [recursive acronym], a very popular open source server side scripting language allows users to develop rich, effective and scallable web portals and web applications. It was created by “Rasmus Lerdorf”. It can be run under IIS, apache and other popular web servers.

Sites developed using PHP:

  1. feedburner
  2. istockphoto
  3. yousendit
  4. meebo
  5. techcrunch

PHP Tutorial

Installing PHP 5 and apache on windows xp

Comments Off

PHP is best suited for LAMP [Linux, Apache, MySQL and PHP] environment, but we can use in WAMP [Windows, Apache, MySQL and PHP] environment also, here are the options to install & configure php with apache in windows machines.

1] Use WAMP Server or XAMPP server for one click installation, no need for configuration.
2] Manually install and configure apache & php.

The first option is very easy, you can download a windows set up package from their site and can install in a single click.

Here are the steps for installing apache and php manually in a windows machine:


1] Download apache for windows from http://www.apache.org/

2] Install it.

3] Create your document root folder [Which will be accessed like http://localhost/], for example I am going to create this under C drive ie “C:myprojects”

4] Now open the apache http configuration file[httpd.conf]

5] Search for DocumentRoot, replace the old value by “C:myprojects”, Also set <Directory “C:myprojects”>

6] Now save the file and restart the apache web server.

7] Open your browser and type “http://localhost/”, now you can see apache working.

8] Download the latest PHP [Normal package without installer] from http://www.php.net/

9] Extract it under C drive ie, the “C:php”

10] Again open the apache http conf file, and search for “ScriptAlias”, add the following to work php
ScriptAlias /php/ “c:/php/”
11] Then add
AddType application/x-httpd-php .php and Action application/x-httpd-php “/php/php-cgi.exe”
12] Restart apache
13] Create an “index.php” file under “C:myprojects”, with the following code
‘); ?> 14]Open your browser, and type http://localhost, now you can see php is working..

PHP Tutorial

Recursive function in PHP

Comments Off

recursive function is a function that calls itself repeatedly for a specified condition.
Here is an example function which calls itself to perform a tree structure for a category table
Here is the category table:

category_id parent_id category_name
1 0 CMS
2 0 Blogs
3 0 Forums
4 0 E-Commerce
5 1 Joomla
6 1 Mambo
7 6 Templates
8 6 Mods/Components
9 4 OSCommerce
10 2 Wordpress
11 10 Themes
12 10 Plugins
<?php
echo '<select name="category">
<option value="0">Root</option>';

$allcats = getTree();

foreach($allcats as $key=>$value)
{
echo "<option value='$key'>$value</option>";
}
echo '</select>';

foreach($allcats as $key=&gt;$value)
{
echo "$value";
}
echo '

';

function getTree($id=0)
{
static $cates = array();
static $times = 0;
$times++;
$result = mysql_query("SELECT category_id,category_name FROM category_table WHERE parent_id=$id ORDER BY category_name");
while($row = mysql_fetch_assoc($result))
{
$cates[$row['category_id']] = str_repeat("|   ",$times-1)."|___".$row['category_name'];
getTree($row['category_id']);
}
$times---;
return $cates;
}
?>

The out put of this program would be the following select box:

PHP Tutorial

Email validation using PHP regular expression

Comments Off

Regular expression is a wonderful concept, using this we can play with strings in PHP. The practical use of regular expression is:

  • Email validation
  • validating domain name
  • validating post code format etc.

There are two types of regular expression functions:

  1. ereg functions or POSIX extended regular expression function, which is the standard functions for PHP
  2. preg functions or perl Compatible regular expressions

For this email validation program, we are going to use PHP’s standard regular expression function “ereg”.

Before entering the email validation program, its better to refer few basic syntax about regular expression functions.

s -> this means an empty white space
^ -> this means start of a string
$ -> this means end of a string
. -> this means any character
(cat|mat) -> this means cat or mat
[0-9] -> this means all numbers from 0 to 9 inclusive
[a-z] -> this means all lowercase letters from a to z inclusive
[A-Z] -> this means all uppercase letters from A to Z inclusive
[^a-z] -> this means no occurrence of lowercase letters from a to z inclusive, the hat symbol (^) inside the sets denotes “not”
? -> this means zero or one of the proceeding characters
* -> this means zero or more characters
+ -> this means one or more characters
{3} -> this means exactly three characters
{3,} -> this means three or more characters
{3,6} -> this means 3 to 6 characters, it may be 3 or 4 or 5 or 6

Here is the php source code for email validation using php regx function:

<?php
$email
= “myemail@mydomain.com”;

if (ereg(‘^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+.([a-zA-Z]{2,4})$’,$email)
{
echo
‘Valid email id’;
} else {
echo
‘Invalid email id’;
}
?>

Now I am going to split the string pattern into 3 parts, ie

1] ^[a-zA-Z0-9._-]+@
2] [a-zA-Z0-9._-]+.
3] ([a-zA-Z]{2,4})$

1]^[a-zA-Z0-9._-]+@

Here ^ symbol denotes that this is the start of the email part.
a-zA-Z0-9._- denotes combination of characters to form the username section of an email
+ symbol denotes, it should have 1 or more characters from the proceeding sets
@ symbol is a default symbol between username and domain name parts.

2] [a-zA-Z0-9._-]+.
a-zA-Z0-9._- denotes combination of characters to form the domain name without the tld
+ symbol denotes, it should have 1 or more characters from the proceeding sets
. symbol denotes, the dot operator proceeding to the tld, here we are using to escape

3] ([a-zA-Z]{2,4})$

a-zA-Z denotes the combination of chars to form the tld name
{2,4} denotes the length of the tld may be between 2 to 4 characters
$ denotes the end of an email.

PHP Tutorial

PHP Interview Questions and Answers

Comments Off

Question: Is PHP a case sensitive programming language?

Answer: PHP is a partially case sensitive programming language. We can use function names, class names in case insensitive manner.

Question: What is mean by LAMP?

Answer: LAMP means combination of Linux, Apache, MySQL and PHP.

Question: How do you get the user’s ip address in PHP?

Answer: Using the server variable: $_SERVER['REMOTE_ADDR']

Question: What is the difference between require and include?

Answer: When using require function to embed another file in php, it will give fatal error if the file is not exists.
When using include function to embed another file in php, it will give warning if the file is not exists.


Question: How to find the number of elements in an array?

Answer: Using count($array) or sizeof($array).

Question: How do you make one way encryption for your passwords in PHP?

Answer: Using md5 function or sha1 function

Question: How do you get ASCII value of a character?

Answer: By using ord function.

PHP Tutorial

Generating CAPTCHA Image Using PHP

Comments Off

The CAPTCHA concept is very useful to prevent automated registration. If you have enabled gd library, you can create a captcha code for your registration form using PHP.

Consider the following parts of code, name the file as “captcha.php”

session_start();

if(isset($_SESSION['captcha']))
{
unset(
$_SESSION['captcha']);
}

The above code will start session and clear the old captcha’s session value if it set.

$num_chars = 5; //number of characters for captcha image
$characters = array_merge(range(0,9),range(‘A’,‘Z’),range(‘a’,‘z’)); //creating combination of numbers & alphabets
shuffle($characters); //shuffling the characters

The above part of code describes the number of captcha characters and total available characters, here I am using all the lower and upper case alphabets and all numerics.
//getting the required random 5 characters
$captcha_text = “”;
for(
$i=0;$i<$num_chars;$i++)
{
$captcha_text .= $characters[rand(0,count($characters)-1)];
}

$_SESSION['captcha'] = $captcha_text; // assigning the text into session

This part of code generated the required captcha code in a random manner from the available character array, also It assigns the value to session variable.

header(“Content-type: image/png”); // setting the content type as png
$captcha_image = imagecreatetruecolor(140, 30);

$captcha_background = imagecolorallocate($captcha_image, 225, 238, 221); //setting captcha background colour
$captcha_text_colour = imagecolorallocate($captcha_image, 58, 94, 47); //setting cpatcha text colour

imagefilledrectangle($captcha_image, 0, 0, 140, 29, $captcha_background); //creating the rectangle

$font = ‘Arial.ttf’; //setting the font path

imagettftext($captcha_image, 20, 0, 11, 21, $captcha_text_colour, $font, $captcha_text);
imagepng($captcha_image);
imagedestroy($captcha_image);

The remaining code will draw the image.

How to use this captcha?

It’s simple, in your registration form put this part of code:

<img src=”captcha.php”>

Then you can put a text box to enter the captcha value, and then you can compare the entered captcha value with the assigned captcha session value.

PHP Tutorial

File Uploading in PHP

Comments Off

File uploading is very simple in PHP when comparing to other server side programming languages. File uploading is very useful in most of the situations like uploading user’s photos, uploading csv reports, uploading pdf reports and so on.

Making a simple front end with file browsing box:

<form enctype="multipart/form-data" method="post">
Upload a file
<input name="my_file" type="file" />
<input type="submit" value="Upload" />
</form>

Note: You should have this enctype=”multipart/form-data”‘ in your form tag while uploading files.
The php source code to upload the files

if(isset($_FILES['my_file']['name']) && $_FILES['my_file']['name'] != '')
{
$upload_dir = 'home/myaccount/public_html/images';//uploading directory, this folder should have write permission to the current user
$upload_file = $upload_dir.'/'.basename($_FILES['my_file']['name']);

  //check if the file name already exists
   if(file_exists($upload_file))
     {
     echo "File Already Exists"; //if file already exists print the error message
     }
     else
     {
          if(move_uploaded_file($_FILES['my_file']['tmp_name'],$upload_file))
             {
             echo "File Uploaded";
             }
            else
            {
            echo "There was a problem to upload file";
            }
     }
}
?>

PHP Tutorial

Using session in PHP

Comments Off

Keeping in mind the fact that Internet is a stateless platform and every request for a web page is treated as unique, there is a serious need of a tool to maintain the state. Otherwise, it will be a messy situation to keep track of requests made by a particular user. The good news is that use of PHP session serves the solution to this problem. This session variable is of great importance for web applications like shopping carts and is considered as equivalent to cookies, other significant way of maintaining the state.

What Is PHP Session Capable Of

PHP session is capable of storing the information in the form of session variables, in order to handle the ever-increasing traffic on a website. For instance, consider a shopping website, with products scattered in different categories and different pages. In such a situation, a user may switch from one page t another and keep on adding products from different pages to his or her shopping cart.

Thus, in order to keep the track of a particular user on the shopping website, PHP sessions store user information and use it again and again. This is a powerful entity to serve the purpose for websites with huge customer base.

Getting Started With PHP Session

PHP session is initiated using following piece of code:

session_start();?>

Now, suppose you visit a website in regular intervals in a specific period of time. The website must not treat you like a new user on every visit of yours. Rather, it must take the advantage of session variable to assign a user value to your first visit and use it again and again for every visit paid by you. Thus, we can add following code to accomplish this task:

session_start();$_SESSION['counter']++;

echo "Welcome Back! You have viewed this page " . $_SESSION['counter'] . " times";

?>

Thus, if you revert to a particular website in short period of time, the counter will be incremented. If you visit the website 5th time, you might see it written somewhere that “Welcome Back! You have viewed this page 5 times”.

How Does It Work

Whenever you visit a web page, the PHP session sets information on your computer in the form of a cookie. It is generally a random key, formed by alphabets and numbers. In case, you visit another webpage of same website, the session explores the computer for a previously generated key. In case a match is found, that particular session is utilized. Otherwise, a new session is created with whole procedure related.

How To End A PHP Session

A session is destroyed with the help of following code:

session_destroy();

?>

It is a matter of fact that a session exists until and unless the associated user closes the browser used to open the website. Once the browser window is shut down, the session is destroyed. You may also decide the life of a session by bringing in following modifications in php.ini file.

session.cookie_lifetime = 0

You may change the value from zero to number of seconds you want a session to live.

You may also destroy a session variable using unset() or all session variable using session_unset().

PHP Tutorial