Archive | September, 2012

Browser Redirection in PHP

22 Sep

The PHP header() function supplies raw HTTP headers to the browser and can be used to redirect it to another location. The redirection script should be at the very top of the page to prevent any other part of the page from loading.

The target is specified by the Location: header as the argument to the header() function. After calling this function the exit() function can be used to halt parsing of rest of the code.

Following example demonstrates how you can redirect a borwser request to another web page. Try out this example by puttingthe source code in test.php script.

<?php
  if( $_POST["location"] )
  {
     $location = $_POST["location"];
     header( "Location:$location" );
     exit();
  }
?>
<html>
<body>
   <p>Choose a site to visit :

<form action="" method="POST"> <select name="location"> <option value="http://w3c.org"> World Wise Web Consortium </option> <option value="http://www.google.com"> Google Search Page </option> </select> <input type="submit" /> </form> </body> </html>

Display Images Randomly in PHP

22 Sep

The PHP rand() function is used to generate a random number.i This function can generate numbers with-in a given range. The random number generator should be seeded to prevent a regular pattern of numbers being generated. This is achieved using the srand() function that specifiies the seed number as its argument.

Following example demonstrates how you can display different image each time out of four images:

<html>
<body>
<?php
  srand( microtime() * 1000000 );
  $num = rand( 1, 4 );
   
  switch( $num ) 
  {
  case 1: $image_file = "/home/images/alfa.jpg";
          break;
  case 2: $image_file = "/home/images/ferrari.jpg";
          break;
  case 3: $image_file = "/home/images/jaguar.jpg";
          break;
  case 4: $image_file = "/home/images/porsche.jpg";
          break;
  }
  echo "Random Image : ";
?>
</body>
</html>

Identifying Browser & Platform

22 Sep

PHP creates some useful environment variables that can be seen in the phpinfo.php page that was used to setup the PHP environment.

One of the environemnt variables set by PHP is HTTP_USER_AGENT which identifies the user’s browser and operating system.

PHP provides a function getenv() to access the value of all the environment variables. The information contained in the HTTP_USER_AGENT environment variable can be used to create dynamic content appropriate to the borwser.

Following example demonstrates how you can identify a client borwser and operating system.

NOTE: The function preg_match()is discussed in PHP Regular expression session.

<html>
<body>
<?php
   $viewer = getenv( "HTTP_USER_AGENT" );
   $browser = "An unidentified browser";
   if( preg_match( "/MSIE/i", "$viewer" ) )
   {
      $browser = "Internet Explorer";
   }
   else if(  preg_match( "/Netscape/i", "$viewer" ) )
   {
      $browser = "Netscape";
   }
   else if(  preg_match( "/Mozilla/i", "$viewer" ) )
   {
      $browser = "Mozilla";
   }
   $platform = "An unidentified OS!";
   if( preg_match( "/Windows/i", "$viewer" ) )
   {
      $platform = "Windows!";
   }
   else if ( preg_match( "/Linux/i", "$viewer" ) )
   {
      $platform = "Linux!";
   }
   echo("You are using $browser on $platform");
?>
</body>
</html>

This is producing following result on my machine. This result may be different for your computer depnding on what you are using.

PHP Sending Emails

22 Sep

PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function].

Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.

The configuration for Windows should look something like this:

[mail function]
; For Win32 only.
SMTP = smtp.secureserver.net

; For win32 only
sendmail_from = webmaster@tutorialspoint.com
Linux users simply need to let PHP know the location of their sendmail application. The path and any desired switches should be specified to the sendmail_path directive.

The configuration for Linux should look something like this:

[mail function]
; For Win32 only.
SMTP =

; For win32 only
sendmail_from =

; For Unix only
sendmail_path = /usr/sbin/sendmail -t -i
Now you are ready to go:

Sending plain text email:

PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient’s email address, the subject of the the message and the actual message additionally there are other two optional parameters.

mail( to, subject, message, headers, parameters );
Here is the description for each parameters.

Parameter Description
to Required. Specifies the receiver / receivers of the email
subject Required. Specifies the subject of the email. This parameter cannot contain any newline characters
message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parameters Optional. Specifies an additional parameter to the sendmail program
As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed.

Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.

Example:

Following example will send an HTML email message to xyz@somedomain.com. You can code this program in such a way that it should receive all content from the user and then it should send an email.

<html>
<head>
<title>Sending email using PHP
</head>
<body>
<?php
   $to = "xyz@somedomain.com";
   $subject = "This is subject";
   $message = "This is simple text message.";
   $header = "From:abc@somedomain.com \r\n";
   $retval = mail ($to,$subject,$message,$header);
   if( $retval == true )  
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>

Sending HTML email:

When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.

While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example:

Following example will send an HTML email message to xyz@somedomain.com copying it to afgh@somedomain.com. You can code this program in such a way that it should recieve all content from the user and then it should send an email.

<html>
<head>
<title>Sending HTML email using PHP
</head>
<body>
<?php
   $to = "xyz@somedomain.com";
   $subject = "This is subject";
   $message = "This is HTML message.";
   $message .= "

This is headline.

"; $header = "From:abc@somedomain.com \r\n"; $header = "Cc:afgh@somedomain.com \r\n"; $header .= "MIME-Version: 1.0\r\n"; $header .= "Content-type: text/html\r\n"; $retval = mail ($to,$subject,$message,$header); if( $retval == true ) { echo "Message sent successfully..."; } else { echo "Message could not be sent..."; } ?> </body> </html>

Sending attachments with email:

To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.

A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email’s final section must also end with two hyphens.

Attached files should be encoded with the base64_encode() function for safer transmission and are best split into chunks with the chunk_split() function. This adds \r\n inside the file at regular intervals, normally every 76 characters.

Following is the example which will send a file /tmp/test.txt as an attachment. you can code your program to receive an uploaded file and send it.

<html>
<head>
<title>Sending attachment using PHP
</head>
<body>
<?php
  $to = "xyz@somedomain.com";
  $subject = "This is subject";
  $message = "This is test message.";
  # Open a file
  $file = fopen( "/tmp/test.txt", "r" );
  if( $file == false )
  {
     echo "Error in opening file";
     exit();
  }
  # Read the file into a variable
  $size = filesize("/tmp/test.txt");
  $content = fread( $file, $size);

  # encode the data for safe transit
  # and insert \r\n after every 76 chars.
  $encoded_content = chunk_split( base64_encode($content));
  
  # Get a random 32 bit number using time() as seed.
  $num = md5( time() );

  # Define the main headers.
  $header = "From:xyz@somedomain.com\r\n";
  $header .= "MIME-Version: 1.0\r\n";
  $header .= "Content-Type: multipart/mixed; ";
  $header .= "boundary=$num\r\n";
  $header .= "--$num\r\n";

  # Define the message section
  $header .= "Content-Type: text/plain\r\n";
  $header .= "Content-Transfer-Encoding:8bit\r\n\n";
  $header .= "$message\r\n";
  $header .= "--$num\r\n";

  # Define the attachment section
  $header .= "Content-Type:  multipart/mixed; ";
  $header .= "name=\"test.txt\"\r\n";
  $header .= "Content-Transfer-Encoding:base64\r\n";
  $header .= "Content-Disposition:attachment; ";
  $header .= "filename=\"test.txt\"\r\n\n";
  $header .= "$encoded_content\r\n";
  $header .= "--$num--";

  # Send email now
  $retval = mail ( $to, $subject, "", $header );
  if( $retval == true )
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>

You try all the above examples. If you face any problem then you can post that problem in discussion forum.

PHP File Uploading

22 Sep

A PHP script can be used with a HTML form to allow users to upload files to the server. Initially files are uploaded into a temporary directory and then relocated to a target destination by a PHP script.

Information in the phpinfo.php page describes the temporary directory that is used for file uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini

The process of uploading a file follows these steps

The user opens the page containing a HTML form featuring a text files, a browse button and a submit button.

The user clicks the browse button and selects a file to upload from the local PC.

The full path to the selected file appears in the text filed then the user clicks the submit button.

The selected file is sent to the temporary directory on the server.

The PHP script that was specified as the form handler in the form’s action attribute checks that the file has arrived and then copies the file into an intended directory.

The PHP script confirms the success to the user.

As usual when writing files it is necessary for both temporary and final locations to have permissions set that enable file writing. If either is set to be read-only then process will fail.

An uploaded file could be a text file or image file or any document.

Creating an upload form:

The following HTM code below creates an uploader form. This form is having method attribute set to post and enctype attribute is set to multipart/form-data

<html>
<head>
<title>File Uploading Form
</head>
<body>
<h3>File Upload:
Select a file to upload: 
<form action="/php/file_uploader.php" method="post" enctype="multipart/form-data"> <input type="file" name="file" size="50" /> <br /> <input type="submit" value="Upload File" /> </form> </body> </html>

Creating an upload script:

There is one global PHP variable called $_FILES. This variable is an associate double dimension array and keeps all the information related to uploaded file. So if the value assigned to the input’s name attribute in uploading form was file, then PHP would create following five variables:

$_FILES[‘file’][‘tmp_name’]- the uploaded file in the temporary directory on the web server.

$_FILES[‘file’][‘name’] – the actual name of the uploaded file.

$_FILES[‘file’][‘size’] – the size in bytes of the uploaded file.

$_FILES[‘file’][‘type’] – the MIME type of the uploaded file.

$_FILES[‘file’][‘error’] – the error code associated with this file upload.

The following example below attempts to copy a file uploaded by the HTML Form listed in previous section page to /var/www/html directory which is document root of your PHP server and it will display all the file’s detail upon completion. Please note that if you are going to display uploaded file then don’t try with binary files like images or word document.

Here is the code of uploader.php script which will take care of uploading a file.

<?php
if( $_FILES['file']['name'] != "" )
{
   copy( $_FILES['file']['name'], "/var/www/html" ) or 
           die( "Could not copy file!");
}
else
{
    die("No file specified!");
}
?>
<html>
<head>
<title>Uploading Complete
</head>
<body>
<h2>Uploaded File Info:
<ul>
<li>Sent file: <?php echo $_FILES['file']['name'];  ?>
<li>File size: <?php echo $_FILES['file']['size'];  ?> bytes
<li>File type: <?php echo $_FILES['file']['type'];  ?>
</ul>
</body>
</html>

When you will upload a file using upload form and upload script, it will display following result:

Uploaded File Info:

Sent file: uploadedfile.txt

File size: 2003 bytes

File type: image/jpg

You try out above example yourself on your webserver. If you have any problem then post it to Discussion Forums to get any further help.

PHP GET and POST Methods

22 Sep

There are two ways the browser client can send information to the web server.

The GET Method
The POST Method

Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand.

name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server.

The GET Method

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.

http://www.test.com/index.htm?name1=value1&name2=value2
The GET method produces a long string that appears in your server logs, in the browser’s Location: box.

The GET method is restricted to send upto 1024 characters only.

Never use GET method if you have password or other sensitive information to be sent to the server.

GET can’t be used to send binary data, like images or word documents, to the server.

The data sent by GET method can be accessed using QUERY_STRING environment variable.

The PHP provides $_GET associative array to access all the sent information using GET method.

Try out following example by putting the source code in test.php script.

<?php
  if( $_GET["name"] || $_GET["age"] )
  {
     echo "Welcome ". $_GET['name']. "
"; echo "You are ". $_GET['age']. " years old."; exit(); } ?> <html> <body> <form action="" method="GET"> Name: Age: </form> </body> </html>

The POST Method

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.

The POST method does not have any restriction on data size to be sent.

The POST method can be used to send ASCII as well as binary data.

The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.

The PHP provides $_POST associative array to access all the sent information using GET method.

Try out following example by putting the source code in test.php script.

<?php
  if( $_POST["name"] || $_POST["age"] )
  {
     echo "Welcome ". $_POST['name']. "
"; echo "You are ". $_POST['age']. " years old."; exit(); } ?> <html< <body< <form action="" method="POST"> Name: Age: </body> </html>

The $_REQUEST variable

The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies.

The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.

Try out following example by putting the source code in test.php script.

<?php
  if( $_REQUEST["name"] || $_REQUEST["age"] )
  {
     echo "Welcome ". $_REQUEST['name']. "
"; echo "You are ". $_REQUEST['age']. " years old."; exit(); } ?> <html> <body> <form action="" method="POST"> Name: Age: </body> </html>

Here $_PHP_SELF variable contains the name of self script in which it is being called.

PHP ADDING AND SUBTRACTING DATES

22 Sep

Here’s how you add and subtract dates from one another. For example, this simple code can calculate what the date will be 2 weeks before or after 1998-08-14 (yyyy-mm-dd).
Subtracting days from a date
The following example will subtract 3 days from 1998-08-14. The result will be 1998-08-11.

$date = “1998-08-14”;
$newdate = strtotime ( ‘-3 day’ , strtotime ( $date ) ) ;
$newdate = date ( ‘Y-m-j’ , $newdate );
echo $newdate;

Subtracting Weeks from a date
The following example will subtract 3 weeks from 1998-08-14. The result will be 1998-07-24. Notice that the only difference in the code is the week statement.

$date = “1998-08-14”;
$newdate = strtotime ( ‘-3 week’ , strtotime ( $date ) ) ;
$newdate = date ( ‘Y-m-j’ , $newdate );
echo $newdate;

Subtracting Months from a date
The following example will subtract 3 months from 1998-08-14. The result will be 1998-05-14. Notice that the only difference in the code is the month statement.

$date = “1998-08-14”;
$newdate = strtotime ( ‘-3 month’ , strtotime ( $date ) ) ;
$newdate = date ( ‘Y-m-j’ , $newdate );
echo $newdate;

Subtracting Years from a date
The following example will subtract 3 years from 1998-08-14. The result will be 1995-08-14. Notice that the only difference in the code is the year statement.

$date = “1998-08-14”;
$newdate = strtotime ( ‘-3 year’ , strtotime ( $date ) ) ;
$newdate = date ( ‘Y-m-j’ , $newdate );
echo $newdate;

Adding days, months, weeks and years from a date
There isn’t really much difference from subtracting and adding dates. To add dates, just use any of the examples above and replace the negative (-) with a positive (+) e.g. ‘+3 weeks’

PHP Date and Time

22 Sep

Dates are so much part of everyday life that it becomes easy to work with them without thinking. PHP also provides powerful tools for date arithmetic that make manipulating dates easy.

Getting the Time Stamp with time():

PHP’s time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer.

The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp.

<?php
print time();
?>

It will produce following result:

948316201
This is something difficult to understand. But PHP offers excellent tools to convert a time stamp into a form that humans are comfortable with.

Converting a Time Stamp with getdate():

The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time().

Following table lists the elements contained in the array returned by getdate().

Key Description Example
seconds Seconds past the minutes (0-59) 20
minutes Minutes past the hour (0 – 59) 29
hours Hours of the day (0 – 23) 22
mday Day of the month (1 – 31) 11
wday Day of the week (0 – 6) 4
mon Month of the year (1 – 12) 7
year Year (4 digits) 1997
yday Day of year ( 0 – 365 ) 19
weekday Day of the week Thursday
month Month of the year January
0 Timestamp 948370048
Now you have complete control over date and time. You can format this date and time in whatever format you wan.

Example:

Try out following example

<?php
$date_array = getdate();
foreach ( $date_array as $key => $val )
{
print "$key = $val
";
}
$formated_date = "Today's date: ";
$formated_date .= $date_array[mday] . "/";
$formated_date .= $date_array[mon] . "/";
$formated_date .= $date_array[year];

print $formated_date;
?>

It will produce following result:

seconds = 27
minutes = 25
hours = 11
mday = 12
wday = 6
mon = 5
year = 2007
yday = 131
weekday = Saturday
month = May
0 = 1178994327
Today’s date: 12/5/2007
Converting a Time Stamp with date():

The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it.

date(format,timestamp)
The date() optionally accepts a time stamp if ommited then current date and time will be used. Any other data you include in the format string passed to date() will be included in the return value.

Following table lists the codes that a format string can contain:

Format Description Example
a ‘am’ or ‘pm’ lowercase pm
A ‘AM’ or ‘PM’ uppercase PM
d Day of month, a number with leading zeroes 20
D Day of week (three letters) Thu
F Month name January
h Hour (12-hour format – leading zeroes) 12
H Hour (24-hour format – leading zeroes) 22
g Hour (12-hour format – no leading zeroes) 12
G Hour (24-hour format – no leading zeroes) 22
i Minutes ( 0 – 59 ) 23
j Day of the month (no leading zeroes 20
l (Lower ‘L’) Day of the week Thursday
L Leap year (‘1’ for yes, ‘0’ for no) 1
m Month of year (number – leading zeroes) 1
M Month of year (three letters) Jan
r The RFC 2822 formatted date Thu, 21 Dec 2000 16:01:07 +0200
n Month of year (number – no leading zeroes) 2
s Seconds of hour 20
U Time stamp 948372444
y Year (two digits) 06
Y Year (four digits) 2006
z Day of year (0 – 365) 206
Z Offset in seconds from GMT +5
Example:

Try out following example

<?php
print date("m/d/y G.i:s
", time());
print "Today is ";
print date("j of F Y, \a\\t g.i a", time());
?>

It will produce following result:

01/20/00 13.27:55
Today is 20 of January 2000, at 1.27 pm
Hope you have good understanding on how to format date and time according to your requirement. For your reference a complete list of all the date and time functions is given in PHP Date & Time Functions.

Swapping two variables without using a temp variable in C/C++

21 Sep

1. Simple Method


void main() 
{
      int x = 8;
      int y = 10;
      x = x + y;
      y = x - y;
      x = x - y;
}

2. Method using XOR

void main() 
{
	  int i = 516;
	  int j = 615;
	  i = i ^ j;   // ^ = bitwise XOR
	  j = i ^ j;
	  i = i ^ j;
}

The difference between stack and heap memory allocation

21 Sep

A common question amongst coders new to C or C++ relates to the difference between stack and heap memory allocation. The answer lies in how the code is executed at the very lowest level.

When a program is executed, each thread is allocated a limited amount of stack space. The stack holds information used by the program, including the raw byte code executed on the processor.

Variables allocated on the stack, or automatic variables, are stored directly to this memory. Access to this memory is very fast, and it’s allocation is dealt with when the program is compiled. Large chunks of memory, such as very large arrays, should not be allocated on the stack to avoid overfilling the stack memory (known as stack overflow). Stack variables only exist in the block of code in which they were declared. For example:


void a()
{
if(true) {
int x = 0;
}
x = 1;
}

In this code, x is allocated on the stack. This value is not available outside of the if() block, so attempting to access the variable outside of the block, as above, result in a compilation error.

Variables allocated on the heap, or dynamic variables, have their memory allocated at run time (ie: as the program is executing). Accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory (ie: RAM and swap space). This memory remains allocated until explicitly freed by the program and, as a result, may be accessed outside of the block in which it was allocated. For example:

int *x;
void b()
{
if(true) {
x = malloc(sizeof(int));
}
*x = 1;
}

void c()
{
free(x);
}

In this example, memory for the variable x is allocated when b() is called, and remains in memory until c() is called. Notice how we can set the value of x outside of the if() block in which it is allocated.

In summary, temporary variables should be allocated on the stack. It’s less mucking around with memory allocation, the code is easier to read, the memory is accessed faster and the program does not need to allocate the memory on the fly. For large variables or arrays whose size may vary, heap memory allocation is your friend. Just remember to free all of the memory allocated or you’ll end up with memory leaks.

In Short
STACK memory is referred as temporary memory,if you come out of the program the memory of the variable will not no more there.[eg., int a; memory for a will not maintained after v came out from the program]. While HEAP memory is referred as permanent memory,memory allocated for the object will be maintained even if we came out of the program.[eg.memory for OBJECT will remains there ever].