Go back to previous page using javascript

If you like to enable your visitors to go back to the previous page by clicking back button in your websites. use this code

Copy and paste this code into your HTML
<form>
<input type="button" value="Back to Previous Page" onClick="javascript: history.go(-1)">
</form>

Go Back to previous page with a simple link

<a href="javascript: history.go(-1)">Back</a>

How to upload joomla site to server using ftp?

1. Upload your newly created Joomla site to the server via FTP.
2. Create the MySql Database.
3. Edit the configuration.php file and set the newly created server database name, username, password correctly. U don't have to change the host name usually its "localhost" but if your server MySql is belong to a different IP u need to put that ip in the hostname.
4. upload/replace the configuration.php file.
5. Export your Local Joomla(PC) database (e.g using PhpMyadmin) and import the same in your Server Database.
Its all done......

simple CAPTCHA example in PHP

A CAPTCHA is a challenge response test used on computers to check if the user is human.A common kind of CAPTCHA that is used on websites requires that the visitor type the letters and numbers of a distorted image. This method is based on the fact that is difficult for computers to extract the text from the image while it is very easy for humans.


put a small  image in the same directory where both file exist then the image name must be img.jpg

Send Mail with Submitted Form Data and a File Attachment in php

The given PHP example helps you to send the mail with submitted form data and file attachment.The attached file should be .doc or .txt (you can modify it).You only need to change the 'To' email address from sendmail.php file.

Send an Email with Multiple Attachments in PHP

The below PHP example helps you to send an email with multiple attachment file.

sendmail.html

How to redirect a Page Using Javascript in php

If you don't like using header() as I like to redirect page mid-page. This is implemented using
Javascript written through PHP function. Has a die() function at the end for people who has
disabled their Javascript in their browser.

<?php
function redirect($new_location){
   echo ("<script type='text/javascript'>
   document.location.replace('$new_location');
   </script> ");
   die();
}
?>

current Yahoo userid status in php

The given PHP example returns the current Yahoo status(online/offline) against a yahoo userid.

<?php
function yahoo($id){
    $url = 'http://opi.yahoo.com/online?u=';
    $data = file_get_contents($url . $id);
    if (trim(strtolower(strip_tags($data))) != 'user not specified.') {
        return (strlen($data) == 140) ? 'online' : 'offline';
    } else {
    return trim(strip_tags($data));
    }
    }
echo yahoo("yahoo_userid");
?>

How to make alternate row colours in php

The given PHP example helps you to display the row with alternate colours.

<?php
$array_data[] = array("ID", "Name", "Email");
$array_data[] = array("1", "Bill", "bill@phpmoot.com");
$array_data[] = array("2", "Jan", "jan@test.com");
$array_data[] = array("3", "Imran", "imran@phpmoot.com");
$array_data[] = array("4", "Qasim", "qasim@test.com");
$array_data[] = array("5", "phpMoot", "test@phpmoot.com");
// Header rows
print ("<table border='1' width='100%'>");
$alternate = "2"; // number of alternating rows
foreach($array_data as $key => $val){
if ($alternate == "1") {
$colour = "#66CCFF";
$alternate = "2";
}
else {
$colour = "#CCCCFF";
$alternate = "1";
}

print ("<tr bgcolor='$colour'><td>".$val[0]."</td><td>".$val[1]."</td><td>".$val[2]."</td></tr>
");
}
print ("</table>");
?>

PHP – Multiple File Upload on server

The given PHP example helps you to upload the multiple files on server at once.


<?php

$file_to_upload = 5;
$file_dir  = "./"; // directory where you want to upload the files, and don't forget to CHMOD 777 to this folder
if ($_POST) {
  for ($i=0;$i<$file_to_upload;$i++) {
   if (trim($_FILES['myfiles']['name'][$i])!="") {
     $newfile = $file_dir.$_FILES['myfiles']['name'][$i];
     move_uploaded_file($_FILES['myfiles']['tmp_name'][$i], $newfile);
     $j++;
   }
  }
}
if (isset($j)&&$j>0) print "Your file(s) has been uploaded.<br>";
print "<form method='post' enctype='multipart/form-data'>";
for($i=0;$i<$file_to_upload;$i++) {
  print "<input type='file' name='myfiles[]' size='30'><br>";
}
print "<input type='submit' name='action' value='Upload'>";
print "</form>";
?>

A Simple Password Authentication Form - PHP

The given PHP example helps you to make a simple password authentication form.
<?php
if (!empty($loginme)) {
  $connection = mysql_pconnect($dbhost='localhost',$dbuser='root',$dbpass='root');
  mysql_select_db($database='test',$connection);
  $query = "SELECT id FROM customer WHERE email='".mysql_real_escape_string($admin)."' AND password='".mysql_real_escape_string($password)."'";
  $result = mysql_query($query, $connection);
  $num = mysql_num_rows($result);
  if ($num > 0){
     header("Location: home.php"); // do what you want
     exit;
  }
  else{
     echo "username and password are either incorrect or not in the database";
  }
}
?>
<form method="post" action="">
Username: <input type="text" name="admin"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="loginme" value="Login Me">
</form>

Regular Expressions in PHP

Perl-compatible Regular Expressions

Perl Compatible Regular Expressions (normally abbreviated as “PCRE”) offer a very powerful string-matching and replacement mechanism that far surpasses anything we have examined so far.
Regular expressions are often thought of as very complex—and they can be at times. However, properly used they are relatively simple to understand and fairly easy to use. Given their complexity, of course, they are also much more computationally intensive than the simple search-and-replace functions we examined earlier in this chapter. Therefore, you should use them only when appropriate—that is, when using the simpler functions is either impossible or so complicated that it’s not worth the effort.

PHP Strings Formatting

Generic Formatting
If you are not handling numbers or currency values, you can use the printf() family of functions to perform arbitrary formatting of a value. All the functions in this group performin an essentially identical way: they take an input string that specifies the output format and one or more values. The only difference is in the way they return their results: the “plain” printf() function simply writes it to the script’s output, while other variants may return it (sprintf()), write it out to a file (fprintf()), and so on.

PHP Strings Comparing, Strings Searching and Strings Replacing

Comparison is, perhaps, one of the most common operations performed on strings. At times, PHP’s type-juggling mechanisms also make it the most maddening— particularly because strings that can be interpreted as numbers are often transparently converted to their numeric equivalent. Consider, for example, the following code:

PHP Strings, Escaping string and formating string

Strings wear many hats in PHP—far from being relegated to mere collections of textual characters,  they can be used to store binary data of any kind—as well as text encoded in a way that PHP does not understand natively, but that one of its extensions can manipulate directly.
String Basics

PHP - Sorting Arrays

There are a total of eleven functions in the PHP core whose only goal is to provide various methods of sorting the contents of an array. The simplest of these is sort(), which sorts an array based on its values:

PHP Array Iteration

An EasierWay to Iterate
As you can see, using this set of functions requires quite a bit of work; to be fair, there are some situations where they offer the only reasonable way of iterating through an array, particularly if you need to skip back-and-forth between its elements.
If, however, all you need to do is iterate through the entire array fromstart to finish, PHP provides a handy shortcut in the formof the foreach() construct:

PHP Array Operations

As we mentioned in the PHP Basics , a number of operators behave differently if their operands  are arrays. For example, the addition operator + can be used to create the union of its two operands:
<?php
$a = array(1, 2, 3);
$b = array('a' => 1, 'b' => 2, 'c' => 3);
var_dump($a + $b);
?>
This outputs the following:
array(6) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
["a"]=>
int(1)
["b"]=>
int(2)
["c"]=>int(3)
}
Note how the the resulting array includes all of the elements of the two original arrays, even though they have the same values; this is a result of the fact that the keys are different—if the two arrays had common elements that also share the same string keys or that have numeric keys (even if they are different), they would only appear once in the end result:
<?php
$a = array(1, 2, 3);
$b = array('a' => 1, 2, 3);
var_dump($a + $b);
?>
This results in:
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
["a"]=>
int(1)
}
Comparing Arrays
Array-to-array comparison is a relatively rare occurrence, but it can be performed using another set of operators. Like for other types, the equivalence and identity operators can be used for this purpose:
<?php
$a = array(1, 2, 3);
$b = array(1 => 2, 2 => 3, 0 => 1);
$c = array('a' => 1, 'b' => 2, 'c' => 3);
var_dump($a == $b); // True
var_dump($a === $b); // False
var_dump($a == $c); // True
var_dump($a === $c); // False
?>
As you can see, the equivalence operator == returns true if both arrays have the same number of elements with the same values and keys, regardless of their order. The identity operator ===, on the other hand, returns true only if the array contains the same key/value pairs in the same order. Similarly, the inequality and non-identity operators can determine whether two arrays are  different
<?php
$a = array(1, 2, 3);
$b = array(1 => 2, 2 => 3, 0 => 1);
var_dump($a != $b); // False
var_dump($a !== $b); // True
?>
Once again, the inequality operator only ensures that both arrays contain the same elements with the same keys, whereas the non-identity operator also verifies their position.
Counting, Searching and Deleting Elements
The size of an array can be retrieved by calling the count() function:
<?php
$a = array(1, 2, 4);
$b = array();
$c = 10;
echo count($a); // Outputs 3
echo count($b); // Outputs 0
echo count($c); // Outputs 1
?>
As you can see, count() cannot be used to determine whether a variable contains an array—since running it on a scalar value will return one. The right way to tell whether a variable contains an array is to use is_array() instead.
A similar problem exists with determining whether an element with the given key exists. This is often done by calling isset():
<?php
$a = array('a' => 1, 'b' => 2);
echo isset($a['a']); // True
echo isset($a['c']); // False
?>
However, isset() has themajor drawback of considering an element whose value is NULL—which is perfectly valid—as inexistent:
<?php
$a = array('a' => NULL, 'b' => 2);
echo isset($a['a']); // False
?>

The correct way to determine whether an array element exists is to use

<?php
array_key_exists() instead:
$a = array('a' => NULL, 'b' => 2);
echo array_key_exists($a['a']); // True
?>
Obviously, neither these functions will allow you to determine whether an element with a given value exists in an array—this is, instead, performed by the in_array() function:
<?php
$a = array('a' => NULL, 'b' => 2);
echo in_array($a, 2); // True
?>

Finally, an element can be deleted from an array by unsetting it:

<?php
$a = array('a' => NULL, 'b' => 2);
unset($a['b']);
echo in_array ($a, 2); // False
?>
Flipping and Reversing
There are two functions that have rather confusing names and that are sometimes misused: array_flip() and array_reverse(). The first of these two functions inverts the value of each element of an array with its key:
<?php
$a = array('a', 'b', 'c');
var_dump(array_flip($a));
?>

This outputs:
array(3) {
["a"]=>
int(0)
["b"]=>
int(1)
["c"]=> int(2)
}
On the other hand, array_reverse() actually inverts the order of the array’s elements, so that the last one appears first:
<?php
$a = array('x' => 'a', 10 => 'b', 'c');
var_dump(array_reverse($a));
?>

Note how key key association is only lost for those elements whose keys are numeric:
array(3) {
[0]=>
string(1) "c"
[1]=>
string(1) "b"
["x"]=>
string(1) "a"
}

PHP Control Structures

Control structures allow you to control the flow of your script—after all, if all a script could do was run from start to finish, without any control over which portions of the script are run and how many times, writing a programwould be next to impossible.
PHP features a number of different control structures—including some that, despite being redundant, significantly simplify script development. You should be very familiar with all of them, as they are one of the fundamental elements of the language’s structure.
Conditional Structures

PHP Functions

The heart of PHP programming is, arguably, the function. The ability to encapsulate any piece of code in a way that it can be called again and again is invaluable—it is the cornerstone of structured procedural and object oriented programming.
Basic Syntax
Function syntax is, at itsmost basic, very simple. To create a newfunction, we simply use the keyword function, followed by an identifier, a pair of parentheses and braces:
function name() { }
PHP function names are not case-sensitive. As with all identifiers in PHP, the name must consist only of letters (a-z), numbers and the underscore character, and must not start with a number.
To make your function do something, simply place the code to be execute between the braces, then call it.
<?php
function hello(){
echo "Hello World!";
}

hello(); // Displays "Hello World!"
?>
Returning Values
All functions in PHP return a value—even if you don’t explicitly cause themto. Thus, the concept of “void” functions does not really apply to PHP. You can specify the return value of your function by using the return keyword:
<?php
function hello(){
return "Hello World"; // No output is shown
}
$txt = hello(); // Assigns the return value "Hello World" to $txt
echo hello(); // Displays "Hello World"
?>

Naturally, return also allows you to interrupt the execution of a function and exit it even if you don’t want to return a value:

<?php
function hello($who){
echo "Hello $who";
if ($who == "World") {
return; // Nothing else in the function will be processed
}
echo ", how are you";
}
hello("World"); // Displays "Hello World"
hello("Reader") // Displays "Hello Reader, how are you?"
?>

Note, however, that even if you don’t return a value, PHP will still cause your function to return NULL.

Functions can also be declared so that they return by reference; this allows you to return a variable as the result of the function, instead of a copy (returning a copy is the default for every data type except objects). Typically, this is used for things like resources (like database connections) and when implementing the Factory pattern.
However, there is one caveat: you must return a variable—you cannot return an expression by reference, or use an empty return statement to force a NULL return value:
<?php
function &query($sql){
$result = mysql_query($sql);
return $result;
}
// The following is incorrect and will cause PHP to emit a notice when called.
function &getHello(){
return "Hello World";
}
// This will also cause the warning to be issued when called
function &test(){
echo 'This is a test';
}
?>
Variable Scope
PHP has three variable scopes: the global scope, function scope, and class scope.
The global scope is, as its name implies, available to all parts of the script; if you declare or assign a value to a variable outside of a function or class, that variable is created in the global scope.
However, any time you enter a function, PHP creates a new scope—a “clean slate” that, by default, contains no variable and that is completely isolated from the global scope. Any variable defined  within a function is no longer available after the function has finished executing. This allows the  use of names which may be in use elsewhere without having to worry about conflicts.
<?php
$a = "Hello World";
function hello(){
$a = "Hello Reader";
$b = "How are you";
}

hello();
echo $a; // Will output Hello World
echo $b; // Will emit a warning
?>
There are two ways to access variables in the global scope from inside a function; the first consists of "importing" the variable inside the function's scope by using the global statement:
<?php
$a = "Hello";
$b = "World";

function hello(){
global $a, $b;
echo "$a $b";
}

hello(); // Displays "Hello World"
?>
You will notice that global takes a comma-separated list of variables to import— naturally, you can havemultiple global statements inside the same function.
Many developers feel that the use of global introduces an element of confusion into their code, and that “connecting” a function’s scope with the global scope can easily be a source of problems. They prefer, instead, to use the $GLOBALS superglobal array, which contains all the variables in the global scope:
<?php
$a = "Hello";
$b = "World";
function hello(){
echo $GLOBALS['a'] .' '. $GLOBALS['b'];
}
hello(); // Displays "Hello World"
?>
Passing Arguments
Arguments allow you to inject an arbitrary number of values into a function in order to influence its behaviour:
<?php
function hello($who){
echo "Hello $who";
}

hello("World");
/* Here we pass in the value, "World", and the function displays "Hello World"*/
?>
You can define any number of arguments and, in fact, you can pass an arbitrary number of arguments to a function, regardless of how many you specified in its declaration.
PHP will not complain unless you provide fewer arguments than you declared.
Additionally, you can make arguments optional by giving them a default value.
Optional arguments must be right-most in the list and can only take simple values—expressions are not allowed:
<?php
function hello($who = "World")
{
echo "Hello $who";
}
hello();
/* This time we pass in no argument and $who is assigned "World" by default. */
?>
Variable-length Argument Lists
A common mistake when declaring a function is to write the following:
function f ($optional = "null", $required){

}
This does not cause any errors to be emitted, but it also makes no sense whatsoever— because you will never be able to omit the first parameter ($optional) if you want to specify the second, and you can’t omit the second because PHP will emit a warning.
In this case, what you really want is variable-length argument lists—that is, the ability to create a function that accepts a variable number of arguments, depending on the circumstance. A typical example of this behaviour is exhibited by the printf() family of functions.
PHP provides three built-in functions to handle variable-length argument lists:
func_num_args(), func_get_arg() and func_get_args().
Here’s an example of how they’re used:

<?php
function hello(){
if(func_num_args() > 0) {
$arg = func_get_arg(0); // The first argument is at position 0
echo "Hello $arg";
}
else{
echo "Hello World";
}
}

hello("Reader"); // Displays "Hello Reader"
hello(); // Displays "Hello World"
?>
You can use variable-length argument lists even if you do specify arguments in the function header. However, this won’t affect the way the variable-length argument list functions behave—for example, func_num_args() will still return the total number of arguments passed to your function, both declared and anonymous.
<?php
function countAll($arg1){
if(func_num_args() == 0){
die("You need to specify at least one argument");
}
else{
$args = func_get_args(); // Returns an array of arguments
// Remove the defined argument from the beginning
array_shift($args);
$count = strlen($arg1);
foreach($args as $arg){
$count += strlen($arg);
}
}
return $count;
}

echo countAll("foo", "bar", "baz"); // Displays '9'
?>
Passing Arguments by Reference
Function arguments can also be passed by reference, as opposed to the traditional by-value method, by prefixing them with the by-reference operator &. This allows your function to affect external variables:
<?php
function countAll(&$count){
if(func_num_args() == 0){
die("You need to specify at least one argument");
}
else{
$args = func_get_args(); // Returns an array of arguments
// Remove the defined argument from the beginning
array_shift($args);
foreach($args as $arg) {
$count += strlen($arg);
}
}
}

$count = 0;
countAll($count, "foo", "bar", "baz"); // $count now equals 9
?>
Unlike PHP 4, PHP 5 allows default values to be specified for parameters even when they are declared as by-reference:
<?php
function cmdExists($cmd, &$output = null) {
$output = 'whereis $cmd';
if(strpos($output, DIRECTORY_SEPARATOR) !== false) {
return true;
}
else{
return false;
}
}
?>
In the example above, the $output parameter is completely optional—if a variable is not passed in, a new one will be created within the context of cmdExists() and, of course, destroyed when the function returns.

PHP Operators

There are many types of operators in PHP, those are:

• Assignment Operators for assigning data to variables
• Arithmetic Operators for performing basic math functions
• String Operators for joining two or more strings
• Comparison Operators for comparing two pieces of data
• Logical Operators for performing logical operations on Boolean values

In addition, PHP also provides:
• Bitwise Operators for manipulating bits using boolean math
• Error Control Operators for suppressing errors
• Execution Operators for executing system commands
• Incrementing/Decrementing Operators for incrementing and decrementing numerical values
• Type Operators for identifying Objects

Arithmetic Operators
Arithmetic operators allow you to perform basic mathematical operations:

Addition $a = 1 + 3.5;
Subtraction $a = 4 - 2;
Multiplication $a = 8 * 3;
Division $a = 15 / 5;
Modulus $a = 23 % 7;

Incrementing/decrementing operators are a special category of operators that make it possible to increment or decrement the value of an integer by one. They are unary operators, because they only accept one operand (that is, the variable that needs to be incremented or decremented), and are somewhat of an oddity, in that their behavior changes depending on whether they are appended or prepended to their operand.

The position of the operator determines whether the adjustment it performs takes place prior to, or after returning the value:

• If the operator is placed after its operand, the interpreter will first return the value of the latter
(unchanged), and then either increment or decrement it by one.
• If the operator is placed before the operand, the interpreter will first increment or decrement the
value of the latter, and then return the newly-calculated value.

Here are a few examples:

example of php constants

php constants
Conversely to variables, constants are meant for defining immutable values. Constants can be accessed for any scope within a script; however, they can only contain scalar values. Constant names, like variables, are case-sensitive; they also follow the same naming requirements, with the exception of the leading $. It is considered best practice to define constants using only upper-case names.

example of constants


PHP Variables

Variables are temporary storage containers. In PHP, a variable can contain any type of data, such as, for example, strings, integers, floating-point numbers, objects and arrays. PHP is loosely typed, meaning that it will implicitly change the type of a variable as needed, depending on the operation being performed on its value. This contrasts with strongly typed languages, like C and Java,where variables can only contain one type of data throughout their existence.

PHP variables are identified by a dollar sign $, followed by an identifier name. Variables must be named using only letters (a-z, A-Z), numbers and the underscore character; their namesmust start with either a letter or an underscore, and are one of only two identifier types in PHP that are case-sensitive (the other is constants, discussed below). Here are a few examples:

* $name = 'valid'; // Valid name

* $_name = 'valid'; // Valid name

* $1name = 'invalid'; // Invalid name, starts with a number

Variable of Variables
In PHP, it is also possible to create so-called variable variables. That is a variable whose name is contained in another variable. For example:

PHP Data Types

PHP supports many different data types that are integers, strings, floating-point numbers, objects and arrays, but they are generally divided in two categories:

making dynamic and interactive Web pages in php

PHP stands for PHP Hyper Text pre processor, a server site scripting language, also a powerful tool for making dynamic and server interactive Web pages.

PHP is the widely-used and free.
Related Posts Plugin for WordPress, Blogger...