Showing posts with label Learn Php Basics. Show all posts
Showing posts with label Learn Php Basics. Show all posts

Php Simple E-mail Script


The PHP mail() function is used to send emails from a script.

Syntax:

mail(to, subject, message ,headers, parameters)

Params Required Explaination of parameters
to Yes  Reciever's email address
subject Yes Specifies the subject of the email.
message Yes  Message to be sent. Each line should be separated with a (\n). Lines should not longer than 70 characters
headers No Additional headers, like From, Cc, and Bcc. The additional headers should be separated with  (\r\n)
parameters No  Specifies an additional parameter to the sendmail program

Note: PHP requires an installed  email system ro work email system. It is defined in the configuration settings in the php.ini file. Click to View The configuration of mail()

Example :

The simplest example to send an email with PHP.
First declare the variables $to, $subject, $message, $from, $headers then we use the variables in the mail() function to send an e-mail:

<?php

$to = "someone@example.com";

$subject = "Test mail";

$message = "Hello! This is a simple email message.";

$from = "someonelse@example.com";

$headers = "From:" . $from;

mail($to,$subject,$message,$headers);

echo "Mail Sent.";

?>


Click to view Script for Sending email with multiple attachement 

Php Arrays

An array is a special variable, which can store multiple values in one single variable.
There are three kind of arrays in php:
  • Numeric array - An array with a numeric index
  • Associative array - An array where each ID key is associated with a value
  • Multidimensional array -Array elements can contain one or more array.

Numeric Array

Numeric Array can be created by two ways.
1. Auto index.In this index will assigned automatically.
$bikes = array("Hero","Bajaj","Yamaha");
2. We can assign index manually also :
$bikes[0]="Hero";
$bikes[1]="Bajaj";
$bikes[2]="Yamaha";

Associative Arrays

In associative array there is a key value pair
With associative arrays we can use the values as keys and assign values to them.

Example :

In this example we use an array to assign ages to the different persons:

$personages = array("Sujal"=>32, "Mitesh"=>30, "Hiren"=&gt;34);

$personages['Sujal'] = "32";
$personages['Mitesh'] = "30";
$personages['Hiren'] = "34";

Multidimensional Arrays

Multidimentional array means each element of array can also be a array.

Example :

$Arrayresult = Array
(
[Admin] => Array
  (
  [0] => Sujal
  [1] => Mitesh
  [2] => Hiren
  )
[Receptionist] => Array
  (
  [0] => Glenn
  )
[Staff] => Array
  (
  [0] => Rahul
  [1] => Sandhya
  [2] => Suraj
  )
)
We can access staff details by $Arrayresult['staff'][0]  or $Arrayresult['staff'][1] or  $Arrayresult['staff'][2]  

Php $_POST & $_REQUEST variable

The $_POST Variable

The $_POST variable is used to collect values from a form which are sent using post method.
Information sent with the POST method is not visible to addressbar and it has no limitations

Note: There is default 8 Mb max size for the POST method it can be changed by setting the post_max_size in the php.ini file).

Example :

<form action="target.php" method="post">

Name: <input type="text" name="username" />

Age: <input type="text" name="country" />

<input type="submit" />
</form> 
When the user clicks the "Submit" button, the addressbar will be like this:
http://www.test.com/target.php 
The "target.php" file can now use the $_POST variable to collect form data (the names of the form fields will automatically be the keys in the $_POST array):

Welcome <?php echo $_POST["username"]; ?>!<br />

You are from  <?php echo $_POST["country"]; ?> country.

The PHP $_REQUEST Variable

The  $_REQUEST variable contain all values of  $_GET, $_POST, and $_COOKIE.
The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods.

Example :

Welcome <?php echo $_REQUEST["username"]; ?>!<br />

You are from <?php echo $_REQUEST["country"]; ?> country.

Php $_GET variable

 

The $_GET variable is used To collect values in a form with form method "get"
Information sent from the GET method is visible in url and displayed in the browser's address bar.

The get method is not suitable for very large variable values. It should not be used with values exceeding 2000 characters.

Example

<form action="target.php" method="get">

UserName: <input type="text" name="username" />

Country: <input type="text" name="country" />

<input type="submit" />

</form>


When the user press the "Submit" button, the URL sent to the 
server look like below:

http://www.test.com/target.php?username=Hiren&country=india


The "target.php" file can now use the $_GET variable to collect form data (the names of the form fields will automatically be the keys in the $_GET array):

Welcome <?php echo $_GET["username"]; ?>.

You are from <?php echo $_GET["country"]; ?> country!

When should use  "get" method?

When using method="get" in HTML forms, all variable names and values are displayed in the addressbar. 

Note: get method should not be used when sending sensitive information like password!


Sessions in Php


Session is used to store information about user .
Session variables hold information about one single user, and are available to whole application.

Session Variables

Session allow you to store user information on the server for later use (i.e. username, shopping items, etc).
Sessions work by creating a unique id (session_id) for each visitor and store variables based on this session_id. The session_id is either stored in a cookie or is appended in the URL.

session_id is used to get or set the session id for the current session.
session_id() returns the session id for the current session or the empty string ("") if there is no current session

Start a PHP Session

Before you store  information in your session, you must first start  the session.
Note: The session_start() function must be written BEFORE the <html> tag:
<?php session_start(); ?>

<html>
<body>

</body>
</html>
The code above will register the user's session with the server, allow you to start saving user information, and assign a session_id for that user's session.

Store a Session Variable

The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php

session_start();
// store session data
$_SESSION['visits']=1;

?>
<html>
<body>
<?php

//retrieve session data
echo "Pagevisits=". $_SESSION['visits'];
?>

</body>
</html>
Output:
Pagevisits=1
In the example below, we create a simple page-visits counter.
The isset() function checks if the "visits" variable has already been set. If "visits" has been set, we can increment our counter. If "visits" doesn't exist, we create a "visits" variable, and set it to 1:

<?php
session_start(); 
if(isset($_SESSION['visits']))
 $_SESSION['visits']=$_SESSION['visits']+1;
else
 $_SESSION['visits']=1;

echo "visits=". $_SESSION['visits'];
?>

Destroy a Php Session

You can use the unset() or the session_destroy() function to delete some session data.
The unset() function is used to free up the specified session variable:
<?php

session_start();

if(isset($_SESSION['visits']))
  unset($_SESSION['visits']);

?> 
You can completely destroy the session using the session_destroy() function:

<?php
session_destroy();
?>

Cookies in Php

What is a Cookie?

A cookie is often used to identify a user. A cookie is a small file that is stored on the user's computer. Each requests on to page in browser, it also send the cookie too.
We can create and retrieve the cookies in php.

Creating Cookie in Php

In Php setcookie() function is used to set a cookie.
The setcookie() function must appear BEFORE the <html> tag.

Syntax :

setcookie(name, value, expire, path, domain, secure, httponly);

name - The name of the cookie. 
value - The value of the cookie. 
expire - The time the cookie expires
path - The path on the server in which the cookie will be available on
domain - The domain that the cookie is available to. Setting the domain  
to 'www.test.com' will make the cookie available in the www subdomain and higher subdomains.
secure - When TRUE the cookie will be made accessible only through 
the HTTP protocol. This means that the cookie won't be accessible by scripting 
languages, such as JavaScript.
httponly - When set to TRUE, the cookie will only be set if a secure connection 
exists.
Note to Remeber : The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received.
To prevent URLencoding in Cookie we can use setrawcookie().

Example 1

In the example below, we will create a cookie "username" and assign the value "Hiren Prajapati" to it. We also specify that the cookie should expire after one hour:
<?php

setcookie("username", "Hiren Prajapati", time()+3600);

?>
<html>

.....

Example 2

In the example below, we will create a cookie "username" and assign the value "Hiren Prajapati" to it. We also specify that the cookie should expire after one month:
<?php

$expiretime=time()+60*60*24*30;
setcookie("username", "Hiren Prajapati", $expiretime);

?>
<html>

.....

Retrieve a Cookie

We can retrieve a cookie using $_COOKIE variable.

In the example below, we retrieve the value of the cookie named "username" and display it on a page:
<?php

// Print a cookie
echo $_COOKIE["username"];

// print all cookies
print_r($_COOKIE);

?>

We can check the cookie using isset as the example below.

<html>
<body>

<?php

if (isset($_COOKIE["username"]))
  echo "Welcome " . $_COOKIE["username"] . "!<br />";
else
  echo "Welcome Guest!<br />";

?>

</body>
</html>

Php Loops

    
     This article will show you how php loops are working

  • while
  • The while loop executes a block of code while a condition is true.
    Syntax:
    while (condition)
      {   code that will be executed;   }

    Example

    This example  defines a loop that starts with i=1. The loop will continue 
    to run until i is less than, or equal to 5. i will increase by 1 in each iteration:
    
    <html>
    <body>
    <?php
    
    $k=1;
    while($k<=5)
       {
      echo "The loop number is " . $k . "<br />";
      $k++;
      }
    
    ?>
    </body>
    </html>
    
    
    Result:
    The loop number is 1
    The loop number is 2
    The loop number is 3
    The loop number is 4
    The loop number is 5

  • do...while
  • The do...while statement will always execute the block of code once, then check the condition, and repeat the loop while the condition is true.
    Syntax:
    do
    { 
      code that will be executed;
    }
    while (condition);

    Example


    The example below defines a loop that starts with i=1. It will then increment 
    i with 1, and write some result. Then condition is checked, and the loop 
    will continue to run until i is less than, or equal to 5:
    
    <html>
    <body>
    <?php
    
    $k=1;
    do
       {
      $k++;
      echo "The loop number is " . $k . "<br />";
      }
    while ($k<=5);
    
    ?>
    </body>
    </html>
    
    Result:
    The loop number is 2
    The loop number is 3
    The loop number is 4
    The loop number is 5
    The loop number is 6

  • for
  • The for loop is used when you know in advance how many times the script should run.
    Syntax:
    for (init; condition; increment)
    {
      code that will be executed;
    }

    Example

    The example below defines a loop that starts with i=1. The loop will continue 
    to run as long as the variable i is less than, or equal to 5. The 
    variable i will increase by 1 each time the loop runs:
    
    <html>
    <body>
    <?php
    
    for ($k=1; $k<=5; $k++) 
     {
      echo "The loop number is " . $k . "<br />"; 
    }
    
    ?>
    </body>
    </html>
    
    Result:
    The loop number is 1
    The loop number is 2
    The loop number is 3
    The loop number is 4
    The loop number is 5

  • foreach
  • The foreach loop is used to loop through arrays.
    Syntax:
    foreach ($array as $value)
    {
      code that will be executed;
    }
    For every iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next iteration, you will be point to next value.

    Example


    The following example shows a loop that will print the values of  
    the array:
    
    <html>
    <body>
    <?php
    
    $x=array("First","Second","Third");
    foreach ($x as $value {
      echo $value . "<br />"; 
    }
    
    ?>
    </body>
    </html>
    
    Result:
    First
    Second
    Third

Php Conditional Statements

In PHP following conditional statements are available:
  • if statement - this statement executes some code only if a specified condition is true
  • <html>
    <body>
    <?php
    
    $var="hello";
    
    if ($var=="hello") echo $var;
    
    ?>
    </body>
    </html>
    Result:hello 
    
  • if...else statement - this statement executes some code if a condition is true and another code if the condition is false
  • <html>
    <body>
    <?php
    $var="hello";
    if ($var!="hello")
    {
      echo $var; 
    }
    else
     {
      echo "this block is executed"; 
    }
    ?>
    </body>
    </html>
    Result:this block is executed 
    
  • if...elseif....else statement - this statement used to execute one of several parts of code to be execute.
  • <html>
    <body>
    <?php
    $d=date("D");
    if ($var=="hello")
      {
       echo "this block is executed"; 
      }
    if ($var=="welcome")
      {
      echo "test code";
      }
    else
      {
       echo "test code"; 
      }
    ?>
    </body>
    </html>
    Result:this block is executed 
    
  • switch statement - use this statement to select one of many blocks of code to be executed
  • <html>
    <body>
    <?php
    
    $var=100;
    switch ($var)
    {
    case 1:
      echo "Number 100";
      break;
    
    case 2:
      echo "Number 200";
      break;
    
    case 3:
      echo "Number 300";
      break;
    
    default:
      echo "No number between 100 and 300";
    }
    ?>
    </body>
    </html>
    Result:Number 100 

Operators in Php

Assignment Operators

Assignment operators are used to assign a value or set a variable to another variable's value. Such an assignment  is done with the "=", or equal character.
Example:
  • $var = 11;
  • $another_var = $var;
Now both $my_var and $another_var contain the value 11. Assignments can also be used with arithmetic operators.

Arithmetic Operators

OperatorMeaningExample
+ Addition 12 + 14
- Subtraction 16 - 12
* Multiplication 15 * 13
/ Division 15 / 3
% Modulus 43 % 10

Example:

$addition = 12 + 14; 
$subtraction = 16 - 12; 
$multiplication = 15 * 13; 
$division = 15 / 3; 
$modulus = 15 % 12; 
echo "addition: 12 + 14 = ".$addition."<br />"; 
echo "subtraction: 16 - 12 = ".$subtraction."<br />"; 
echo "multiplication:  15 * 13 = ".$multiplication."<br />"; 
echo "division: 15 / 3 = ".$division."<br />"; 
echo "modulus: 15 % 12 = " . $modulus 
 . ". Modulus is the remainder after the division operation.

Result:

addition: 12 + 14 = 26
subtraction: 16 - 12 = 4
multiplication: 15 * 13 = 195
division: 15 / 3 = 5
modulus: 15 % 12 = 1. Modulus is the remainder after the division operation.

Comparison Operators

Comparisons are used to check the relationship between variables and/or values.Here are the most important comparison operators of PHP.

OperatorMeaning Example Result
== Equal To $x == $y false
!= Not Equal To $x != $y true
< Less Than $x < $y true
> Greater Than $x > $y false
<= Less Than or Equal To $x <= $y true
>= Greater Than or Equal To $x >= $y false

String Operators

"." is used for concatation operator for strings in php.
Example :

$string1 = "Hiren";
$string2 = "Prajapati";
$result= $string1 ." ". $string2;
echo $result. "!";

Result:

Hiren Prajapati!

Array Operators

Operator Meaning Description
x + y Union Union of x and y
x == y Equality True if x and y have the same key/value pairs
x === y Identity True if x and y have the same key/value pairs in the same order and of the same types
x != y Inequality True if x is not equal to y
x <> y Inequality True if x is not equal to y
x !== y Non-identity True if x is not identical to y

Logical Operators

Example Meaning/Name Result
$a and $b And TRUE if both $a and $b are TRUE.
$a or $b Or TRUE if either $a or $b is TRUE.
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
! $a Not TRUE if $a is not TRUE.
$a && $b And TRUE if both $a and $b are TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.

Pre/Post-Increment & Decrement

    
 To add one to a variable or "increment" use the "++" operator: 
      $xyz++; Which is equivalent to $xyz += 1; or $x = $xyz + 1;
 To subtract 1 from a variable, or "decrement" use the "--" operator:
      $xyz--;  Which is equivalent to $xyz -= 1; or $xyz = $xyz - 1;
In addition to this "shorterhand" technique, you can specify whether you want to increment before the line of code is being executed or after the line has executed.

Php Basics

Basic PHP Syntax

PHP script is starts with <?php and ends with ?>. A PHP script can be placed anywhere in the document.
You can start a PHP script with <? and end with ?>.

A PHP file must have a .php extension.
A PHP file generally contains HTML tags, and some PHP scripting code.

The example below sends "How are you" string to browser.
<html>
<body>
<?php

echo "How are you";

?>
</body>
</html>
Each code line in PHP must end with a semicolon.

Comments in PHP

sinlge line comment : //
multiline comment : /* */

<?php
//This is a comment
/*
This is
a comment
block
*/
?>

PHP Variables

A variable can have a short name, like a, or a more descriptive name, like abc.
Remeber this for variable in php
  • Variables in PHP is start with a $ sign, followed by the name of the variable
  • The variable name must begin with a letter or the underscore character
  • Variable names are case sensitive (abc and ABC are two different variables)
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • A variable name should not contain blank spaces

Declaring PHP Variable

<?php

$txt="Hello World!";

$x=16;

?>