Thursday, May 31, 2012

simple counter php




simple counter php


Make a folder named as "digits" in your web root in side the digit folder make another folder named as "1". Then you have to design images for numbers(0-9) by using image processing software as follows.


Name above images as 1,gif,2gif...............9.gif and incert into folder "1 " you created.Next you have to make empty text file called hits where visitors number of hits are storing.

Create below php file and run you can see the count of visitors hit.

<?PHP

$counterstyle = "images";  
$imagetype = "1";          

$hitslog = "hits.txt";    
$imagefolder = "digits";   

$hits = file($hitslog);
$hits = $hits[0] + 1;


$fp = fopen($hitslog, "w");
fwrite($fp, $hits);


if ($counterstyle == "text") { print $hits; }


if ($counterstyle == "images") {
 $digit = strval($hits);
 for ($i = 0; $i < strlen($hits); $i++) {
print "<img src=\"$imagefolder/$imagetype/$digit[$i].gif\">";
                }
        }

?>

Users online php

Users online php

You have created my_database in your previous lessens.Now you have to create table called "useronline" in your my_database using following fields.

CREATE TABLE `useronline` (
  `id` int(10) NOT NULL auto_increment,
  `ip` varchar(15) NOT NULL default '',
  `timestamp` varchar(15) NOT NULL default '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id`(`id`)
) TYPE=MyISAM COMMENT='' AUTO_INCREMENT=1 ;

This page shows the number of users online

 <?php
 include_once ("usersOnline.php");
$visitors_online = new usersOnline();

if (count($visitors_online->error) == 0) {

    if ($visitors_online->count_users() == 1) {
        echo "<table bgcolor=#515fb0><tr bgcolor=#ffffff><td>There is " . $visitors_online->count_users() . " visitor online</td></tr></table>";
    }
    else {
        echo "<table bgcolor=#515fb0><tr bgcolor=#ffffff><td>There are " . $visitors_online->count_users() . " visitors online</td></tr></table>";
    }
}
else {
    echo "<b>Users online class errors:</b><br /><ul>\r\n";
    for ($i = 0; $i < count($visitors_online->error); $i ++ ) {
        echo "<table bgcolor=#515fb0><tr bgcolor=#ffffff><td>" . $visitors_online->error[$i] . "visitor online</td></tr></table>";
    }
}
?>

Bellow shows you usersOnline.php which connect with your data base and insert the user details.

<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "my_database";
$conn = mysql_connect("$host","$user","$pass") or die ("Unable to connect to database.");
mysql_select_db("$db", $conn);
class usersOnline {

    var $timeout = 600;
    var $count = 0;
    var $error;
    var $i = 0;
   
    function usersOnline () {
        $this->timestamp = time();
        $this->ip = $this->ipCheck();
        $this->new_user();
        $this->delete_user();
        $this->count_users();
    }
   
    function ipCheck() {
   
        if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        }
        elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_X_FORWARDED')) {
            $ip = getenv('HTTP_X_FORWARDED');
        }
        elseif (getenv('HTTP_FORWARDED_FOR')) {
            $ip = getenv('HTTP_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_FORWARDED')) {
            $ip = getenv('HTTP_FORWARDED');
        }
        else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
   
    function new_user() {
        $insert = mysql_query ("INSERT INTO useronline(timestamp, ip) VALUES ('$this->timestamp', '$this->ip')");
        if (!$insert) {
            $this->error[$this->i] = "Unable to record new visitor\r\n";           
            $this->i ++;
        }
    }
   
    function delete_user() {
        $delete = mysql_query ("DELETE FROM useronline WHERE timestamp < ($this->timestamp - $this->timeout)");
        if (!$delete) {
            $this->error[$this->i] = "Unable to delete visitors";
            $this->i ++;
        }
    }
   
    function count_users() {
        if (count($this->error) == 0) {
            $count = mysql_num_rows ( mysql_query("SELECT DISTINCT ip FROM useronline"));
            return $count;
        }
    }

}

?>

Wednesday, May 30, 2012

Get Visitors IP Address PHP



Get Visitors IP Address PHP


Get Visitors IP Address PHP

 web statistic is very important when you start  your own site.web statistics mainly consist of page views today,yesterday,last month &all history etc.in addition to those some applications have IP addresses of viewers display.In this post I show you how to collect Ip address of your page viewers and store in a text file.
                                           First you have to make empty  text file called "visitor.txt" in your web root. where store IP Addresses of visitors.
           Following PHP File track the visitors IP address and store in above text file.
<?php
$counter = "visitor.txt";
$today = getdate();
$month = $today[month];
$mday = $today[mday];
$year = $today[year];
$current_date = $mday . $month . $year;
$fp = fopen($counter, "a");
$line = $REMOTE_ADDR . "|" . $mday . $month . $year . "\n";
$size = strlen($line);
fputs($fp, $line, $size);
fclose($fp);
echo "IP Address: " . $_SERVER['REMOTE_ADDR'] . "<br>"; // Display IP address
echo "Referrer: " . $_SERVER['HTTP_REFERER'] . "<br>"; // Display the referrer
echo "Browser: " . $_SERVER['HTTP_USER_AGENT'] . ""; // Display browser type
?>
Login system php

Tuesday, May 29, 2012

Login System php


Login System php

Login system basically consist of Registration Form,Login form and Login out links, By looking at the sites which have logging systems you may view basically above files only.but behind those viewable files there are some files hidden and do very important role in logging systems I have created fallowing files to make this system work properly and keeping security to avoid unauthorized person access.
  1. register.php- contains registration form.
  2. register-check.php- validates the above form and checks with database the user existence  and conveys correctly filed form data into the MySql table.
  3. dbcon.php- Connects with your database "my_database".
  4. registered.php- inform you have registered successfully and link to login form. 
  5. login_form.pp-collect your login details. 
  6. check_login- check login details are correct or not If correct direct to member area and If not direct to login_ fail.php. 
  7. member-area.php- link to profile area and logout.
  8. login_failed-inform you your login details are wrong.
  9. logout.php- you can logout.
  10. authorisation.php- check  member id is present or direct to access-denied.php
  11. access-denied-access is not allowed who are going to type URL of member-area.php.
dbcon.php
    Create following table in your data base called "my_database".

     CREATE TABLE IF NOT EXISTS `members` (
      `member_id` int(11) NOT NULL AUTO_INCREMENT,
      `firstname` varchar(100) NOT NULL,
      `lastname` varchar(100) NOT NULL,
      `login` varchar(100) NOT NULL,
      `passwd` varchar(32) NOT NULL,
      PRIMARY KEY (`member_id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

    register.php

    <?php
        session_start();
    ?>
    <html>
    <head>

    <title>Registration Form</title>

    </head>
    <body>
    <?php
        if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
            echo '<ul class="err">';
            foreach($_SESSION['ERRMSG_ARR'] as $msg) {
                echo '<li>',$msg,'</li>';
            }
            echo '</ul>';
            unset($_SESSION['ERRMSG_ARR']);
        }
    ?>
    <h2><center><font color=#f09718>Registration Form</font></center></h2>
    <form id="loginForm" name="loginForm" method="post" action="register-check.php">
      <table bgcolor=#f09718 align="center">
        <tr  bgcolor=#ffffff>
          <th>First Name </th>
          <td><input name="fname" type="text" class="textfield" id="fname" /></td>
        </tr>
        <tr bgcolor=#ffffff>
          <th>Last Name </th>
          <td><input name="lname" type="text" class="textfield" id="lname" /></td>
        </tr>
        <tr bgcolor=#ffffff>
          <th width="124">Login</th>
          <td width="168"><input name="login" type="text" class="textfield" id="login" /></td>
        </tr>
        <tr bgcolor=#ffffff>
          <th>Password</th>
          <td><input name="password" type="password" class="textfield" id="password" /></td>
        </tr>
        <tr bgcolor=#ffffff>
          <th>Confirm Password </th>
          <td><input name="cpassword" type="password" class="textfield" id="cpassword" /></td>
        </tr>
        <tr bgcolor=#ffffff>
          <td>&nbsp;</td>
          <td><input type="submit" name="Submit" value="Register" /></td>
        </tr>
      </table>
    </form>
    </body>
    </html>

    register-check.php

    <?php
      
        session_start();
      
      
        require_once('dbcon.php');
      
      
        $errmsg_arr = array();
      

        $errflag = false;
      
     
        $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
        if(!$link) {
            die('Failed to connect to server: ' . mysql_error());
        }
      
        //Select database
        $db = mysql_select_db(DB_DATABASE);
        if(!$db) {
            die("Unable to select database");
        }
      
        //Function to sanitize values received from the form. Prevents SQL injection
        function clean($str) {
            $str = @trim($str);
            if(get_magic_quotes_gpc()) {
                $str = stripslashes($str);
            }
            return mysql_real_escape_string($str);
        }
      
        //Sanitize the POST values
        $fname = clean($_POST['fname']);
        $lname = clean($_POST['lname']);
        $login = clean($_POST['login']);
        $password = clean($_POST['password']);
        $cpassword = clean($_POST['cpassword']);
      
        //Input Validations
        if($fname == '') {
            $errmsg_arr[] = 'First name missing';
            $errflag = true;
        }
        if($lname == '') {
            $errmsg_arr[] = 'Last name missing';
            $errflag = true;
        }
        if($login == '') {
            $errmsg_arr[] = 'Login ID missing';
            $errflag = true;
        }
        if($password == '') {
            $errmsg_arr[] = 'Password missing';
            $errflag = true;
        }
        if($cpassword == '') {
            $errmsg_arr[] = 'Confirm password missing';
            $errflag = true;
        }
        if( strcmp($password, $cpassword) != 0 ) {
            $errmsg_arr[] = 'Passwords do not match';
            $errflag = true;
        }
      
        //Check for duplicate login ID
        if($login != '') {
            $qry = "SELECT * FROM members WHERE login='$login'";
            $result = mysql_query($qry);
            if($result) {
                if(mysql_num_rows($result) > 0) {
                    $errmsg_arr[] = 'Login ID already in use';
                    $errflag = true;
                }
                @mysql_free_result($result);
            }
            else {
                die("Query failed");
            }
        }
      
      
        if($errflag) {
            $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
            session_write_close();
            header("location: register.php");
            exit();
        }


        $qry = "INSERT INTO members(firstname, lastname, login, passwd) VALUES('$fname','$lname','$login','".md5($_POST['password'])."')";
        $result = @mysql_query($qry);
      
        //Check whether the query was successful or not
        if($result) {
            header("location: register-success.php");
            exit();
        }else {
            die("Query failed");
        }
    ?>

    dbcon.php 

    <?php
        define('DB_HOST', 'localhost');
        define('DB_USER', 'root');
        define('DB_PASSWORD', '');
        define('DB_DATABASE', 'my_database');
    ?>


    register-success.php



    <html>
    <head>
    <title>Registration Successful</title>
    </head>
    <body>
    <h1>Registration Successful</h1>
    <p><a href="login_form.php">Click here</a> to login to your account.</p>
    </body>
    </html>


    login_form.php


    <head>
    <title>Login Form</title>
    </head>
    <body>
    <div align="center">
    <table bgcolor=eda528>
    <h3>Login Form</h3>
    <form id="loginForm" name="loginForm" method="post" action="check_login.php">
      <tr bgcolor=#ffffff>
          <td width="112"><b>Login</b></td>
          <td width="188"><input name="login" type="text" class="textfield" id="login" /></td>
        </tr>
        <tr bgcolor=#ffffff>
          <td><b>Password</b></td>
          <td><input name="password" type="password" class="textfield" id="password" /></td>
        </tr>
        <tr bgcolor=#ffffff>
          <td>&nbsp;</td>
          <td><input type="submit" name="Submit" value="Login" /></td>
        </tr>
    </table>
    </td></tr>
    </table>
    </div>

    </form>
    </body>
    </html>

    check_login.php


    <?php
       
        session_start();
       
       
        require_once('dbcon.php');
       
       
        $errmsg_arr = array();
       

        $errflag = false;
       
       
        $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
        if(!$link) {
            die('Failed to connect to server: ' . mysql_error());
        }
       
        //Select database
        $db = mysql_select_db(DB_DATABASE);
        if(!$db) {
            die("Unable to select database");
        }
       
       
        function clean($str) {
            $str = @trim($str);
            if(get_magic_quotes_gpc()) {
                $str = stripslashes($str);
            }
            return mysql_real_escape_string($str);
        }
       
       
        $login = clean($_POST['login']);
        $password = clean($_POST['password']);
       
        //Input Validations
        if($login == '') {
            $errmsg_arr[] = 'Login ID missing';
            $errflag = true;
        }
        if($password == '') {
            $errmsg_arr[] = 'Password missing';
            $errflag = true;
        }
       
        //If there are input validations, redirect back to the login form
        if($errflag) {
            $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
            session_write_close();
            header("location: login-form.php");
            exit();
        }
       
       
        $qry="SELECT * FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'";
        $result=mysql_query($qry);
       
        //Check whether the query was successful or not
        if($result) {
            if(mysql_num_rows($result) == 1) {
                //Login Successful
                session_regenerate_id();
                $member = mysql_fetch_assoc($result);
                $_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
                $_SESSION['SESS_FIRST_NAME'] = $member['firstname'];
                $_SESSION['SESS_LAST_NAME'] = $member['lastname'];
                session_write_close();
                header("location: member-area.php");
                exit();
            }else {
                //Login failed
                header("location: login_failed.php");
                exit();
            }
        }else {
            die("Query failed");
        }
    ?>

    member-area.php


    <?php
    require_once('authorisation.php');
    ?>
    <head>
    <title>Member Area</title>
    </head>
    <body>
    <center><h1>Welcome <?php echo $_SESSION['SESS_FIRST_NAME'];?></h1>
    <a href="profile.php"><?php echo $_SESSION['SESS_FIRST_NAME'];?>&nbsp;Enter Your Profile</a> | <a href="logout.php">Logout</a>
    <p>members area. </p></center>
    </body>
    </html>


    login_failed.php


    <head>
    <title>Login Failed</title>
    <body>
    <h1>Login Failed </h1>
    <p align="center">&nbsp;</p>
    <h4 align="center" class="err">Login Failed!<br />
      Please check your username and password</h4>
    </body>
    </html>

    profile.php
    you can create your own file

    logout.php


     <?php
      
        session_start();
      
      
        unset($_SESSION['SESS_MEMBER_ID']);
        unset($_SESSION['SESS_FIRST_NAME']);
        unset($_SESSION['SESS_LAST_NAME']);
    ?>
    <html>
    <head>

    <title>Logged Out</title>

    </head>
    <body>
    <h1>Logout </h1>
    <p align="center">&nbsp;</p>
    <h4 align="center" class="err">You have been logged out.</h4>
    <p align="center">Click here to <a href="login_form.php">Login</a></p>
    </body>
    </html>

    authorisation.php 

    <?php
        //Start session
        session_start();
      
        //Check whether the session variable SESS_MEMBER_ID is present or not
        if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
            header("location: access-denied.php");
            exit();
        }
    ?>

    access-denied.php 


    <html>
    <head>
    <title>Access Denied</title>
    </head>
    <body>
    <h1>Access Denied </h1>
    <p align="center">&nbsp;</p>
    <h4 align="center" class="err">Access Denied!<br />
      You do not have access to this resource.</h4>
    </body>
    </html>



    different types of input php



    Different types of input php

    In HTML Form You may have seen different types of input fields like text fields,text areas,check boxes,options and radios etc.This post is to show you how to create above fields in HTML and how post the details of forms through a PHP file in to a MySql database.
                     By now you may have created the data base called "my_database" which we have used for our previous lessens. create table called "persanal_data" in your database using following fields and data type indicated.

    CREATE TABLE IF NOT EXISTS `persanal_data` (
      `id` int(50) NOT NULL AUTO_INCREMENT,
      `Fname` varchar(50) NOT NULL,
      `Lname` varchar(50) NOT NULL,
      `gender` varchar(50) NOT NULL,
      `level` varchar(50) NOT NULL,
      `details` longtext NOT NULL,
      `pet` varchar(50) NOT NULL,
      `drink` varchar(50) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

    Then I have created HTML file including different types of filed as follows.

       
    First Name:-
    Last Name:-
    Gender:-Male:-
    Female:-
    Please Select your Level of Education:-Primery:-
    Secondary:-
    University:-
    :
    Select a your favorite pet:-:
    Select type of drink:-:

    Then following php file should be created to send the collected data from the form to mysql.

    <?php
    $username="root";
    $password="";
    $database="my_database";
    $Fname = $_POST["Fname"];
    $Lname = $_POST["Lname"];
    $gender = $_POST["gender"];
    $level = $_POST["level"];
    $details = $_POST["details"];
    $pet = $_POST["pet"];
    $drink = $_POST["drink"];
    mysql_connect(localhost,$username,$password);
    @mysql_select_db($database) or die( "Unable to select database");
    $query = "INSERT INTO persanal_data VALUES ('','$Fname','$Lname','$gender','$level ','$details','$pet','$drink')";
    mysql_query($query);
    mysql_close();
    echo
    "You have sucessfully entered data";
    ?>

    Monday, May 28, 2012

    php image thumbnails



    Image Thumbnails Generations


    Make 2 folders named "image" and "thumbnails" in your root directory. Insert Medium size or large Images in to images folder Then run the following php file and you will find thumbnails of images you inserted in to images folder in your thumbnails folder.

    <?php

    $imagefolder='./image';            
    $thumbsfolder='./thumbnails';
    $errorimage = 1;            
    $prefix = "tn_";             
    $max_width = 150;            
    $max_height = 150;           

    echo "<table cellspacing=0><tr><td align=center><a style='color: blue; font-size: 11px; text-decoration: none;' </td></tr>";

    @set_time_limit(0);

    if (!is_dir($thumbsfolder)){
     mkdir($thumbsfolder, 0777);
    }

    if (!is_dir($thumbsfolder)){
    echo "<tr><td style='border: 2px solid red;'><font color=red><b>ERROR #4</b></font>: Could not create direcotry! Please create it manually!</td></tr></table>";
    }

    $pics=directory($imagefolder,"jpg,jpeg,png,gif");

    $pics=ditchtn($pics,$prefix);

    if ($pics[0]!="")
    {
     $time_start = microtime_float();
     $ix = 0;
     foreach ($pics as $p)
      {
       createthumb($imagefolder."/".$p,$thumbsfolder."/".$prefix.$p,$max_width,$max_height,$errorimage);
       $ix++;
      }

      $time_end = microtime_float();
      $time = $time_end - $time_start;
      echo "<tr><td style='border: 2px solid green;'>&nbsp;<b>DONE</b>, $ix thumbnails where created in ".round($time,4)." seconds!&nbsp;</td></tr></table>";


    }
    else
    {
     echo ("<tr><td style='border: 2px solid red;'><font color=red><b>ERROR #1</b></font>: There are no images in this folder!</td></tr></table>");
     exit;
    }



    function ditchtn($arr,$thumbname)
    {
     foreach ($arr as $item)
      {
       $array = strstr($item, $thumbname);
       if (!$array[1]){
        $tmparr[]=$item;
       }
      }
     return $tmparr;
    }


       
    function createthumb($name,$filename,$new_w,$new_h,$errorimage)
    {
     $system=explode(".",$name);

     if (strpos(strtolower($system[(count($system)-1)]), "jpg") !== FALSE ){
      $src_img=@imagecreatefromjpeg($name);
     }

     if (strpos(strtolower($system[(count($system)-1)]), "jpeg") !== FALSE ){
      $src_img=@imagecreatefromjpeg($name);
     }

     if (strpos(strtolower($system[(count($system)-1)]), "png") !== FALSE ){
      $src_img=@imagecreatefrompng($name);
     }

     if (strpos(strtolower($system[(count($system)-1)]), "gif") !== FALSE ){
      $src_img=@imagecreatefromgif($name);
     }

    if (!$src_img){
     if (strpos(strtolower($system[(count($system)-1)]), "gif") !== FALSE ){
      if($errorimage == 1){      


       $src_img = imagecreate ("150", "20");
       $bgc = imagecolorallocate ($src_img, 255, 255, 255);
       $tc = imagecolorallocate ($src_img, 255, 0, 0);
       imagefilledrectangle ($src_img, 0, 0, 150, 20, $bgc);
       imagestring ($src_img, 1, 5, 5, "Error loading $name", $tc);

       imagejpeg($src_img,$filename);

       imagedestroy($src_img);
       echo "<tr><td style='border: 2px solid blue; border-bottom: 0px solid blue;'>";
       echo "<a style='color: black; text-decoration: underline;' href='".$filename."'>Thumbnail</a> of <a style='color: black; text-decoration: underline;' href='".$name."'>".strtolower($name)."</a> <font color=red>unsuccessfully</font> created<br>";
       echo "</td></tr>";
      }
      else
      {
       echo ("<tr><td style='border: 2px solid red;'><font color=red><b>ERROR #2</b></font>: Your GD lib does not support gif images!</td></tr></table>");
       exit;
      }
     }
     else
     {
      echo ("<tr><td style='border: 2px solid red;'><font color=red><b>ERROR #2</b></font>: Unknow filetype!</td></tr></table>");
      exit;
     }
    }
    else
    {
     $old_x=imageSX($src_img);
     $old_y=imageSY($src_img);
     if ($old_x > $old_y){
      $thumb_w=$new_w;
      $thumb_h=$old_y*($new_h/$old_x);
     }

     if ($old_x < $old_y) {
      $thumb_w=$old_x*($new_w/$old_y);
      $thumb_h=$new_h;
     }
     if ($old_x == $old_y){
      $thumb_w=$new_w;
      $thumb_h=$new_h;
     }

     if ($thumb_w == "" OR $thumb_h == ""){
      echo ("<tr><td style='border: 2px solid red;'><font color=red><b>ERROR #3</b></font>: Unexpected error!</td></tr></table>");
      exit;
     }

     $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
     imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

     if (strpos(strtolower($system[(count($system)-1)]), "jpg") !== FALSE ){
      imagejpeg($dst_img,$filename);
     }

     if (strpos(strtolower($system[(count($system)-1)]), "jpeg") !== FALSE ){
      imagejpeg($dst_img,$filename);
     }

     if (strpos(strtolower($system[(count($system)-1)]), "png") !== FALSE ){
      imagepng($dst_img,$filename);
     }

     if (strpos(strtolower($system[(count($system)-1)]), "gif") !== FALSE ){
      imagegif($dst_img,$filename);
     }


     imagedestroy($dst_img);
     imagedestroy($src_img);
     echo "<tr><td style='border: 2px solid blue; border-bottom: 0px solid blue;'>";
     echo "<a style='color: black; text-decoration: underline;' href='".$filename."'>Thumbnail</a> of <a style='color: black; text-decoration: underline;' href='".$name."'>".strtolower($name)."</a> <font color=green>successfully</font> created<br>";
     echo "</td></tr>";
     }
    }


    function directory($dir,$filters)
    {
     $handle=opendir($dir);
     $files=array();
     if ($filters == ""){
      while(($file = readdir($handle))!==false){
       $files[] = $file;
      }
     }
    else{
     if ($filters != "")  {
      $filters=explode(",",$filters);
      while (($file = readdir($handle))!==false){
       for ($f=0;$f<count($filters);$f++){
        $system=explode(".",$file);
        if (strtolower($system[(count(system))]) == strtolower($filters[$f])){
         $files[] = $file;
        }
       }
      }
     }
     else
     {
      echo ("<tr><td style='border: 2px solid red;'><font color=red><b>ERROR #3</b></font>: Unexpected error!</td></tr></table>");
      exit;
     }
    }
    closedir($handle);
    return $files;
    }

    function microtime_float()
    {
     list($usec, $sec) = explode(" ", microtime());
     return ((float)$usec + (float)$sec);
    }
    ?>

    PHP Image of the day

    PHP Image of the day

     First create  a folder named "files" in your root folder and incer 31 images into it naming phpto1, phpto2....etc.. Then create the the fallowing php file. You don't have to change image everyday The images are automatically changed in each day.


    <?php

    $totalPics="31";                   

    $photoOfTheDay = Array (          

       '1' => 'files/photo1.jpg' ,    
       '2' => 'files/photo2.jpg' ,    
       '3' => 'files/photo3.jpg' ,   
       '4' => 'files/photo4.jpg' ,    
       '5' => 'files/photo5.jpg' ,    
       '6' => 'files/photo6.jpg' ,    
       '7' => 'files/photo7.jpg' ,    
       '8' => 'files/photo1.jpg' ,    
       '9' => 'files/photo2.jpg' ,    
       '10' => 'files/photo3.jpg' ,    
       '11' => 'files/photo4.jpg' ,    
       '12' => 'files/photo5.jpg' ,    
       '13' => 'files/photo6.jpg' ,    
       '14' => 'files/photo7.jpg' ,   
       '15' => 'files/photo1.jpg' ,    
       '16' => 'files/photo2.jpg' ,    
       '17' => 'files/photo3.jpg' ,    
       '18' => 'files/photo4.jpg' ,    
       '19' => 'files/photo5.jpg' ,    
       '20' => 'files/photo6.jpg' ,    
       '21' => 'files/photo7.jpg' ,    
       '22' => 'files/photo4.jpg' ,    
       '23' => 'files/photo5.jpg' ,    
       '24' => 'files/photo6.jpg' ,    
       '25' => 'files/photo7.jpg' ,    
       '26' => 'files/photo1.jpg' ,    
       '27' => 'files/photo2.jpg' ,    
       '28' => 'files/photo3.jpg' ,    
       '29' => 'files/photo4.jpg' ,    
       '30' => 'files/photo5.jpg' ,    
       '31' => 'files/photo6.jpg' , );   
    $x=date("j"); 
    if($x > $totalPics) { $x=rand(1,$totalPics); }
    echo <<<EOC
    <center><img src="$photoOfTheDay[$x]"></center>
    EOC;

    ?>

    php image manipulations



    php image manipulations

    Sunday, May 27, 2012

    Multiple Files Upload php


    Multiple Files Upload into Multiple Folders

    The following folders should be created in your web root
    1.  accountant
    2.  deputy_director
    3.  Administrative_officer
    Director in an office can send files to above 3 officers or more.
    Following HTML file is used to upload files to above 3 folders.

                                  Upload To All












    multiple Files Upload
    Title
    Select file


    Codes for above file is as follows

    <html>
     <head>
     <title>UPload Multiple file</title>
    </head>
    <body>
    <center><h2>Upload To All </h2></center>
    <form action="upload4.php" method="post" enctype="multipart/form-data" name="form1" id="form1" > <tr><td>
    <table align="center">
    <tr><td colspan=2><hr></hr></td></tr>
    <tr> <td><strong>multiple Files Upload </strong></td> </tr>
    <tr><td>Title</td></tr>
    <tr><td><input type="text" name="txtName"></td></tr>
     <tr> <td>Select file <input name="ufile" type="file" id="ufile" size="50" /></td> </tr>
    <tr><td><input name="sender" type="hidden" value="Director"></td></tr>
    <tr><td align="center"><input type="submit" name="Submit" value="Upload" /></td> </tr>
    </form>
    <tr><td colspan=2><hr></hr></td></tr>
    </table>
    </body>
    </html>

    This uploaded files details are sent to a data base.Make 3 tables accountant, deputy_director and Administrative_officer in my_database which you have practiced in early lessens.Fields are stated in the below file for Administrative_officer table only.
     
    CREATE TABLE IF NOT EXISTS `Administrative_officer`
    ( `ID` int(11) NOT NULL AUTO_INCREMENT,
     `date` varchar(60) NOT NULL,
    `time` varchar(45) NOT NULL,
     `Name` varchar(100) NOT NULL,
     `file` varchar(100) NOT NULL,
     `sender` varchar(45) NOT NULL,
    PRIMARY KEY (`ID`)
     ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

    upload4.php which carries uploaded 3 files to 3 folders is as follows
    <?php
    $path1= "accountant/".$_FILES['ufile']['name'];
    $path2="deputy_director/".$_FILES['ufile']['name'];
    $path3="Administrative_officer/".$_FILES['ufile']['name'];
    $date = date("y/m/d");
    $time = date("g:i a");
    $file_name = $_FILES['ufile']['name'];
    $random_digit=rand(0000,9999); $new_file_name=$random_digit.$file_name;
    $path1= "accountant/".$new_file_name;
    if($file !=none)
    {
     if(copy($_FILES['ufile']['tmp_name'], $path1))
    {
     mysql_connect("localhost","root","") or die (mysql_error());
    mysql_select_db("my_database");
    $strSQL = "INSERT INTO accountant";
     $strSQL .="(date,time,Name,file,sender) VALUES ('$date','$time','".$_POST["txtName"]."','$new_file_name','".$_POST["sender"]."')"; mysql_query($strSQL); echo "<center>Uploaded To accountant</center> "; mysql_close();
     }
    }
     $file_name = $_FILES['ufile']['name'];
     $random_digit=rand(0000,9999);
    $new_file_name=$random_digit.$file_name;
    $path2= "deputy_director/".$new_file_name;
     if($file !=none)
    {
    if(copy($_FILES['ufile']['tmp_name'], $path2))
    {
     mysql_connect("localhost","root","") or die (mysql_error());
    mysql_select_db("my_database");
    $strSQL = "INSERT INTO deputy_director";
    $strSQL .="(date,time,Name,file,sender) VALUES ('$date','$time','".$_POST["txtName"]."','$new_file_name','".$_POST["sender"]."')"; mysql_query($strSQL); echo "<center>Uploaded To deputy_director</center> "; mysql_close();
    }
    }
    $file_name = $_FILES['ufile']['name'];
    $random_digit=rand(0000,9999);
    $new_file_name=$random_digit.$file_name;
    $path3= "Administrative_officer/".$new_file_name;
     if($file !=none)
    {
     if(copy($_FILES['ufile']['tmp_name'], $path3))
    {
     mysql_connect("localhost","root","") or die (mysql_error()); mysql_select_db("my_database");
    $strSQL = "INSERT INTO Administrative_officer";
     $strSQL .="(date,time,Name,file,sender) VALUES ('$date','$time','".$_POST["txtName"]."','$new_file_name','".$_POST["sender"]."')"; mysql_query($strSQL); echo "<center>Uploaded To Administrative_officer</center> ";
     mysql_close();
    }
    } else { echo "ERROR.....";
    }
    ?>
    accountant, deputy director and Administrative officer should have to view their accounts to see what their director has send them.Their account viewing files looks like follows.
    <?php
     $dbHost = 'localhost';
    $dbUser = 'root';
     $dbPass = '';
    $dbName = 'my_database';
    $dbConn = mysql_connect ($dbHost, $dbUser, $dbPass) or die ('MySQL connect failed. ' . mysql_error());
    mysql_select_db($dbName) or die('Cannot select database. ' . mysql_error());
    ?>
    <html>
     <head>
    <title></title>
    </head>
    <body>
     <h2><font color="#54164e"><center>Accountant</font></center></h2>
    <table align="center" bgcolor="#9a7608" cellpadding="10" cellspacing="3">
    <tr bgcolor="#ffffff">
    <th> <center> ID </center>
    </th> <th> <center> File Name </center> </th>
    <th> <center> Type </center> </th>
    <th> <center> Open File </center> </th>
     <th> <center> Delete Files </center> </th>
    </tr>
    <?php
    if($_POST['btsubmit']=='Submit') {
    foreach($_POST as $k => $v){
    $$k = $v;
    }
    $dir ="accountant";
    $to_del= $_POST['to_del'];
     if (("submit")&&($to_del != "")) {
     foreach($to_del as $rfn) {
     $remove = "$dir/$rfn";
    unlink($remove);
    }
    }
     foreach($to_del as $v){ mysql_query("DELETE FROM accountant where file='$v'");
    }
     echo "<center><font color='white' size=5> records is been deleted.</font></center></br>";
    }
    ?>
    <?php
     $query = "SELECT * FROM accountant";
    $result = mysql_query($query);
    while ($row = mysql_fetch_assoc($result)){
     ?>
    <form name="form" method="post">
    <tr bgcolor="#ffffff">
    <td><?php echo $row["ID"];?></td>
     <td><?php echo $row["Name"];?></td>
    <td><?php echo $row["file"];?></td>
    <td><a href="accountant/<?php echo $row['file'];?>">View</a></td>
    <td> <center> <input type=checkbox name="to_del[]" value="<?php echo $row["file"];?>">Yes </center> </td></tr>
     <?php
    }
    ?>
    <tr><th colspan=4 bgcolor="#ffffff">Select Check box and Press Submit To Delete files</th>
    <td bgcolor="#ffffff"><input type="submit" value="Submit" name="btsubmit"></td>
    </tr>
    </table>
    </form>
    </body>
    </html>

    Accountant page will look as below.

    Accountant










    ID









    File Name









    Type









    Open File









    Delete Files
    1 wintekweb 94530802772A20120502M00201.jpg View








    Yes
    2 wintekweb2 413010 ways to make money online.docx View








    Yes
    3 wintekweb3 6057db.sql View








    Yes
    Select Check box and Press Submit To Delete files

    By clicking the View you can see the file uploaded by director. Here by clicking check box and press submit file also could be deleted.

    Saturday, May 26, 2012

    multiple file upload php



    Multiple File Upload into single folder

    Make Folder Named "upload" in your root directory Then you  have to make HTML form to submit uploaded files into upload folder in your root directory.Files I have created for this purpose are "mupload.html","mupload.php".

    Below shows you the file upload interface created from "mupload.html" pressing Add another link creates another upload field in to the interface.

    Multiple File Upload

    Add another
    Following codes generate the above file called "mupload.html".

    <html>
    <head>
     <title>multiple file upload </title>
    <script type="text/javascript">
    function add_file_field(){
    var container=document.getElementById('file_container');
    var file_field=document.createElement('input');
    file_field.name='images[]';
    file_field.type='file';
    container.appendChild(file_field);
     var br_field=document.createElement('br');
    container.appendChild(br_field);
    }
    </script>
    </head>
    <body>
     <form action="mupload.php" method="post" enctype="multipart/form-data" name="mutiple_file_upload_form" id="mutiple_file_upload_form">
     <h3>Multiple File Upload </h3>
    <div id="file_container"> <input name="images[]" type="file" /> <br /> </div>
    <a href="javascript:void(0);" onClick="add_file_field();">Add another</a><br />
    <input type="submit" name="Submit" value="Submit" />
    </form>
    </body>
     </html>

    Below shows you the"mupload.php"  file which carries the uploaded file into folder upload in your root directory.

    <?php
     if (isset($_POST['Submit'])) {
     $number_of_file_fields = 0;
     $number_of_uploaded_files = 0;
    $number_of_moved_files = 0;
    $uploaded_files = array();
    $upload_directory = dirname(__file__) . '/upload/';
     for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
     $number_of_file_fields++;
     if ($_FILES['images']['name'][$i] != '') {
     $number_of_uploaded_files++;
     $uploaded_files[] = $_FILES['images']['name'][$i];
     if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . $_FILES['images']['name'][$i])) {
    $number_of_moved_files++;
     }
     }
     }
    echo "Number of File fields created $number_of_file_fields.<br/> ";
     echo "Number of files submitted $number_of_uploaded_files . <br/>";
    echo "Number of successfully moved files $number_of_moved_files . <br/>";
    echo "File Names are <br/>" . implode(',', $uploaded_files);
    }
     ?>

    File Upload Scripts

    File Upload Scripts

    Single File Upload in to one folder scripts
    Multiple Files upload into one folder
    Single File Upload into Multiple Folders(with file upload database)

    Single file upload php


    Before writing scripts for file upload make a Folder named "science" in your htdocs  or www (web root) then below contains a file in html format in which creates uploading interface and posting the uploaded file into php file called "upload.php". 
    html interface looks as below



    Select a file to upload
    Science:


     
    Fallowing Codes creates the above file upload interface.

    <html>
    <head>
    <script type="text/javascript" language="JavaScript"><!--
    function ExtensionsOkay() {
    var extension = new Array();
    var fieldvalue = document.Myform.file.value;
    extension[0] = ".doc";
    extension[1] = ".docx";
    extension[2] = ".jpg";
    extension[3] = ".jpeg";
    extension[4] = ".pdf";
    extension[5] = ".xls";
    var thisext = fieldvalue.substr(fieldvalue.lastIndexOf('.'));
     for(var i = 0; i < extension.length; i++) {
     if(thisext == extension[i]) { return true; }
     }
     alert("Your upload form contains an unapproved file name."); return false;
    }
    //--></script>
    </head>
    <body>
    <center> <br><br><br> Select a file to upload<br><br>
    <table >
    <tr>
    <td> <form name= "Myform" enctype="multipart/form-data" action="upload.php" method="POST" onsubmit="return ExtensionsOkay();"/>
     <input type="hidden" /> Science:</td><td> <input name="file" type="file" /></td><td> <input type="submit" value="Upload File" /> </form></td>
    </tr>
    </table>
    </center>
    </body>
    </html>

    upload.php is shown below.

    <html>
     <body>
    <?php
    $target_path = "science/";
     $target_path = $target_path . basename( $_FILES['file']['name']);
     if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
    echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
    }
    else
    {
    echo "There was an error uploading the file, please try again!";
    }
     ?>
    </br></br>
    <a href="view.php">View Uploaded files</a>
    </body>
    </html>

    view.php is shown below.

    <?PHP
     $folder = "science/";
    $handle = opendir($folder);
    while ($file = readdir($handle))
    {
     $files[ ] = $file;
    }
    closedir($handle);
    foreach ($files as $file)
     {
     echo '<li><a href="science/'.$file.'">'.$file.'</a></li>';
    }
    ?>

    Friday, May 25, 2012

    php mysql delete

    PHP MySQL Delete 

    The DELETE statement is used to delete records in MySql tables.
    Delete Data In a Database Table
    Example:-
    Following is the biodata table we created in previous lesson.
    First Name Last Name Age
    Scarlett Johansson 25
    Clooney Anderson 25
    Kate Hudson Hudson 25

    We will delete the record with last name Anderson.
    The following codes deletes the records in the "biodata"  where LastName is Anderson.

    <?php
    $con = mysql_connect("localhost","root","");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }

    mysql_select_db("my_database", $con);

    mysql_query("DELETE FROM biodata WHERE LastName='Anderson'");

    mysql_close($con);
    echo "delete 1 record";
    ?>

    Delete data using web interface (HTML PHP Files) 

    Re design the biodata view table with delete hyperlink like in following table. 

    Id First Name Last Name Age Delete
    1 Scarlett Johansson 25 delete
    2 Clooney Anderson 35 delete
    3 Kate Hudson 30 delete

    Codes for above modified table is as follows 

    <?php
     $host="localhost";
     $username="root";
     $password="";
     $db_name="my_database";
     $tbl_name="biodata";
    mysql_connect("$host", "$username", "$password")or die("cannot connect");   mysql_select_db("$db_name")or die("cannot select DB");
    $sql="SELECT * FROM $tbl_name";
    $result=mysql_query($sql);
    ?>
    <table bgcolor=#000000 align="center">
     <tr>
    <td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
    <td align="center" bgcolor="#FFFFFF"><strong>First Name</strong></td>
     <td align="center" bgcolor="#FFFFFF"><strong>Last Name</strong></td>
    <td align="center" bgcolor="#FFFFFF"><strong>Age</strong></td>
    <td align="center" bgcolor="#FFFFFF"><strong>Delete</strong></td> </tr>
    <?php
    while($rows=mysql_fetch_array($result)){
    ?>
    <tr>
    <td bgcolor="#FFFFFF"><?php echo $rows['id']; ?></td>
    <td bgcolor="#FFFFFF"><?php echo $rows['FirstName']; ?></td>
    <td bgcolor="#FFFFFF"><?php echo $rows['LastName']; ?></td>
    <td bgcolor="#FFFFFF"><?php echo $rows['Age']; ?></td>
    <td bgcolor="#FFFFFF"><a href="delete_records.php?id=<?php echo $rows['id']; ?>">delete</a></td>
    </tr>
    <?php
     }
     mysql_close();
     ?>
    </table>

    "delete_records.php", The file which deletes data from the biodata table is bellow

    <?php
    $host="localhost";
    $username="root";
    $password="";
    $db_name="my_database";
    $tbl_name="biodata";
     mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB");
     $id=$_GET['id'];
    $sql="DELETE FROM $tbl_name WHERE id='$id'";
    $result=mysql_query($sql);
    if($result)
    {
    echo "Deleted Successfully";
    }
    else
    {
    echo "ERROR";
    }
    mysql_close();
    ?>

    Delete Multiple Records in MySql Tables 

    Again we have to design the biodata table as follows with the facility of multiple delete interface.

    Php Multiple Records Delete






    ID





    First Name





    Last Name





    Age





    Delete Files
    1 Scarlett Johansson 25




    Yes
    2 Clooney Anderson 35




    Yes
    3 Kate Hudson 30




    Yes
    Select Check box and Press Submit To Delete files

    Look at bellow codes to create multiple delete php

    <?php
    $dbHost = 'localhost';
    $dbUser = 'root';
    $dbPass = '';
    $dbName = 'my_database';
    $dbConn = mysql_connect ($dbHost,$dbUser, $dbPass) or die ('MySQL connect failed. ' . mysql_error());
    mysql_select_db($dbName) or die('Cannot select database. ' . mysql_error());
    ?>
    <html>
     <head>
     <title></title>
     </head>
    <body>
     <h2><font color="#54164e"><center>Php Multiple Records Delete</font></center></h2>
    <table align="center" bgcolor="#9a7608" >
    <tr bgcolor="#ffffff">
     <th> <center> ID </center> </th> <th> <center> First Name </center> </th>
    <th> <center> Last Name</center> </th>
    <th> <center> Age </center> </th>
    <th> <center> Delete Files </center> </th> </tr>
    <?php
     if($_POST['btsubmit']=='Submit') {
     foreach($_POST as $k => $v){
    $$k = $v;
    }
     $to_del= $_POST['to_del'];
    if (("submit")&&($to_del != "")) {
     }
    foreach($to_del as $v){
     mysql_query("DELETE FROM biodata where id='$v'");
    }
     echo "<center><font color='white' size=5> records is been deleted.</font></center></br>";
    }
    ?>
    <?php $query = "SELECT * FROM biodata";
     $result = mysql_query($query);
     while ($row = mysql_fetch_assoc($result)){
     ?>
    <form name="form" method="post">
    <tr bgcolor="#ffffff">
    <td><?php echo $row["ID"];?></td>
    <td><?php echo $row["FirstName"];?></td>
    <td><?php echo $row["LastName"];?></td>
    <td><?php echo $row['Age'];?></td>
    <td> <center> <input type=checkbox name="to_del[]" value="<?php echo $row["id"];?>">Yes </center> </td>
    </tr>
    <?php
     }
    ?>
    <tr><th colspan=4 bgcolor="#ffffff">Select Check box and Press Submit To Delete files</th><td bgcolor="#ffffff"><input type="submit" value="Submit" name="btsubmit"></td>
    </tr>
    </table>
    </form>
    </body>
    </html>