Tuesday 31 July 2012

simple pagination code in php and mysql


<?php
/*
Place code to connect to your DB here.
*/
// include your code to connect to DB.

$tbl_name=""; //your table name
// How many adjacent pages should be shown on each side?
$adjacents = 3;

/*
  First get total number of rows in data table.
  If you have a WHERE clause in your query, make sure you mirror it here.
*/
$query = "SELECT COUNT(*) as num FROM $tbl_name";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];

/* Setup vars for query. */
$targetpage = "yourfilename.php"; //your file name  (the name of this file)
$limit = 2; //how many items to show per page
$page = $_GET['page'];
if($page)
$start = ($page - 1) * $limit; //first item to display on this page
else
$start = 0; //if no page var is given, set start to 0

/* Get data. */
$sql = "SELECT column_name FROM $tbl_name LIMIT $start, $limit";
$result = mysql_query($sql);

/* Setup page vars for display. */
if ($page == 0) $page = 1; //if no page var is given, default to 1.
$prev = $page - 1; //previous page is page - 1
$next = $page + 1; //next page is page + 1
$lastpage = ceil($total_pages/$limit); //lastpage is = total pages / items per page, rounded up.
$lpm1 = $lastpage - 1; //last page minus 1

/*
Now we apply our rules and draw the pagination object.
We're actually saving the code to a variable in case we want to draw it more than once.
*/
$pagination = "";
if($lastpage > 1)
{
$pagination .= "<div class=\"pagination\">";
//previous button
if ($page > 1)
$pagination.= "<a href=\"$targetpage?page=$prev\">« previous</a>";
else
$pagination.= "<span class=\"disabled\">« previous</span>";

//pages
if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
}
}
elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some
{
//close to beginning; only hide later pages
if($page < 1 + ($adjacents * 2))
{
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
}
$pagination.= "...";
$pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
$pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";
}
//in middle; hide some front and some back
elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
{
$pagination.= "<a href=\"$targetpage?page=1\">1</a>";
$pagination.= "<a href=\"$targetpage?page=2\">2</a>";
$pagination.= "...";
for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
}
$pagination.= "...";
$pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
$pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";
}
//close to end; only hide early pages
else
{
$pagination.= "<a href=\"$targetpage?page=1\">1</a>";
$pagination.= "<a href=\"$targetpage?page=2\">2</a>";
$pagination.= "...";
for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
}
}
}

//next button
if ($page < $counter - 1)
$pagination.= "<a href=\"$targetpage?page=$next\">next »</a>";
else
$pagination.= "<span class=\"disabled\">next »</span>";
$pagination.= "</div>\n";
}
?>

<?php
while($row = mysql_fetch_array($result))
{

// Your while loop here

}
?>

<?php echo $pagination;?>

send php mail with submit form data and file attachment

careers.html

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 


<title>Untitled Document</title> 
</head> 

<body style="padding:3px; margin:0px;" bgcolor="#FFFFFF"> 
<table cellpadding="0" cellspacing="0" border="0" width="440"> 
    
    <tr><td style="height:10px"></td></tr> 
    <tr> 
      <td colspan="2" style="text-align:justify; line-height:15px;" class="body"> 
        
      <form name="frm" method="POST" action="careersuccess.php" enctype="multipart/form-data"> 
      <table cellpadding="0" cellspacing="0" border="0" width="100%"> 
          <tr> 
            <td width="23%" class="body"> Name</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><input type="text" name="strname" class="textfield"></td> 
        </tr> 
        <tr><td style="height:3px"></td></tr> 
        <tr> 
            <td width="23%" class="body"> Address</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><textarea cols="16" name="straddress"></textarea></td> 
        </tr> 
        <tr><td style="height:3px"></td></tr> 
        <tr> 
            <td width="23%" class="body"> City</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><input type="text" name="strcity" class="textfield"></td> 
        </tr> 
        <tr><td style="height:3px"></td></tr> 
        <tr> 
            <td width="23%" class="body"> State</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><input type="text" name="strstate" class="textfield"></td> 
        </tr> 
        <tr><td style="height:3px"></td></tr> 
        <tr> 
            <td width="23%" class="body"> Contact No</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><input type="text" name="strno" class="textfield"></td> 
        </tr> 
        <tr><td style="height:3px"></td></tr> 
        <tr> 
            <td width="23%" class="body"> Email</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><input type="text" name="stremail" class="textfield"></td> 
        </tr> 
        <tr><td style="height:3px"></td></tr> 
        <tr> 
            <td width="23%" class="body"> Comments</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><textarea cols="16" name="strcomments"></textarea></td> 
        </tr> 
        <tr><td style="height:3px"></td></tr> 
        <tr> 
            <td width="23%" class="body"> Resume</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><input type="file" name="strresume"></td> 
        </tr> 
        <tr><td style="height:10px"></td></tr> 
        <tr> 
            <td colspan="3" align="center"> 
                <input type="submit" value="Send" name="submit" onClick="return validate();"> <input type="reset" value="Reset" name="reset"> 
            </td> 
        </tr> 
        
      </table>    
     </form> 

</td> 
    </tr> 
    <tr> 
      <td colspan="2" align="center"> </td> 
  </tr> 
    </table> 
</body> 
</html>




careersuccess.php

<?php 
      
                      
       $strname
=ucfirst($_REQUEST["strname"]); 
    
$straddress=ucfirst($_REQUEST["straddress"]); 
    
$strcity=ucfirst($_REQUEST["strcity"]); 
    
$strstate=ucfirst($_REQUEST["strstate"]);        
        
       
$phone=$_REQUEST["strno"]; 
       if(
$phone != ""){ $strno=$phone; } else { $strno="-"; }    
        
    
$stremail=$_REQUEST["stremail"];    
    
$strcomments=ucfirst($_REQUEST["strcomments"]); 

    
    
$filename=$_FILES["strresume"]["name"]; 
    
$filetype=$_FILES["strresume"]["type"]; 
    
$filesize=$_FILES["strresume"]["size"]; 
    
$filetemp=$_FILES["strresume"]["tmp_name"]; 


        
    if(
$filetype=="application/octet-stream" or $filetype=="text/plain" or $filetype=="application/msword") 
    { 
    
        
$message= ' 
    
    
            <table cellspacing="0" cellpadding="8" border="0" width="400"> 
            <tr> 
                <td colspan="2"></td> 
            </tr> 
            <tr bgcolor="#eeeeee"> 
                <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;"><strong>Name</strong></td> 
                <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;">'
.$strname.'</td> 
            </tr> 
            <tr><td colspan="2" style="padding:0px;"><img src="images/whitespace.gif" alt="" width="100%" height="1" /></td></tr> 
            <tr bgcolor="#eeeeee"> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;"><strong>Address</strong></td> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;">'
.$straddress.'</td> 
              </tr> 
            <tr><td colspan="2" style="padding:0px;"><img src="images/whitespace.gif" alt="" width="100%" height="1" /></td></tr> 
            <tr bgcolor="#eeeeee"> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;"><strong>City</strong></td> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;">'
.$strcity.'</td> 
              </tr> 
              <tr><td colspan="2" style="padding:0px;"><img src="images/whitespace.gif" alt="" width="100%" height="1" /></td></tr> 
            <tr bgcolor="#eeeeee"> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;"><strong>State</strong></td> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;">'
.$strstate.'</td> 
              </tr> 
              <tr><td colspan="2" style="padding:0px;"><img src="images/whitespace.gif" alt="" width="100%" height="1" /></td></tr> 
            <tr bgcolor="#eeeeee"> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;"><strong>Contact No.</strong></td> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;">'
.$strno.'</td> 
              </tr> 
            <tr><td colspan="2" style="padding:0px;"><img src="images/whitespace.gif" alt="" width="100%" height="1" /></td></tr> 
            <tr bgcolor="#eeeeee"> 
                <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;"><strong>Email</strong></td> 
                <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;">'
.$stremail.'</td> 
            </tr> 
            <tr><td colspan="2" style="padding:0px;"><img src="images/whitespace.gif" alt="" width="100%" height="1" /></td></tr> 
            
            <tr bgcolor="#eeeeee"> 
                <td colspan="2" style="font-family:Verdana, Arial; font-size:11px; color:#333333;"><strong>Comments</strong></td> 
            </tr>                
            <tr bgcolor="#eeeeee"> 
                <td colspan="2" style="font-family:Verdana, Arial; font-size:11px; color:#333333;">'
.$strcomments.'</td> 
            </tr>                
                                    
            <tr><td colspan="2" style="padding:0px;"><img src="images/whitespace.gif" alt="" width="100%" height="1" /></td></tr> 
         </table> 


            

'
; 

    
// MAIL SUBJECT 

    
$subject = "Mail with doc file attachment"; 
    
    
// TO MAIL ADDRESS 
    
    
    
$to="to@mail.com"; 
/* 
    // MAIL HEADERS 
                        
    $headers  = "MIME-Version: 1.0\n"; 
    $headers .= "Content-type: text/html; charset=iso-8859-1\n"; 
    $headers .= "From: Name <name@name.com>\n"; 

*/ 
  


    // MAIL HEADERS with attachment 

    
$fp = fopen($strresume, "rb"); 
    
$file = fread($fp, $strresume_size); 

    
$file = chunk_split(base64_encode($file)); 
    
$num = md5(time()); 
    
        
//Normal headers 

    
$headers  = "From: Name<name@name.com>\r\n"; 
       
$headers  .= "MIME-Version: 1.0\r\n"; 
       
$headers  .= "Content-Type: multipart/mixed; "; 
       
$headers  .= "boundary=".$num."\r\n"; 
       
$headers  .= "--$num\r\n"; 

        
// This two steps to help avoid spam    

    
$headers .= "Message-ID: <".$now." TheSystem@".$_SERVER['SERVER_NAME'].">\r\n"; 
    
$headers .= "X-Mailer: PHP v".phpversion()."\r\n";          

        
// With message 
        
    
$headers .= "Content-Type: text/html; charset=iso-8859-1\r\n"; 
       
$headers .= "Content-Transfer-Encoding: 8bit\r\n"; 
       
$headers .= "".$message."\n"; 
       
$headers .= "--".$num."\n" 

        
// Attachment headers 

    
$headers  .= "Content-Type:".$strresume_type." "; 
       
$headers  .= "name=\"".$strresume_name."\"r\n"; 
       
$headers  .= "Content-Transfer-Encoding: base64\r\n"; 
       
$headers  .= "Content-Disposition: attachment; "; 
       
$headers  .= "filename=\"".$strresume_name."\"\r\n\n"; 
       
$headers  .= "".$file."\r\n"; 
       
$headers  .= "--".$num."--"; 

    
    
    
// SEND MAIL 
        
       
@mail($to, $subject, $message, $headers); 
    

     
fclose($fp); 

    echo 
'<font style="font-family:Verdana, Arial; font-size:11px; color:#333333; font-weight:bold">Attachment has been sent Successfully.<br /></font>'; 
} 
else 
    { 
        echo 
'<font style="font-family:Verdana, Arial; font-size:11px; color:#F3363F; font-weight:bold">Wrong file format. Mail was not sent.</font>'; 
        
//echo "<script>window.location.href='careers.html';</script>"; 
    
} 
?>

How to Use a PHP Session ,assign form values to session variable


A session is a way to store information (in the form of variables) to be used across multiple pages. Unlike a cookie, specific variable information is not stored on the users computer. It is also unlike other variables in the sense that we are not passing them individually to each new page, but instead retrieving them from the session we open at beginning of each page.

Call this code mypage.php

 <?php
 // this starts the session
 session_start();

 // this sets variables in the session
 $_SESSION['color']='red';
 $_SESSION['size']='small';
 $_SESSION['shape']='round';
 print "Done";
 ?>

The first thing we do with this code, is open the session using session_start(). We then set our first session variables (color, size and shape) to be red, small and round respectively.

Just like with our cookies, the session_start() code must be in the header and you can not send anything to the browser before it. It's best to just put it directly after the <?php to avoid potential problems.

So how will it know it's me? Most sessions set a cookie on your computer to uses as a key... it will look something like this: 350401be75bbb0fafd3d912a1a1d5e54. Then when a session is opened on another page, it scans your computer for a key. If there is a match, it accesses that session, if not it starts a new session for you.

Now we are going to make a second page. We again will start with session_start() (we need this on every page) - and we will access the session information we set on our first page. Notice we aren't passing any variables, they are all stored in the session.

Call this code mypage2.php

 <?php
 // this starts the session
 session_start();

 // echo variable from the session, we set this on our other page
 echo "Our color value is ".$_SESSION['color'];
 echo "Our size value is ".$_SESSION['size'];
 echo "Our shape value is ".$_SESSION['shape'];
 ?>

All of the values are stored in the $_SESSION array, which we access here. Another way to show this is to simply run this code:

 <?php
 session_start();
 Print_r ($_SESSION);
 ?>

You can also store an array within the session array. Let's go back to our mypage.php file and edit it slightly to do this:

 <?php
 session_start();

 // makes an array
 $colors=array('red', 'yellow', 'blue');
 // adds it to our session
 $_SESSION['color']=$colors;
 $_SESSION['size']='small';
 $_SESSION['shape']='round';
 print "Done";
 ?>

Now let's run this on mypage2.php to show our new information:

 <?php
 session_start();
 Print_r ($_SESSION);
 echo "<p>";

 //echo a single entry from the array
 echo $_SESSION['color'][2];
 ?>

 <?php
 // you have to open the session to be able to modify or remove it
 session_start();

 // to change a variable, just overwrite it
 $_SESSION['size']='large';

 //you can remove a single variable in the session
 unset($_SESSION['shape']);

 // or this would remove all the variables in the session, but not the session itself
 session_unset();

 // this would destroy the session variables
 session_destroy();
 ?>

Sunday 29 July 2012

why use php for web development


 Open source: PHP is a server side open source language which means it is available for free. It can be used on different platforms such as UNIX, Linux & Windows and considered the suitable language to develop dynamic sites.

Dynamic language: PHP is used in close correlation with HTML for displaying dynamic data and other elements on a web page. The code available within the delimiters is parsed and all other information is ignored by PHP and sent directly to output.

Less use of resources: PHP and the related procedures do not require too much from system resources. The processes and functions load as well as execute quickly since PHP makes use of Apache modules developed in C coding language.

Dynamic CMS: Development using PHP has made management of content on a web site very simple as entire content on the web site is kept in a database server and fetched by developers as and when required.

1. Ease of use

As stated above, this language has proven to many, to be very easy to learn, very straight-forward. The language rules are not as strict as many common languages of now days, such as C++, Java etc. Any newcomer to the world of PHP will get the hang of this language very quickly on my opninion.

2. Integrates with HTML, CSS, javascript, ajax, jquery very well.

When speaking of web development, there is no need to create workarounds to be able to display an HTML page when using PHP. All you have to do is place the HTML, CSS, js, etc… within the file and you are good to go.

3. Well documented

Nothing is complete if it lacks documentation. This language contains their full manual online, and accessible to everyone in need of it. You need to learn something you have never done before? Just google it and you will definately find some crazy person that already went through the hassle for you, and is willing to help you out at the same time.

4. Great community

Our communities are huge! The people have supported this language from the very start. Versed in every aspect, you can see how people strive to get more out of this simple language (yet powerful). This being open source, has the advantage that everyone can take a glance at it. That being said, with more exposure, the more opportunity this has of growing. Believe me, this has grown since the beggining, and it will keep growing.

5. Updated regularly (security etc, solid platform).

Great technology needs to be updated constantly. The team at PHP.net have done a tremendous job in keeping their language up to date with all the bugs that have been found so far. Also, adding new features every once in a while to make our lives as programmers a bit much easier.

6. Database communication is excellent

PHP is known to have a variety of database support. It has enough flavors to satisfy most individual needs. Here I found a list of supported databases so far. I’m not sure how accurate it is, but its good enough.

http://phplens.com/adodb/supported.databases.html

7. Trend, a lot of people use it (widely used, for open source projects like WP, Joomla, PHPBB, etc.)

This language has become very trendy. A lot of web developers prefer using PHP. (Note: I said a lot prefer, not all.) If you decide to start a new career path using PHP, then you will most certainly have a place to go. The job market is stacking with PHP developer roles, and PHP leads, etc. This is an actual fact, due to the reports from craigslist, stating that the job growth for PHP web developer has increased within the past year. Also, there are a lot of open source projects like WordPress, Joomla, Drupal to mention a few, and companies are using these more and more each day.

8. Usability

One of the best things is that applications done within PHP are cross platform. They are indipendently ran on a server, and doesn’t matter what type of Operating system you are using, it is likely to run. In some cases you will just need to add a few conditions and manipulate the design a little bit, but having to create a new one from scratch, just because there is no compatibility, negatory!

9. Best of all, its free!

You definately can’t go wrong with FREE! You know the old saying, “If it’s free, it’s for me!”. Some people prefer to pay for some web server, that will cost thousands of dollars to maintain up to date. Not with PHP though, you can install a free operating system (linux, unix), that is also very well documented, and have PHP installed in it, configured, and maintainable for much lower cost than any other type of OS.

Some other features of PHP development include:

    Easy access to coding libraries
    Open source programming
    Availability of server interfaces
    Use of different databases such as Oracle, MySQL, PostgreSQL, etc
    Similarity to Java and C
    Platform compatibility

Friday 27 July 2012

most useful array function in php



Function
Explanation
Example
sizeof($arr)
This function returns the number of elements in an array.
Use this function to find out how many elements an array contains; this information is most commonly used to initialize a loop counter when processing the array.
Code:
$data = array("red", "green", "blue");

echo "Array has " . sizeof($data) . " elements";
?>

Output:
Array has 3 elements
array_values($arr)
This function accepts a PHP array and returns a new array containing only its values (not its keys). Its counterpart is the array_keys() function.
Use this function to retrieve all the values from an associative array.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_values($data));
?>

Output:
Array
(
[0] => Holmes
[1] => Moriarty
)
array_keys($arr)
This function accepts a PHP array and returns a new array containing only its keys (not its values). Its counterpart is the array_values() function.
Use this function to retrieve all the keys from an associative array.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_keys($data));
?>

Output:
Array
(
[0] => hero
[1] => villain
)
array_pop($arr)
This function removes an element from the end of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_pop($data);
print_r($data);
?>

Output:
Array
(
[0] => Donald
[1] => Jim
)
array_push($arr, $val)
This function adds an element to the end of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_push($data, "Harry");
print_r($data);
?>

Output:
Array
(
[0] => Donald
[1] => Jim
[2] => Tom
[3] => Harry
)
array_shift($arr)
This function removes an element from the beginning of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_shift($data);
print_r($data);
?>

Output:
Array
(
[0] => Jim
[1] => Tom
)
array_unshift($arr, $val)
This function adds an element to the beginning of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_unshift($data, "Sarah");
print_r($data);
?>

Output:
Array
(
[0] => Sarah
[1] => Donald
[2] => Jim
[3] => Tom
)
each($arr)
This function is most often used to iteratively traverse an array. Each time each() is called, it returns the current key-value pair and moves the array cursor forward one element. This makes it most suitable for use in a loop.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
while (list($key, $value) = each($data)) {
echo "$key: $value \n";
}
?>

Output:
hero: Holmes
villain: Moriarty
sort($arr)
This function sorts the elements of an array in ascending order. String values will be arranged in ascending alphabetical order.
Note: Other sorting functions include asort(), arsort(), ksort(), krsort() and rsort().
Code:
$data = array("g", "t", "a", "s");
sort($data);
print_r($data);
?>

Output:
Array
(
[0] => a
[1] => g
[2] => s
[3] => t
)
array_flip($arr)
The function exchanges the keys and values of a PHP associative array.
Use this function if you have a tabular (rows and columns) structure in an array, and you want to interchange the rows and columns.
Code:
$data = array("a" => "apple", "b" => "ball");
print_r(array_flip($data));
?>

Output:
Array
(
[apple] => a
[ball] => b
)
array_reverse($arr)
The function reverses the order of elements in an array.
Use this function to re-order a sorted list of values in reverse for easier processing—for example, when you're trying to begin with the minimum or maximum of a set of ordered values.
Code:
$data = array(10, 20, 25, 60);
print_r(array_reverse($data));
?>

Output:
Array
(
[0] => 60
[1] => 25
[2] => 20
[3] => 10
)
array_merge($arr)
This function merges two or more arrays to create a single composite array. Key collisions are resolved in favor of the latest entry.
Use this function when you need to combine data from two or more arrays into a single structure—for example, records from two different SQL queries.
Code:
$data1 = array("cat", "goat");
$data2 = array("dog", "cow");
print_r(array_merge($data1, $data2));
?>

Output:
Array
(
[0] => cat
[1] => goat
[2] => dog
[3] => cow
)
array_rand($arr)
This function selects one or more random elements from an array.
Use this function when you need to randomly select from a collection of discrete values—for example, picking a random color from a list.
Code:
$data = array("white", "black", "red");
echo "Today's color is " . $data[array_rand($data)];
?>

Output:
Today's color is red
array_search($search, $arr)
This function searches the values in an array for a match to the search term, and returns the corresponding key if found. If more than one match exists, the key of the first matching value is returned.
Use this function to scan a set of index-value pairs for matches, and return the matching index.
Code:
$data = array("blue" => "#0000cc", "black" => "#000000", "green" => "#00ff00");
echo "Found " . array_search("#0000cc", $data);
?>

Output:
Found blue
array_slice($arr, $offset, $length)
This function is useful to extract a subset of the elements of an array, as another array. Extracting begins from array offset $offset and continues until the array slice is $length elements long.
Use this function to break a larger array into smaller ones—for example, when segmenting an array by size ("chunking") or type of data.
Code:
$data = array("vanilla", "strawberry", "mango", "peaches");
print_r(array_slice($data, 1, 2));
?>

Output:
Array
(
[0] => strawberry
[1] => mango
)
array_unique($data)
This function strips an array of duplicate values.
Use this function when you need to remove non-unique elements from an array—for example, when creating an array to hold values for a table's primary key.
Code:
$data = array(1,1,4,6,7,4);
print_r(array_unique($data));
?>

Output:
Array
(
[0] => 1
[3] => 6
[4] => 7
[5] => 4
)
array_walk($arr, $func)
This function "walks" through an array, applying a user-defined function to every element. It returns the changed array.
Use this function if you need to perform custom processing on every element of an array—for example, reducing a number series by 10%.
Code:
function reduceBy10(&$val, $key) {
$val -= $val * 0.1;
}

$data = array(10,20,30,40);
array_walk($data, 'reduceBy10');
print_r($data);
?>

Output:
Array
(
[0] => 9
[1] => 18
[2] => 27
[3] => 36
)

Wednesday 25 July 2012

disable f12 key javascript

 use this code to head tag


<script language="JavaScript">

//////////F12 disable code////////////////////////
    document.onkeypress = function (event) {
        event = (event || window.event);
        if (event.keyCode == 123) {
           //alert('No F-12');
            return false;
        }
    }
    document.onmousedown = function (event) {
        event = (event || window.event);
        if (event.keyCode == 123) {
            //alert('No F-keys');
            return false;
        }
    }
document.onkeydown = function (event) {
        event = (event || window.event);
        if (event.keyCode == 123) {
            //alert('No F-keys');
            return false;
        }
    }
/////////////////////end///////////////////////
</script>
Shoes

Disable Ctrl Key, Right click and F12

Hi ,
Just copy and paste this code and save your file.

<!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>Disable Ctrl Key, Right click and F12 </title>
<script language="JavaScript">

//////////F12 disable code////////////////////////
    document.onkeypress = function (event) {
        event = (event || window.event);
        if (event.keyCode == 123) {
           //alert('No F-12');
            return false;
        }
    }
    document.onmousedown = function (event) {
        event = (event || window.event);
        if (event.keyCode == 123) {
            //alert('No F-keys');
            return false;
        }
    }
document.onkeydown = function (event) {
        event = (event || window.event);
        if (event.keyCode == 123) {
            //alert('No F-keys');
            return false;
        }
    }
/////////////////////end///////////////////////


//Disable right click script
//visit http://www.rainbow.arch.scriptmania.com/scripts/
var message="Sorry, right-click has been disabled";
///////////////////////////////////
function clickIE() {if (document.all) {(message);return false;}}
function clickNS(e) {if
(document.layers||(document.getElementById&&!document.all)) {
if (e.which==2||e.which==3) {(message);return false;}}}
if (document.layers)
{document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}
else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}
document.oncontextmenu=new Function("return false")
//
function disableCtrlKeyCombination(e)
{
//list all CTRL + key combinations you want to disable
var forbiddenKeys = new Array('a', 'n', 'c', 'x', 'v', 'j' , 'w');
var key;
var isCtrl;
if(window.event)
{
key = window.event.keyCode;     //IE
if(window.event.ctrlKey)
isCtrl = true;
else
isCtrl = false;
}
else
{
key = e.which;     //firefox
if(e.ctrlKey)
isCtrl = true;
else
isCtrl = false;
}
//if ctrl is pressed check if other key is in forbidenKeys array
if(isCtrl)
{
for(i=0; i<forbiddenKeys.length; i++)
{
//case-insensitive comparation
if(forbiddenKeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase())
{
alert('Key combination CTRL + '+String.fromCharCode(key) +' has been disabled.');
return false;
}
}
}
return true;
}
</script>
</head>
<body onkeypress="return disableCtrlKeyCombination(event);" onkeydown="return disableCtrlKeyCombination(event);">
Press ctrl and you can check various key is disable with CTRL. like  — 'a', 'n', 'c', 'x', 'v', 'j' , 'w' Just add key in above the array and disable key as you want.
</body>
</html>

Tuesday 24 July 2012

disable past dates in datepicker jquery

In this blog I will show you how to disable all the past dates (less than or older than today) of jQuery Datepicker. To accomplish it I have used the minDate property of the jQuery datepicker and set it to current date to make that happen.

<script type="text/javascript">
                            $(function () {
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('#deliveron').datepicker({
minDate: new Date(currentYear, currentMonth, currentDate)

});
});
                           
                                                       </script>

Adding label tabs to navigation bar

1. Label your posts.
Label your posts according to subjects or categories (if you haven’t by now done so). This is pretty basic, However, if you don’t have the slightest thought what a label is or don’t know how to apply it, read How do I label my posts?.

You can also apply a label to multiple posts at once.

2. Now get the label URL.
You can get the URL to a label-search page by right-clicking on the hyper-linked label. in Chrome select “Copy link address”, and if you are using Internet Explorer, select “Properties” and copy the link from there.
You can usually find the labels at the bottom of your post and in Labels gadget if you have a Labels gadget installed. If you don’t see any label, you can always construct the URL yourself.

A  URL follows the format below:
http://YOURBLOGNAME howtotipsandtrick.blogspot.com/search/label/YOURLABEL PCTools
For a multiple word label such as "YOUR LABEL", you need to replace the space between words with %20, like so: YOUR%20LABEL. Labels are case sensitive; make sure you enter the correct letter case.

Example:
This is the URL for BloggerSentral’s “SEO and traffic” label. Clicking it will take you to a page showing all posts that fall under that label (opens in new tab/window):
http://www.bloggersentral.com/search/label/SEO%20and%20traffic

3. Add the tab with the label URL
The technique of adding the tab is different depending on the type of widget used for the horizontal navigation bar.

To add the tab to the Pages gadget, follow this tutorial: Adding non-page links to Pages/PageList gadget.
If your tab uses a LinkList gadget, enter the URL into “New Site URL” text box

Integrating ICICI Payment Gateway in Linux with PHP



1.Download the SFA files from the ICICI merchant area and extract on the web server under ICICI folder.
2.Copy the ICICI JAR files from “SFA_Dependencies” folder to the following folders
• JAR Files to copy: cryptix32.jar, jcert.jar, jnet.jar, jsse.jar, servlet.jar, sfa.jar
• Copied jar files to  /usr/share/tomcat5/webapps/JavaBridge/WEB-INF/lib/ from
/var/www/ yourdomainname.com/httpdocs/ICICI/SFA_Dependencies [run this stape after installation of
JavaBridge]
• Reset permissions to these files to tomcat:tomcat under the lib folder
• Also copy the jar files to /usr/share/tomcat5/common/lib folder
• Change the owned and group of copied files as per the existing folder owner (Optional and ensure having 777
permissions on the above folder).3. Download JavaBridge from below URL
•   http://sourceforge.net/projects/php-java-bridge/files/Binary%20package/php-java-bridge_6.2.1/php-javabridge_6.2.1_documentation.zip/download
Install JavaBridge with the following steps:
• Deploy all file in apache server. Please extract jar file from javabridge.war, after extracting war file search for
Javabridge.jar file which will be there WEBINF/lib.
• Please extract jar file from javabridge.war and run using below command.
• java -jar JavaBridge.jar
• After that one popup window will appear for port detail. Please select port 8080 and click on ok button.
• If you are using CUI (character user interface) interface then need to run mentioned command. Please run
mentioned command and let me know output.
• java -jar /usr/lib/php/modules/JavaBridge.jar HTTP_LOCAL:8080 3 JavaBridge.log
Copy java folder which is there in Java Bridge\META-INF under the TestPages folder on the server.
Kindly make the changes in testjava.php ---------> include_once("java/Java.inc")  
Note: J should be in uppercase in Java.inc
http://yourdomainname.com/ICICI/SFAClient/TestPages/testjava.php --> to check Java Bridge Installation.4. Edit php.ini files with below lines.
[java]
java.hosts = 127.0.0.1:8080
java.servlet = On,Off,User as per the prevelant scenario.
java.log_file="/home/java_bridge.log"
;;;;;;;;;;;;;;;;;;;
; Module Settings ;
;;;;;;;;;;;;;;;;;;;
java.classpath = /usr/share/tomcat5/webapps/JavaBridge/WEB- INF/lib/cryptix32.jar;
/usr/share/tomcat5/webapps/JavaBridge/WEB-INF/lib/jcert.jar;
/usr/share/tomcat5/webapps/JavaBridge/WEB-INF/lib/jnet.jar;
/usr/share/tomcat5/webapps/JavaBridge/WEB-INF/lib/jsse.jar;
/usr/share/tomcat5/webapps/JavaBridge/WEB- INF/lib/servlet.jar;
/usr/share/tomcat5/webapps/JavaBridge/WEB-INF/lib/sfa.jar;
Note: - Latest JavaBridge 5.4.2 does not require you to set the classpath in the php.ini file unlike the  earlier versions.
              Above highlighted path is example path kindly set as per your system path.
  5.  Place below jar files in class path
   a) cryptix32.jar
   b) jcert.jar
   c) jnet.jar
   d) servlet.jar
   e) jsse.jar
   f)  sfa.jar
If you are not very sure of this you could always put the .jar files in $JAVA_HOME$/jre/lib/ext folder, which is class path by
default.CLASSPATH=$CLASSPATH:/usr/share/tomcat5/webapps/JavaBridge/WEB-INF/lib/cryptix32.jar;
CLASSPATH=$CLASSPATH:/usr/share/tomcat5/webapps/JavaBridge/WEB-INF/lib/jnet.jar;
CLASSPATH=$CLASSPATH:/usr/share/tomcat5/webapps/JavaBridge/WEB-INF/lib/servlet.jar;
CLASSPATH=$CLASSPATH:/usr/share/tomcat5/webapps/JavaBridge/WEB-INF/lib/sfa.jar;
CLASSPATH=$CLASSPATH:/usr/share/tomcat5/webapps/JavaBridge/WEB-INF/lib/jcert.jar;
CLASSPATH=$CLASSPATH:/usr/share/tomcat5/webapps/JavaBridge/WEB-INF/lib/jsse.jar;
• # env to check the environment variables.
• Once above jar file is set Restart Application server.
Note: - Above highlighted path is example path kindly set as per your system path.
6. Extract the sfa.jar file in “SFA_Dependencies” and edit the sfa.properties file with the following entries:
verbose=true
Key.Directory=/var/www/key
OS.Type=UNIX
traceLog=/var/log/tomcat5/icici.log
Stop Apache or  Tomcat and then copy the following key files to the /var/www/key directory:
• 0000XXXX.key
7. Update the TestSSL.php page change Merchant ID & Response URL and use the updated file:
$oMerchant-
>setMerchantDetails(“0000XXXX”,”0000XXXX”,”0000XXXX”,”193.545.34.33,rand().”",”Ord123,”http://10.10.10.147:8756/S
FAResponse.php”,”POST”,”INR”,”INV123,”req.Sale”,”100,”",”Ext1,”true”,”Ext3,”Ext4,”Ext5);
 In SFAResponse.php and “PostLibPHP.php” file on line 2 change
             ‘ require_once(“java/Java.php”);’ to ‘ require_once(“java/Java.inc”);’
Change the key path as per your system path in SFAResponse.php
 $strMerchantId="0000XXXX";
             $astrFileName="var/www/key/0000XXXX.key";
Execute TestSSL
• http://domainname.com/ICICI/SFAClient/TestPages/TestSsl.php ---> will redirect to ICICI Payseal Page