Sunday, 13 November 2011

PHP with Mysql

Retweet this button on every post blogger
Mysql is the world's most popular open source database System ,with its superior speed, reliability, and ease of use, MySQL has become the preferred choice for Web, Web 2.0 today's millions  database based applications runs on mysql for their data storage needs, learning mysql is relatively easy and has a several advantage over other paid RDBMS software's.


PHP provide a large base of its function repository for handling mysql operation efficiently. these functions allow you to access MySQL database servers.

The structure of PHP and Mysql connectivity.
 
 As you can determine from the above diagram there is three boxes


  1. One is a client is running  a web Browser and making request to web server.
  2. Second is a Web server that handle clients request and make Appropriate request to Web Database software running at the extreme end of the structure it stores all the data. 
you can learn more about Mysql and can see its documentation at Mysql Reference .

If you have installed WAMP or XAMPP Bundle on your Ssystem Mysql comes with that automatically.

Five Important commands of MySQL.
  1. mysql_connect("host_name","User","Password") 
        this PHP function open's a MySQL Connection With the three parameters  passed  called.         host_name : - The name of host on which your server is running .
        user_name :- user name of the Database.
         password: - password of the database.

     2. mysql_select _db("db_name",resource link);
         Select the database with the provide resource returned by the mysql_connect() call, by                          default connect with the last opened coonection.
   
    3. mysql_query("Query",resource link)
        sends a unique query (multiple queries are not supported) to the currently active database on the     server      that's associated with the specified link_identifier.
   
    4. mysql_fetch_array(resource $result, $result_type)
        Fetch a result row as an associative array, a numeric array, or both
    5.  mysql_num_rows( resource $result )
         Get number of rows in result.retrieves the number of rows from a result set. This command is only         valid for statements like SELECT or SHOW that return an actual result set.



Saturday, 25 June 2011

Lesson 15 : PHP Query String.

Retweet this button on every post blogger
Query string is usual part of any website it sits in the URL bar and associated with  website URL for navigation to the different sections of the website. use of query string to send data of one page to others.
Example of query string;
index.php?page=user&role=admin


The query string always starts with Question mark (?) and separates two variables with address operator(&).

Example program  of Query string  :-
page page1.php
<?php
if ( isset ( $_POST['submit'] ) )
{
     $url = "nextpage.php?fname=".$_POST['fname']."&lname=".$_POST['lname']."&fdigit=".$_POST['fdigit']."&sdigit=".$_POST['sdigit'];
header("Location:$url");
}


?>


<html>
<head><title>PHP Query String.</title></head>
<body>
<center>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<table cellpadding="0" cellspacing="0">
<tr><td>Firt 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>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><input type="submit" name="submit" value="Go.." /></td></tr>
</table>
</form>
</center>
</body>
</html>


This program contains nothing the whole magic at the nextpage.php  


Page nextpage.php


<html>
<head><title>Next page</title></head>
<body>
<center>
<table cellpadding="0" cellspacing="0">
<tr><td>Firt name</td><td><?php echo $_GET['fname'];?></tr>
<tr><td>Last name</td><td><?php echo $_GET['lname'];?></td></tr>
<tr><td>First digit</td><td><?php echo $_GET['fdigit'];?></td></tr>
<tr><td>Last digit</td><td><?php echo $_GET['sdigit'];?></td></tr>
<?php

$sum  = $_GET['fdigit']+$_GET['sdigit'];
?>
<tr><td>Sum:</td><td><?php if ( isset ( $sum ) ) echo $sum; ?></td></tr>

</table>
</center>

</body>
</html>
There are two option to get value from a query string $_GET and $_REQUEST these both are PHP globals array.
The major drawback with Query string  that they can be manipulate while running.
TIP :- NEVER SEND SENSITIVE DATA USING QUERY STRING BECAUSE ITS SHOWS WHAT IS CONTAINS.   

Wednesday, 22 June 2011

Lesson 14 : PHP Script for Login & Louout.

Retweet this button on every post blogger
Login-Logout is a very basic mechanism for authenticate a user   User of your website or application. this mechanism always implemented using PHP session  variable.

$_SESSION is an associative array containing session variables available to the current script.
for registering a session variable we must have to start_session.
About session_start():-

Syntax : -

bool session_start ( void )

Returns TRUE if a session successfully started otherwise FALSE.
1. session_start — Initialize session data.
2. session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
3When session.use_trans_sid is enabled, the session_start() function will register an internal output handler for URL rewriting.

PHP script for login logout :-

Example page index.php 

<?php
session_start();
if(isset($_POST['submit']))
{
$_SESSION['user'] = "user";
}
?>
<!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=utf-8" />
<title>log in page.</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<?php
if(isset($_SESSION['user']) && $_SESSION['user']!="")
{
header("Location: login.php");
}
?>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<center>
<div>
<fieldset style="width:300px;">
<legend>Login</legend>
<label id="userid"><input type="text" id="userid" name="userid"  /></label>
<label id="passwd"><input type="text" id="passwd" name="passwd"  /></label>
<input type="submit" name="submit" value="go" />
</fieldset>
</div>
</center>
</form>
</body>
</html>

Example page login.php

<?php
session_start();
if(!isset($_SESSION['user']))
header("Location: index.php");
else
echo "Congratulation you are logged in!!";
?>
<a href="logout.php" >Logout</a>

Example page logout.php

<?php
session_start();
unset($_SESSION['user']);
header("Location: index.php");
exit;
?>

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>