Tuesday, 21 June 2011

Lesson 13 : PHP state management and Login Logout.

Retweet this button on every post blogger
Just because HTTP is a stateless protocol it does not remember what user has done last time or a last minute   we have to manually manage our state while communicating with the server, state management is a good topic  and it includes some core PHP basics such as Session state management , Query string, cookies and Databases.

Managing states in PHP :
.
PHP Cookies :-
Cookies are small piece of information that stored at the client side for later reference .
Some basic function of cookies are storing user name and a encrypted password at the client side when a user
click on the remember me check box, or when a website wants to track their user,.

PHP syntax for cookies are :

(PHP 4, PHP 5)
setcookie — Send a cookie
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [,bool $secure = false [, bool $httponly = false ]]]]]] )


Tips :-
1. A cookie  must be set before ant output is sent to the browser, this is the same condition as for header including <html><head> tag and ant whitespace. 

An example of using cookies :
<?php
//this file is included
if(isset($_POST['set']))
{
    if ( setcookie("name","developer",time()+30) ) //thirty seconds expiry time
    echo "Cookie has been set successfully!";
    else
   echo "FAIL";
}
?>
<html>
<head><title>PHP cookies.</title></head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?> method="post" >
<table>
<tr><td>Name</td><input type="text" name="name" /></tr>
<tr><td>&nbsp;</td><input type="submit" name="set" value="setcookie" /></tr>
</table>
</form>
</body>
</html> 


save this as name anyname.php


Now retrieving value from a cookie : -
Once the cookie has been set it have to retrieved on the next page for that purpose we use $_COOKIE superglobal array it is  An associative array of variables passed to the current script via HTTP Cookies. 
An example for $_COOKIE :- 
<?php
     echo "Getting value the saved cookie";
    $value = $_COOKIE['name'];
   echo "<br/>";
  echo  "Cookie value is : " .$value;
?>


save this page to anyname.php

Thursday, 16 June 2011

Lesson 12 PHP file download Script

Retweet this button on every post blogger
File download in PHP is quite easy we have to just scan our directory from which we want to download files
this procedure could be understand more easily by this example;

here we assume that the folder(directory) we want to download file is uploaded_files/ ,


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>File download in PHP</title>
</head>

<body>
<h1>PHP file download.</h1>
<table cellpadding="5" cellspacing="5">
<thead><th>File</th><th>Download</th></thead>
<?php
$path = "uploaded_files/"; // the path for the folder.
if (file_exists($path))
 {
    $files = scandir($path);
for($i=2; $i<sizeof($files); $i++)
{
  ?>
  <tr><td><?php echo $files[$i] ?></td><td><a href="<?php echo $path.$files[$i]; ?>"><img src="dl.gif" /></a></td></tr>
  <?php
 }
}
?>
</table>
</body>
</html>
This script simply output a table with file name and download image.

Monday, 13 June 2011

Lesson 11PHP file upload.

Retweet this button on every post blogger
File upload to server computer is a very task to do in PHP to see how it happens lets see a example.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>File upload using PHP</title>
</head>
<?php
if(isset($_POST['submit']))
{
     if(isset($_FILES['upload']['name']))
{
    echo "<b>Attributes of file upload:</b><br/>";
echo "<b>File name:</b>" .$_FILES['upload']['name'];
echo "<br/><b>File type:</b>" .$_FILES['upload']['type'];
echo "<br/><b>File Size:</b>" .$_FILES['upload']['size']."bytes";
echo "<br/><b>File Temp:</b>" .$_FILES['upload']['tmp_name'];
echo "<br/><b>File error:</b>" .$_FILES['upload']['error'];

$path1 = $_FILES['upload']['tmp_name'];
$path2 = "uploaded_files/".$_FILES['upload']['name'];
if($_FILES['upload']['type']=="image/pjpeg" || $_FILES['upload']['type']=="image/gif" || $_FILES['upload']['type']=="text/plain" || $_FILES['upload']['type']=="application/x-php"  || $_FILES['upload']['type']=="application/msword")
{
move_uploaded_file($path1,$path2);
echo "<br/>file uploaded to server.";
}
else
echo "<br/><b>select only jpeg,gif,text or  php files to upload.</b>";
}
else
echo "No file choosed.";

}

?>
<body>
<form name="form" method="post"  action="<?php echo $_SERVER['PHP_SELF'];?>" enctype="multipart/form-data">
<h1>File upload using PHP</h1>
<center>
<table>
<tr>
<td>Choose file</td><td><input type="file" name="upload"  /></td>
</tr>

<tr><td>&nbsp;</td><td><input type="submit" name="submit" value="upload"  /></td></tr>
</table>

</center>
</form>
</body>
</html>
 1.Where uploaded file folder created at the server holds the user uploaded files.
2.To upload a file the HTML input type must be "file"
3. form enctype="multipart/form-data" must be set that shows that form data must be send as MIME file encoded as binary file.
4. Uploaded file parameters  should use $_FILE global array  to retrieve different file abstract
5. There are five different parameters associated with it. these are ,
    file name
   file type
  file size
 file tmp_name which is temporary storage of file uploaded to server.
file error.

what we to do simply move our file from temporary storage to path  specified by the developer.

Lesson 10 file system using PHP.

Retweet this button on every post blogger
The task is to input a drive name ,folder name , file name, file contents and file extension from the user and save it into the server hard drive.we will learn some php file handling function here.
Program :
<?php
/*php  file system scipt */
if(isset($_POST['submit'])) {
   $errors=''; //an null string
   if ($_POST['folder']=="") {
   $errors.= "<li>Please give a folder name</li>";
    }
 
    if ($_POST['file]=="") {
   $errors.= "<li>Please give a file name</li>";
    }
 
    if ($_POST['text]=="") {
   $errors.= "<li>Please give a file contents</li>";
    }
 
 
   if ($errors=='') {
   $path = $_POST['drive']."/".$_POST['folder'];
   if  (!file_eixsts( $path)) {
   mkdir($path);
   }
  $file_path = $path."/".$_POST['file'].$_POST['ext'];


    if  (!file_eixsts( $file_path)) {
    $fp = fopen($path,"w");  //opening file in write mode at the given path and return a pointer to it.
    fwrite($fp,$_POST['text']); // writing file to directory
   fclose($fp);
   echo "Your file has benn saved.";
   echo "<br/>";
    }


   else
   echo "file exists already, try again";
}
else
echo "<ul>".$errors."</ul>";


?>


<html>
<head>
<title>PHP file handling</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" name="form"><
<center>
<table>
<tr>
<td>Drive name</td><td><select name="drive">
<option name="c:\">C:\</option>
<option name="d:\">D:\</option>
</select></td>
</tr>

<tr>
<td>Folder name</td><td><input type="text" name="folder" /></td>
</tr>


<tr>
<td>File name</td><td><input type="text" name="file" /></td>
</tr>


<tr>
<td>File contents</td><td><textarea name="text" cols="4" rows="15"></textarea></td>
</tr>


<tr>
<td>File type</td><td><select name="ext">
<option name=".txt">*.txt</option>
<option name=".html">*.html</option>
<option name=".ppt">*.ppt</option>
<option name=".doc">*.doc</option>

</select></td>
</tr>


<tr>
<td>&nbsp;</td><td><input type="submit" name="submit" value="save" /></td>
</tr>
</table>
</center>
</form>
</body>
</html>

Friday, 10 June 2011

Lesson 9 : Post back in PHP

Retweet this button on every post blogger
The method of page post back is quite  easy concept it trip back  on the page on which our code has been placed or in another terms we can say page call itself  for further operation.
Simple example of PHP post back : 
<?php
/*
php code for handling post back.
*/
if(isset($_POST['submit']))
{
    $first = $_POST['fname'];
    $last = $_POST['lname'];
   echo "Full nmae : ".$first." ".$last;
}

?>

<html>
<head><title>Handling post back in PHP</title></head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?> " method="post" name="form">
<center>
<table>
<tr>
<td>first name</td><td><input type="text" name="fname" /></td>
<tr><td>last  name</td><td><input type="text" name="lname" /></td></tr>
<tr><td>&nbsp;</td><td><input type="submit" name="submit" value="go.."</td></tr>
</tr>
</table>
</center>
,</form>
</body>
</html >

 this simple program defining PHP post back as by checking in the starting of the program for posted array variable submit if it got it setted then the further script will  execute .

Another simple example on PHP post back with checkbox input : 
<?php
if(isset($_POST['submit']))
{
    $firstdigit = $_POST['fdigit'];
   $lastdigit = $_POST['ldigit'];
 
  if(isset($_POST['add']))
  {
        $sum =  $firstdigit + $lastdigit ;
  }
 
   if(isset($_POST['mul']))
  {
        $multi =  $firstdigit * $lastdigit ;
  }  
  

}


?>


<html>
<head>
<title>PHP post back</title>
</head>
<body>
<table>
<tr>
<td>First digit</td><td><input type="text" name="fdigit" /></td>
</tr>
<tr>
<td>Second digit</td><td><input type="text" name="sdigit" /></td>
</tr>
<tr>
<td>&nbsp;</td><td>Add<input type="checkbox" name="add" <?php if(isset($_POST['add'])) echo "checked"; ?> />Multiply<input type="checkbox" name="mul" <?php if(isset($_POST['mul'])) echo "checked"; ?> /></td>
</tr>
<tr><td>&nbsp;</td><td><input type="submit" name="submit" value="process" /></td></tr>

<tr>
<td>Results</td>
<td>&nbsp;</td>
</tr>



<tr>
<td>Addition</td>
<td><?php if(isset($sum)) echo $sum; ?></td>
</tr>


<tr>
<td>Multipliaction</td>
<td><?php if(isset($multi)) echo $multi; ?></td>
</tr>


</table>
</body>
</html>

Thursday, 2 June 2011

Lesson 8 : PHP form handling

Retweet this button on every post blogger
Sending form data from one page to another for further processing in an quite simple task in PHP, By setting up only form input type name attribute we can extract them at the server side using PHP global array.
Some example global  array in PHP which we often use in form handling are :

$_POST[]
$_GET[]
$_SERVER[]
$_REQUEST[]
$_COOKIE[]

The global arrays are all associative arrays. This means the value is associated with a name that is the index key for the contents and, sensibly, describes what the value represents. For instance,$_SERVER["SCRIPT_NAME"] contains the URL path to the current page.

Sometimes you can also access the values of the array directly by variable name. This varialbe name is the same as the index key for the array. Thus, the variable name for $_SERVER["SCRIPT_NAME"] would be$SCRIPT_NAME. this can be achieve by extracting the array. 

I think this is enough for any beginner. lets look at the example.
page1.php
<html>
<head><title>PHP from handling.</title></head>
<body>
<form action = "page2.php" method="post">
<center>
<table>
<caption>General info</caption>
<tr>
<td>First Name</td><td><input  type="text" name="fname" /></td>
</tr>
<tr>
<td>Last Name</td><td><input  type="text" name="lname" /></td>
</tr>
<tr>
<td>Address</td><td><input  type="text" name="add" /></td>
</tr>
<tr><td>&nbsp;</td><td><input  type="submit" name="submit"  value="Go.."/></td></tr>

</table>
</center>
</form>
</body>
</html> 
                                                                    --Output--
page2.php
<html>
<head><title>PHP from handling.</title></head>
<body>
<center>
<table>
<caption>General info</caption>
<tr>
<td>First Name</td><td><?php echo $_POST['fname']; ?></td>
</tr>
<tr>
<td>Last Name</td><td><?php echo $_POST['lname']; ?></td>
</tr>
<tr>
<td>Address</td><td><?php echo $_POST['add']; ?></td>
</tr>
</table>
</center>
</body>
</html>   
                                       
                                                                   --Output--
 for sake of simplicity we also extract $_POST[] array as extract($_POST);, and simply use the form input names as POSTED variables in pag2.php.


































Wednesday, 1 June 2011

Lesson 7 include and require

Retweet this button on every post blogger

The include() statement includes and evaluates the specified file.

Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include() will finally check in the calling script's own directory and the current working directory before failing. The include() construct will emit a warning if it cannot find a file; this is different behavior from require(), which will emit a fatal error.

An example :-
vars.php
<?php

$color = 'green';
$fruit = 'apple';

?>

test.php
<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>

require()

require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.


require_once()

The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.

include_once()

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include()statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.