Tuesday, 24 July 2012

Chat application using a database table in PHP

This article is to describe a simple chat application in php or web chat application.
When think about how to create chat application in php  we can understand that. each user accessing
the webpage get a separate instance of the webpage and there have no direct
connection between two users using the same page at the same time.So we can use
a sql database to communicate with two users.

   Online chat application in php means a chat application using ajax or in othe words
 a jquery chat application.

           Before go through the source code you can see a sample screen shot here
 Please open this same page in another tab or another browser to test the chat application.
For reduce  complexity I am not using a user login.You can simply login to chat by using your name or nick
name without any log up process.


Enter your name like Xwe , Yrt , Zty  in the From text box.You can see the online users in the right column.Click one of the
names , you can see a chat box is opened.You can write messages in it and send to the selected user.


You can download the complete zip file fromthis link:-
http://sukeshbr.freeiz.com/blog_works/openchat/openchat.zip
Here is the source code for chat application in php
 Here have two files index.php and back.php
 code
 index.php
 <html>
    <head>
       
    </head>
    <body>
        <table width="100%" height="100%" border="1" align="center" valign="center">
            <tr><td colspan="2" height="6%"><h3>Chat Window</h3></td></tr>
            <tr><td colspan="2" height="6%"> From(Your Name or Id):&nbsp;&nbsp;<input type="text" name="sender" id="sender"><br></td></tr>
            <tr><td width='85%'>
                    <div id="chat_view" >
      
       &nbsp;
                    </div>
                </td>
                <td>
                    <div id="users" name="users">Online Users</div>
                </td>
            </tr>
        </table>
        <div id="chat_list"></div>
        <style type="text/css">
            .chat_box{
border-style:solid;
border-width:medium;
width:200px;
height:300px;
float:left;

}
#msg{
width:200px;
height:200px;
overflow:auto;
}
#new_msg_text
{
width:200px;
height:50px;
}
#close_button{
width:20px;
height:20px;
}
.user_list{

}
        </style>
       
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                window.setInterval(function() {
                   viewMsg();
                   viewOnlineUsers();
                   createNewChatBox();
                   
                },1000);
            });
           
            function creatNewBox(receiver)
            {
            var newbox ="<div class='chat_box' id='chat_box_"+receiver+"'>"+
            "<div id='chat_header'><input type='text' name='receiver[]' READONLY value='"+
            receiver+"' id='receiver'><img id='close_button' src='images/close_button.jpg' alt='X' onclick='closeWindow($(this))'/></div>"+
            "<div  height='20%' id='msg' >"+
                "<br><br><br></div>"+
             "<div id='newmsg'><textarea rows='4' cols='10' id='new_msg_text'>&nbsp;</textarea></div>"+
             "<input type='button' id='btn' onclick='saveMsg($(this))'>"+
        "</div>";
       
        return newbox;
            }
           
            function createNewChatBox()
            {
             var sender=$("#sender").val();
    $("#chat_list").load('back.php?opt=get_chat&sender='+sender);
    $("input[name='chat_users[]']").each(function(){
   
viewBox($(this).val());
});
            }
            function viewBox(receiver)
            {
                if($.trim($("#sender").val())==$.trim(receiver))
                return;
               $(document).ready(function(){
               var flag=false;
              $("input[name='receiver[]']").each(function(){
             
if($(this).val()==receiver)
{flag=true;}
});
        if(flag==false)$("#chat_view").append(creatNewBox(receiver));          
               });
            }
           
            function viewOnlineUsers()
            {
                var sender=$("#sender").val();
                $("#users").load('back.php?opt=view_users&sender='+sender);
               
            }
            function closeWindow(obj)
            {
            obj.parent().parent().remove();
            }
           
            function viewMsg()
            {
                var sender=$("#sender").val();
$("input[name='receiver[]']").each(function(){
var receiver=$(this).val();
$("#chat_box_"+receiver).find("#msg").load('back.php?opt=view_msg&sender='+sender+"&receiver="+receiver);
});
}
         
        function saveMsg(obj)
        {
            var receiver=obj.parent().find("#receiver").val();
                          
            var sender=$("#sender").val();
            var msg=obj.parent().find("#new_msg_text").val();
           
           $.ajax({
           type: 'POST',
           url: 'back.php?opt=save',
           data: {"receiver":receiver,"sender":sender,"msg":msg},
           success: function(){
              
           alert("success");
           }
          
           });
        }
        </script>
       
    </body>
</html>


back.php
<?php



extract($_POST);
extract($_GET);
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('sukesh');
switch ($opt) {
    case "save":
        $query = "INSERT INTO chat (sender,receiver,msg,time) values('" . $sender . "','" . $receiver . "','" . $msg . "',NOW()" . ")";
        mysql_query($query, $con) or die("Error...");

        break;

    case "view_msg":
       
        $query = "SELECT * FROM chat WHERE receiver='" . $sender. "' AND sender='".$receiver."'";
       
        $r = mysql_query($query, $con) or die("Error...");
        while ($row = mysql_fetch_array($r)) {
            echo "<table><tr>";
            echo "<td>".$row['msg']."</td>";

            echo "</tr></table>";
        }
        break;
       
        case "get_chat":
        $query = "SELECT DISTINCT  sender from chat ".
        "  WHERE receiver='$sender' AND AddTime(time, '00:00:15')>=NOW()";
        echo $query ;
           $r = mysql_query($query, $con) or die("Error...3");
        while ($row = mysql_fetch_array($r)) {
       
        echo "<input type='text' name='chat_users[]' value='".$row['sender']."'>";
        }
        break;
        case "view_users":
            $query = "SELECT count(*) as count FROM users WHERE user_id='".$sender."'";
            $r=mysql_query($query, $con) or die("Error...1");
            $row = mysql_fetch_array($r);
            if($row['count']>0)
                $query = "UPDATE users SET last_visit=NOW() WHERE user_id='".$sender."'";
                else
            $query = "INSERT INTO users (user_id,last_visit) values('".$sender."',NOW())";
             
            mysql_query($query, $con) or die("Error...2");
       
            $query = "SELECT * FROM users WHERE AddTime(last_visit, '00:00:15')>=NOW()";
           
     
        $r = mysql_query($query, $con) or die("Error...3");
        while ($row = mysql_fetch_array($r)) {
            echo "<table><tr>";
       
            echo "<td><a onclick=\"viewBox('".$row['user_id']."')\">".$row['user_id']."</a></td>";

            echo "</tr></table>";
        }
            break;
}
?>


Here I am using two Mysql tables namely chat and users
chat








users






The query to make this tables
chat
CREATE TABLE IF NOT EXISTS `chat` (
  `sender` varchar(255) DEFAULT NULL,
  `receiver` varchar(255) DEFAULT NULL,
  `msg` text,
  `time` datetime DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

users
CREATE TABLE IF NOT EXISTS `users` (
  `user_id` varchar(255) NOT NULL,
  `last_visit` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


You can also read :-
Simple Game Using Jquery

Monday, 25 June 2012

Simple Game Using Jquery

This article is to discuss about online game programming.In other words  how to make a game
in  html . Nothing to think further the option is jquery.
    There are any jquery games examples are available in internet.But here I am
introducing a free online ball game coded in jquery.This is padd and ball game.The padd
move with mouse movement.We may save the ball from fall to the ground.I think
this is a simple jquery game.

You can see the working of game which I named Hit Ball before go through this
jquery game source code.


 
You can download the source code from here
http://sukeshbr.byethost3.com/Blog_Works/hit_ball/hit_ball.zip


Here have two html files g1.html and end.html.

Code

g1.html
<html>
<head>
<style type="text/css">
*{    margin: 0;
    padding: 0}
#bar{
position:absolute;
left:200px;
width:130px;
height:20px;

}
#ball{
position:absolute;
left:270px;
width:20px;
height:20px;
}
#plain{
width:97%;
height:95%;
border:10px solid #000000;
background:#ccffff;
}

#block_red1{
position:absolute;
top:100px;
left:50px;
width:50px;
height:25px;
}
#block_blue1{
position:absolute;
top:100px;
left:100px;
width:50px;
height:25px;
}
#block_red2{
position:absolute;
top:100px;
left:150px;
width:50px;
height:25px;
}
#block_pink1{
position:absolute;
top:100px;
left:200px;
width:50px;
height:25px;
}
#block_blue2{
position:absolute;
top:100px;
left:250px;
width:50px;
height:25px;
}
#block_pink2{
position:absolute;
top:100px;
left:300px;
width:50px;
height:25px;
}


</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#bar").css("top", window.innerHeight-80);
$("#ball").css("top", window.innerHeight-100);
var click_stat=false;
//Code to move bar
$(document).mousemove(function(m){
$("#body").css('cursor', 'none');
if(m.pageX>10&&m.pageX<window.innerWidth-180)
{
$("#bar").css({"left":m.pageX});
if(click_stat==false)
$("#ball").css({"left":m.pageX+70});
}
});


window.setInterval(function() {
if(click_stat==true){
var p = $("#ball");
var position = p.position();
var status=getStatus();
if(status==1)
{
var tadd=getTAdd();
var ladd=getLAdd();
$("#ball").css({"top":position.top+tadd,"left":position.left+ladd});
}
else if(status==0)
{
alert("Game Over...");
location.href="end.html";
}
else if(status==2)
{
alert("You Won...");
location.href="end.html";
}
}
},40);


//code to detect initial click
$(document).click(function(){

$("#plain").css('cursor', 'none');
click_stat=true;

});
});

function getLAdd()
{
var ladd=0;
var pball = $("#ball");
var pbar = $("#bar");
var bar_position = pbar.position();
var ball_position = pball.position();

if(ball_position.top>=window.innerHeight-100)
{
if(ball_position.left-10>=bar_position.left && ball_position.left-10<=bar_position.left+100 )
 {ladd=-2; }
 if(ball_position.left+10<=bar_position.left+200  && ball_position.left+10>=bar_position.left+100 )
 {ladd=2; }

}

if(ladd==0){ladd=getLAdd.ladd;}
if(ball_position.left<=15|| ball_position.left>=window.innerWidth-40)
ladd=-ladd;

getLAdd.ladd=ladd;
return ladd;
}

function getTAdd()
{
var tadd=0;
var pball = $("#ball");
var pbar = $("#bar");
var ball_position = pball.position();
var bar_position = pbar.position();
if(ball_position.top>=0 && ball_position.top<=11) tadd=5;
if(ball_position.top>=window.innerHeight-100) tadd=-5;
if(ball_position.top>75&&ball_position.top<125)
{

if(($("#block_red1").length>0) && (ball_position.left+20>50&&ball_position.left<100))
{
tadd=-(getTAdd.tadd);
$("#block_red1").remove();
}

if(($("#block_blue1").length>0) && (ball_position.left+20>100&&ball_position.left<150))
{
tadd=-(getTAdd.tadd);
$("#block_blue1").remove();
}
if(($("#block_red2").length>0) && (ball_position.left+20>150&&ball_position.left<200))
{
tadd=-(getTAdd.tadd);
$("#block_red2").remove();
}
if(($("#block_pink1").length>0) && (ball_position.left+20>200&&ball_position.left<250))
{
tadd=-(getTAdd.tadd);
$("#block_pink1").remove();
}
if(($("#block_blue2").length>0) && (ball_position.left+20>250&&ball_position.left<300))
{
tadd=-(getTAdd.tadd);
$("#block_blue2").remove();
}
if(($("#block_pink2").length>0) && (ball_position.left+20>300&&ball_position.left<350))
{
tadd=-(getTAdd.tadd);
$("#block_pink2").remove();
}
}
if(tadd==0){tadd=getTAdd.tadd;}
getTAdd.tadd=tadd;
return tadd;
}

function getStatus()
{
var stat;
var pball = $("#ball");
var pbar = $("#bar");
var bar_position = pbar.position();
var ball_position = pball.position();
if(ball_position.top>=bar_position.top-20)
{
if(ball_position.left+22>=bar_position.left && ball_position.left<=bar_position.left+200)
stat=1;
else
stat=0;
}
else stat=1;
if(stat!=0&&($("#block_blue1").length==0)&&($("#block_blue2").length==0)
&&($("#block_red1").length==0)&&($("#block_red2").length==0)
&&($("#block_pink1").length==0)&&($("#block_pink2").length==0))
stat=2;
return stat;
}
</script>

</head>
<body>
<div id="plain"  >
<img id="block_red1" src="images/block_red.png">
<img id="block_blue1" src="images/block_blue.png">
<img id="block_red2" src="images/block_red.png">
<img id="block_pink1" src="images/block_pink.png">
<img id="block_blue2" src="images/block_blue.png">
<img id="block_pink2" src="images/block_pink.png">

<label id="name"><h3>Hit_ball By Sukesh B R</h3></label>
<img id="bar"  src="images/bar.png">
<img id="ball"  src="images/ball.png">
</div>
</body>
</html>


end.html
<html>
<body>
<h1>Game Completed...</h1>
<br>
<a href="g1.html">Restart</a>
</body>
</html>

Code description

 Let we start from g1.html.   In the body section I placed two images namely bar and ball .
 The images for this is in the image folder which can be download from above.You can see another
 four images.They are the bricks placed above the  bar.

   In the css section , there are the code to position correctly the bricks , padd and ball.


  In the jquery section  in the mousemove event the code to move the padd is written.m is
the mouse object m.pageX gives the x cordinate of mouse pointer m.pageY  gives the y cordinte of
mouse position.      Here we change only the left property of bar image with m.pageX. 
We wont change the y cordinate.Because we need to move the padd in horizontal direction
only.


  window.setInterval()  is  another event used to execute a particular block iteratively
  in a particular time interval.in this function  getTAdd()  is called to get the   tadd which is added to the y position of the ball.
  getLAdd() is called to get the ladd which is added to the x position of the ball.
 
  The variable status returned from getStatus() determine that the game is active or
  game over or win in the game.
 
 
 In the functions getTAdd(),getLAdd() and getStatus() the ladd , tadd and staus   is calculated
by analysing the position of ball and padd.  If the ball is hit the left half of padd the ladd   will be +2.


If the ball is hit the right half of padd the ladd will be -2.  If the ball position come   near to the walls the ladd is multiplied with -1. Thus the ladd change to opposite value.  This will gives a good flow to ball.

  In the top when come near to the top wall or bricks the tadd is multiplied with minus.
  So the ball then move to downward  direction.When ball come near to a brick this the
  brick will be removed using remove() method.
 
  This is only a brief description.Hope that you can understand the core.

You can also read :-

Play wav file using HTML

Very simple Menu using Jquery Beginners Tutorial

 

Thursday, 14 June 2012

Very simple Menu using Jquery Beginners Tutorial

This  article is to teach how to create drop down menu  in html.I am not going to design a
graphical pull down menu.  Instead I am trying to reveal the basic construction of pull down
menu.

  When creating menus using jquery only the hiding and pop up of menu is handled by jquery. The
actual layout is created using  css. Creating drop down menus in css means align a <ul> and
it's child <ul> using css,because the pull down menu is constructed using a <ul>.So code for
creating menu in html includes css and jquery.

You can see a demo of resultant menu here




Code


<html>
<head>

<style type="text/css">

*{    margin: 0;
    padding: 0}
    #menu{
        z-index:5;
    }
a{
text-decoration:none;
}
    #menu li
    {    float: left;
        list-style: none;
   
        }

    #menu li a
    {    display: block;
        }



        #menu li ul
        {
            position: absolute;
            display: none;

            }

        #menu li ul li
        {    float: none;
            display: inline
            }

</style>


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#menu > li").mouseenter(function(){
$(this).find('ul').css('display', 'inline');
});

$("#menu > li").mouseleave(function(){
$(this).find('ul').css('display', 'none');
});
});
</script>
</head>


<body>
<ul id="menu">
<li><a>Menu1</a>
<ul>
<li><a href="http://www.facebook.com">Facebook</a></li>
<li><a href="http://www.google.com">Google</a></li>
<li><a href="http://newprograminglogics.blogspot.com">My Blog</a></li>
</ul>
</li>
<li>
<a href="#">Menu2</a>
<ul>
<li><a href="http://www.gmail.com">GMail</a></li>
<li><a href="http://www.twitter.com">Twitter</a></li>
</ul>
</li>
</ul><br>

</body>
</html>



Code description
                      The pull down menu is actually a  <ul>  that is unordered list. Here in the <body>
section I have placed a <ul>   with id="menu".    As seen in the demo above in this page,
here have two menus namely Menu1 and Menu2.

      This Menu1 and Menu2 are  links(<a>) placed in  <li> of <ul> with id="menu".  Besides this link
there have another <ul> in each <li>.  The  menu items are placed in the <li> of this child <ul>.

        This <ul> without applying  css  is displayed just like a list.   But using some simple css
commands we can convert it into a menu form.

*{    margin: 0;
    padding: 0}
This code is for remove margin and padding from all elements.



#menu{
        z-index:5;
    }

Is used to place the menu above all elements in page.   




a{
text-decoration:none;
}
Is use to remove the under line from links.



In the code segment :-
#menu li
    {    float: left;
        list-style: none;
   
        }
       
        float : left   place the li of ul side by side.In default it is from top to bottom,  that is vertically.       
        list-style: none removes the dots (.) from the front of each item.
       
       
       
        #menu li a
    {    display: block;
        }
       
        Is for display each item as a block.

       
       
        #menu li ul
        {
            position: absolute;
            display: none;


            }
            Here position: absolute is for place the menu items exactly  below  menu heading
            irrespect  of other elements in the page.
            display: none is for hide this contents initially.The menu items will be displayed only
            after mouse entered in menu heading.
           
           
       
        #menu li ul li
        {    float: none;
            display: inline
            }
           
            Here float: none is for remove the float to left property of child <ul>'s <li>, which is
            set in #menu li   by{    float: left}


Because here that does not require because the menu items should be displayed in  vertical manner.
display: inline set the menu items vertically.
   
   
   
                The alignment of menu is over.Now we go through the jquery  section which displays and hide
    the menu items.
   
    $("#menu > li").mouseenter(function(){
$(this).find('ul').css('display', 'inline');
});

      This code will display the child ul,that is our menu items.The parent <ul>s <li>s
mouseenter event is defined with setting child <ul>'s display property to inline.Note
that this is set to display:none initially in the css section.$(this).find(ul)
will get the child element.  .css() is a jquery library function used to change css
property of certain elements.
   
     One more thing  remain is  that we need to hide the menu item again when mouse   is come out from the menu items.        That is done by this code
     
$("#menu > li").mouseleave(function(){
$(this).find('ul').css('display', 'none');
});
});
     This is just like above code. mouseleave   event is used to detect the disappearence of mouse
pointer.      $(this).find('ul')    will give the child <ul> then display : none is used
to hide the menu items.

Thus our simple menu is begin to work.

You can also read :-

Simple Game Using Jquery
Facebook like pop up window using jquery
Introducing AJAX with a simple example program

Sunday, 3 June 2012

Delete non empty directory in php

This article is to discuss how can delete any folder in php.Delete a directory in php is done by
the method rmdir().  But it work only if the directory is empty.That is it can delete empty directories only.   


            In php delete non empty directory is done by first delete contents of folder.
That is delete all files in a folder.Then delete the empty directory using rmdir().

This code will  describe how can php remove non empty directory.   

CODE

<?php
    del('new');

        function del($dir)
         {
            $result=array_diff(scandir($dir),array('.','..'));
             foreach($result as $item)
               {

     if(!@unlink($dir.'/'.$item))
    del($dir.'/'.$item);

                }
        rmdir($dir);
           }

?>



        Here I have defined a function with name del().   It has one parameter which is the  name of the directory to be delete.Here my directory name is 'new'.


        In the   del()    function defenition   $result=array_diff(scandir($dir),array('.','..'));
scandir()   is used to get the name of all files and folders in the directory provided.
array_diff(..,array('.','..'))   is used to remove the default '.' and '..' folders.  Then the remaining array is parsed using  a  foreach  loop.


        First assume the item is a file.So delete it using unlink().  If unlink() returns false  the item will be a directory.  So del()   function is called in  recursive manner with the sub folder name ($item).

 
        After the loop has executed rmdir($dir) will call.Now rmdir() can delete the directory
because the directory will be empty.   Hence delete directory with php is done.  

You can also read :-
Extend maximum execution time of php script

Thursday, 24 May 2012

Facebook like pop up window using jquery

This article is discussing pop up window using jquery or popup box using jquery.
Some of you are looking for a code for pop up window in html.     But jquery is the better solution to not only create simple pop up window but also more complicated popup windows.To
modal popup using jquery we use some essential css  too.

Try this :-


code
<html>
<head>
   <style type="text/css">
   #divid
   {
   z-index:5;
   position:absolute;
   width:400px;
   left:200px;
   top:150px;
   border:8px solid #a1a1a1;
   padding:0px 0px;
   background:#FFFFFD;
   border-radius:15px;
  }
  #headid
  {
  background:#6692CD;
  color:#ffffff;
  font-size:18px;
  }
  #shareid
  {
  background-color:#6692CD;
  color:#ffffff;
  font-size:15px;
  }
  </style>

 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){
$("#linkid").mouseenter(function(){
if(!$("#divid").length)
{
$("#bodyid").append("<div id='divid'>"+
"<table width='100%'><tr><td id='headid'>Share this Photo</td></tr>"+
"<tr><td><br><img src='http://mystifyingindia.com/blog/wp-content"+
"/uploads/2010/09/taj_mahal.jpg' width='60' height='50'>"+
"&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspHere come the body of the message..."+
"<br><br></td></tr>"+
"<tr><td align='right'><input type='button' value='Share Photo' id='shareid'>"+
"<input type='button' value='Cancel' onclick='btn_cancel()'></td></tr>"+
"</table></div>"
);
$("#divid").css({"left":window.innerWidth/2-200,"top":window.innerHeight/2-100});
}
});



}

);
</script>
<script type="text/javascript">
function btn_cancel()
{

$("#divid").remove();
}
</script>
</head>

<body id="bodyid">
   <div style='width:290px'>
<a id="linkid"><h3>Mouse over it to see popup window</h3></a>
    </div>


</body>
</html>


Here is the sample screenshot :-

















Here I am actully dynamically include a <div>  with id 'divid' when mouse is move over the text
'Mouse over it to see popup window'.  $("#bodyid").append("<div id='divid'>")   is
used to append the <div> to the body of html  page.

The contents in the pop up box is placed in this div. The css to this div is placed in the css section.
The border-radius property set  the <div> a rounded rectangle .
position:absolue set the pop up box exactly where the top and left is given even if some
elements are also present there.

The top and left positions are calculated just like this
"left":window.innerWidth/2-200 , "top":window.innerHeight/2-100.
window.innerWidth returns the width of browser window.Subtracting 200 from its half
gives the center position of window, because 400 is the predefined width of pop up box.
top position is also calculated just like this.

$("#divid").length returns the number of elements with the id 'divid'.if(!$("#divid").length)
is used to ensure the pop up box is not create when one is existing.

Finally $("#divid").remove() is used to permenently remove the newly added pop up box
from the dom.This is given in the onclick event of cancel button in the pop up box.

You can also read:-
Open a new browser window using javascript

Introducing AJAX with a simple example program 

Very simple Menu using Jquery Beginners Tutorial

Saturday, 28 April 2012

Include a page from url in php


                                   This article is to describe how to include a page from other web site to our php page.
                                php include url is not so simple as include a file in your site. We can edit web pages  by including it to our php page.
     

                                   php include external url  is not use include()  or  require() methods of  php  , which are used for local inclusion of  pages in our site.


    If we want to use that     we may use allow_url_include php for that.
     Here I am using  file_get_contents()   for this purpose.
   
     Code
   
<?php

  $cnt=file_get_contents('http://www.gmail.com');
  echo $cnt;
  echo "<div style=\" position:absolute;left:150px;top:50px \">
  <h1 style=\"color:red\">Successfully included By Sukesh B R
  </h1></div>";

?>


                     Here I am including the Gmail home page.  So give the URL ' http://www.gmail.com ' as
 parameter to file_get_contents() .         The return value from this is stored to the variable
 $cnt.     Then print this using echo statement.


 
                     Hence the Gmail page is displayed just like my local    html page.  Then I include a   <div>    in which a message    'Successfully included By Sukesh B R'       is displayed.I have use little css to display it in the top of gmail page.


Here is a sample screenshot of this page :-




                 



You can add javascript blocks to this page and access the elements of Gmail home page  and make changes in it with your like.You can add any other webpages just like this.


You can also read:- Download image file using PHP

                   Thanks for reading this article.       Please  just tick a response in the Reactions check boxes provided
 under this .

Monday, 23 April 2012

Extend maximum execution time of php script


Hi friends ,
today my discussion is about  extend maximum execution time of php script/page .
OR  solution for Fatal Error:Maximum execution time limit reached  when you run a php page .
OR change the maximum execution time of php script.OR increase the maximum execution time of
php script
.
        We can change the maximum execution time by call a function set_time_limit().
       
       
Syntax

   void set_time_limit ( int $seconds );
    //set_time_limit(300);



                The parameter send to this specifies the maximum execution time in seconds.In the above code the maximum execution time is set to 300 seconds , that is 5 minutes.

This can also achieve by using the function ini_set() , like this ,

   ini_set('max_execution_time', 300);  


                Here also 300 is the maximum execution time in seconds.

Hope that this post is helpful to you.

Thanks by Sukesh B R

You can also read :-
Delete non empty directory in php

Friday, 20 April 2012

Download image file using PHP


Hi friends,
 today my discussion is about how to download an image from an URL using php.OR download picture from the given URL.OR save image file using php.

 Here have two functions used for this:-
     file_get_contents() and file_put_contents()
   
    Code
<?php
set_time_limit(300) ;
$lnk='http://1.bp.blogspot.com/-SZgenQisfQc/TVPnClZOn5I/AAAAAAAABO8/zLFsX4UoFzg/s1600/The-best-top-desktop-dolphin-wallpapers-hd-dolphins-wallpaper-3.jpg';
file_put_contents('image.jpg',
    file_get_contents($lnk));   
?>

   




Code Description
 set_time_limit(300) ;   This statement is used to set the maximum execution time for the php script.It's default value  is 60 seconds.  Set this to 300 seconds allow the time to download the image.
 $lnk holds the URL of a wallpaper image to be download.

     file_get_contents() is used for get the contents from URL. Where file_put_contents() is used
 to write these contents to a file.
           

                 The lnk is given to the parameter to   file_get_contents().  The return data from this and
the name of file to be saved is given to file_put_contents().  Here all these are written in single step.
When you run this script the image will downloaded  to the location where your php page is saved
with the name 'image.jpg'.  To change the download location give it to file_put_contents() parameter
like this file_put_contents( 'imgfolder/img/image.jpg' , '...'  );

Also read this :- Include a page from url in php

Hope that this post is helpful to you.
Thanks By Sukesh B R

Tuesday, 17 April 2012

Add tool tip text to HTML elements



Hi friends ,
Have you Think about giving tool tip text to HTML elements?
Today I am going to discuss add tool tip text to HTML elements.OR add a short descriptions to
links or buttons in HTML
.OR the use of title attribute in HTML.

      Tool tip text is defined as a short description given to a link or button which gives information
about what the link is for.
      title attribute is used to create a tool tip text(Not the <title> tag). Just like other attributes type like this
tiltle="description".

1. For add a tool tip to a link

<a title="Link to Google" href="www.google.com">This is a link</a>


The resultant screenshot is given belove :-







2. For add a tool tip to a Button


<input type="button" title="This is a button"value="Button">


The resultant screenshot is given belove :-

 


3. For add a tooltip to a Textbox :-


<input type="text" title="This is a Textbox">


The resultant screenshot is given belove :-



The title attribute is not valid in: <base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title>.
Hope that this post is helpful to you.
  By Sukesh B R

Friday, 13 April 2012

Pass parameter to another page in PHP


I am discussing How to pass parameters as type GET to another page. OR Pass parameters as GET without using a form.OR Pass parameters through URL.

When we are using a form of method GET the values of text boxes enclosed in the form are
send to the action page through the URL.We can also send values through URL without a form.


If we want to pass a variable to another page when click a link
<a href="target.php?n1=5">Click Here</a>


If we want to pass more than 1 values seperate them with ' & '.
<a href="target.php"?n1=5&n2=10&name=sbr>Click Here</a>


In target.php the values can be retrieved just like form values send as GET method.
That is
$n1=$_GET["n1"];
$n2=$_GET["n2"];
$name=$_GET["name"];






When we want to send values of php variables , these code may be helpful

1.Pass a single value to another page

t1.php
<?php
$n1=5;
?>


<a href="target.php?n1=<?php echo $n1 ;?>">Click Here</a>

target.php
<?php
echo $_GET["n1"];
?>


2.Pass more than one value to another page

t1.php

<?php
$n1=5;
$n2=7;
?>

<a href="target.php?n1=<?php echo $n1 ;?>&n2=<?php echo $n2;?>">Click Here</a>

target.php

<?php
echo $_GET["n1"];
echo $_GET["n2"];
?>

You can see these two examples of using this  method here :-


Change font size of text in HTML page dynamically using  php



Hope that this post is helpful to you.
By Sukesh B R

Thursday, 5 April 2012

ACCESS $_GET , $_POST , $_SESSION using javascript

Hi friends I am going to discuss Access $_GET or $_POST or $_SESSION using javascript.
In other words access parameters send by form as POST or GET method or
Read the session variables in the server using javascript.



    1.Access $_GET values using javascript

Code
<html>


<head>


  <script type="text/javascript">
            var $_GET = <?php echo json_encode($_GET); ?>;
           
            alert($_GET["n1"]); 
  </script>


</head>




         <body>
        <form method="GET">
        <input type="text" name="n1">
        <input type="submit">
        </form>
        </body>




</html>

Code Description

json_encode() is the core function using here.In the javascript section a variable named $_GET
is declared.This variable is assigned with the $_GET array of php page.This is done by this statement :
var $_GET = <?php echo json_encode($_GET); ?>;
Dont forget the semicolon at the end.
All the parameters passed as GET to the page will stored in the variable.These values can be retrived
by their name.That is the name of the textbox in the html page.Here my textbox's name is 'n1'.So I use
$_GET["n1"] to access the value of n1.
save it as a php file(.php extension) and run.



   2.Access $_POST values using javascript

Code
<html>


<head>


  <script type="text/javascript">
            var $_POST = <?php echo json_encode($_POST); ?>;
           
            alert($_POST["n1"]); 
  </script>


</head>




         <body>
        <form method="POST">
        <input type="text" name="n1">
        <input type="submit">
        </form>
        </body>




</html>


Code Description

json_encode()  is the core function using here.In the javascript section a variable named $_POST
is declared.This variable is assigned with the $_POST array of php page.This is done by this statement :
var $_POST = <?php echo json_encode($_POST); ?>;
Dont forget the semicolon at the end.
All the parameters passed as POST to the page will stored in the variable.These values can be retrived
by their name.That is the name of the textbox in the html page.Here my textbox's name is 'n1'.So I use
$_POST["n1"] to access the value of n1.

save it as a php file(.php extension) and run.

 
   3.Access $_SESSION values using javascript


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


<head>


  <script type="text/javascript">
            var $_SESSION = <?php echo json_encode($_SESSION); ?>;
           
            alert($_SESSION["ns"]); 
  </script>


</head>




         <body>
<?php
$_SESSION["ns"]="SESSION_VALUE";
?>
        <form method="POST">
        <input type="text" name="n1">
        <input type="submit">
        </form>
        </body>




</html>

Code Description

json_encode() is the core function using here.
First of all in a php section we call the function session_start().This is for accessing SESSION variable in php.
In the javascript section a variable named $_SESSION  is declared.This variable is assigned with the $_SESSION array of php page.
This is done by this statement :
var $_SESSION = <?php echo json_encode($_SESSION); ?>;
Dont forget the semicolon at the end.
All the SECTION variables  will be stored in the variable $_SESSION.These values can be retrived
by their name.Here my section variable's  name is 'ns'.So I use
$_POST["ns"] to access the value of 'ns'.
save it as a php file(.php extension) and run.

You can also read :-

Thursday, 2 February 2012

Change the text typed in a text box to upper case using CSS

Hi friends ,
Today my discussion is about change the  text typed in a HTML
text box into uppercase
.   It can be simply achieve using a simple CSS
property text-transform.
        We only set the text-transform to uppercase just like this  :
text-transform:uppercase

Here is the sample code
<html>
<body>
<input type="text" style="text-transform:uppercase">
</body>
</html>


Here  the usage of style parameter is inline CSS.   In the style parameter
of <input> contains text-transform:uppercase. It instructs the browser
to transform the text typed in the text box to upper case.

       Other possible values for text-transform parameter are
lowercase and capitalize.
 text-transform:lowercase convert the text typed to lowercase.
 text-transform:capitalize convert the first letter of each word of text typed to uppercase.

       Hope that this post will be helpful to you.
 Thanks by Sukesh B R

Saturday, 14 January 2012

Open a new browser window using javascript

Hi friends,
   Here I am discuss about open a new browser window when click a button
using javascript
.Have you see pop up windows containing advertisements?
We can create like one very easily.
  
   The javascript function used for pop up a new window is window.open().
The syntax for window.open is :
window.open('http://www.google.com','window_name','width=400,height=200');

   In this function first parameter is the URL of the website to be loaded
in the poped up window opened.Here I am use the address of  Google.com.

   The second parameter of open() function is the name of the window.We
can use this name to access the window later.

   The third parameter is using to set the dimensions of the window which is poped up.

Code of a simple form pop up the Google in a new window:

<FORM>
<INPUT type="button" value="Click Me" onClick="window.open('http://www.google.com','Google','height=600,width=600')">
</FORM>



  Here the window.open() function is called in the onclick event of the button in the form.When click in the button , a pop up window with 600 pixel height and 600 pixel width is opened and google.com will load in it in no time.

  In the third parameter we can include more options like the position of the window.We can use the top and left parameters to set the top and left of the window.

<FORM>
<INPUT type="button" value="Click Me" onClick="window.open('http://www.google.com','Google','height=600,width=600,left=0,top=100')">
</FORM>


This code will open a window with 600 pixels height and width and the top left of the window will be (0,100).
But one thing to be noted is that all these are belongs to the third parameter so these are within a single inverter comma('').


We can also specify that which tool bars will appear in our new window just like this
window.open ("http://www.javascript-coder.com", "mywindow","status=yes,toolbar=no");
By this code I am allowing the status bar and disallow toolbar.

  The other values set in the third parameter is as follows :


status     :     The status bar at the bottom of the window.
toolbar    :     The standard browser toolbar, with buttons such as Back and Forward.
location   :     The Location entry field where you enter the URL.
menubar    :    The menu bar of the window
directories:     The standard browser directory buttons, such as What’s New and What’s Cool
resizable  :    Allow/Disallow the user to resize the window.
scrollbars :    Enable the scrollbars if the document is bigger than the window


   windows.close() can be used to close the opened window.
Another thing to be noted is that many browsers block the opening of pop up windows.So inorder to work  the code above explained please unblock the pop up windows in your browser's settings.

I am including a screen shot :


















Thank you to my dear friends.
You can read :-

Facebook like pop up window using jquery


By Sukesh B R

Thursday, 12 January 2012

Multiple submit buttons in a Form in PHP explain with an example

Hi friends, today I am discussing handling multiple submit buttons in a single Form in PHP.
 
According to typical HTML architecture there have one submit button for a Form.When this submit button  is clicked the php page specified by the form action parameter is loaded.

          But some situations we need multiple submit buttons in a single form.In such situations the php page loaded by clicking distinct buttons is same.But the task executed will be different.We can achieve it by isset()  function of PHP.
  
          The syntax for isset() is : isset($_POST["name of submit button in the form"])

We can write the  code for the action page like this:-
 
<?Php
if(isset($_POSt["s1"]))
{
echo "You pressed submit 1";
}

else if(isset($_POSt["s2"]))
{
echo "You pressed submit 2";
}
?>

Where s1 and s2 are the name of submit buttons in the form.

Here I am including a simple calculator example to clear  this concept

This is a screen shot of the program:

 
Source code
calculator.html

<html>
<body>
<form name="f1" method="post" action="sub.php">
Number1 <input type="text" name="n1"></br></br>
Number2 <input type="text" name="n2">
</br></br>
<input type="submit" name="add" value="+">
<input type="submit" name="sub" value="-">
<input type="submit" name="mul" value="*">
<input type="submit" name="div" value="/">
</form>
</body>
</html>

 sub.php 

<?php

if(isset($_POST["add"]))
echo "Sum : ".($_POST["n1"]+$_POST["n2"]);

else if(isset($_POST["sub"]))
echo "Difference : ".($_POST["n1"]-$_POST["n2"]);

else if(isset($_POST["mul"]))
echo "Product : ".($_POST["n1"]*$_POST["n2"]);

else if(isset($_POST["div"]))
echo "Quotient : ".($_POST["n1"]/$_POST["n2"]);
?>


code description:


In calculator.html we can see a form.There have 2 text boxes and 4 submit buttons.The two submit buttons are the
two numbers to perform arithmetic operations.The four submit buttons are for additon,substraction,multiplication and division.
The name of the submit buttons are add,sub,mul,div respectively.

       In sub.php four if else statements are used to determine which submit button is clicked.
 
First if is:
if(isset($_POST["add"]))
Where 'add' is the name of first submit button.isset($_POST["add"])  return TRUE if the submit button clicked is 'add'.If it return true 
echo "Sum : ".($_POST["n1"]+$_POST["n2"]); 
this statement will execute.So the sum of given numbers will be displayed.
If isset() returns FALSE go to the next if statement and check for the click of next submit button.This process will be continued till the clicked button is found.Thus our calculator works properly.

isset() is the standard way to achieve this but we can simply write
if($_POST["add"])
{
echo "Sum : ".($_POST["n1"]+$_POST["n2"]);

for achive the same result.

Hope that this post is helpful to you.Thanks by Sukesh B R

Search This Blog