Warning: Cannot modify header information - headers already sent by (output started at /home/vire0207/public_html/blog/index.php:3) in /home/vire0207/public_html/blog/wp-includes/feed-rss2.php on line 8
Virendra Yadav http://virendrayadav.com/blog Wed, 22 Mar 2017 18:19:20 +0000 en-US hourly 1 https://wordpress.org/?v=4.7.3 http://virendrayadav.com/blog/wp-content/plugins/squirrly-seo/themes/default/css/sq_feed.css Sending Emails using PHP http://virendrayadav.com/blog/sending-emails-using-php/ http://virendrayadav.com/blog/sending-emails-using-php/#respond Wed, 22 Mar 2017 18:19:20 +0000 http://virendrayadav.com/blog/?p=163

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.

Sr.No Parameter & Description
1 to

Required. Specifies the receiver / receivers of the email

2 subject

Required. Specifies the subject of the email. This parameter cannot contain any newline characters

3 message

Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters

4 headers

Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)

5 parameters

Optional. Specifies an additional parameter to the send mail 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.

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 receive all content from the user and then it should send an email.

<html>
   
   <head>
      <title>Sending HTML email using PHP</title>
   </head>
   
   <body>
      
      <?php
         $to = "xyz@somedomain.com";
         $subject = "This is subject";
         
         $message = "<b>This is HTML message.</b>";
         $message .= "<h1>This is headline.</h1>";
         
         $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.

<?php
   // request variables // important
   $from = $_REQUEST["from"];
   $emaila = $_REQUEST["emaila"];
   $filea = $_REQUEST["filea"];
   
   if ($filea) {
      function mail_attachment ($from , $to, $subject, $message, $attachment){
         $fileatt = $attachment; // Path to the file
         $fileatt_type = "application/octet-stream"; // File Type 
         
         $start = strrpos($attachment, '/') == -1 ? 
            strrpos($attachment, '//') : strrpos($attachment, '/')+1;
				
         $fileatt_name = substr($attachment, $start, 
            strlen($attachment)); // Filename that will be used for the 
            file as the attachment 
         
         $email_from = $from; // Who the email is from
         $subject = "New Attachment Message";
         
         $email_subject =  $subject; // The Subject of the email 
         $email_txt = $message; // Message that the email has in it 
         $email_to = $to; // Who the email is to
         
         $headers = "From: ".$email_from;
         $file = fopen($fileatt,'rb'); 
         $data = fread($file,filesize($fileatt)); 
         fclose($file); 
         
         $msg_txt="\n\n You have recieved a new attachment message from $from";
         $semi_rand = md5(time()); 
         $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
         $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . "
            boundary=\"{$mime_boundary}\"";
         
         $email_txt .= $msg_txt;
			
         $email_message .= "This is a multi-part message in MIME format.\n\n" . 
            "--{$mime_boundary}\n" . "Content-Type:text/html; 
            charset = \"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . 
            $email_txt . "\n\n";
				
         $data = chunk_split(base64_encode($data));
         
         $email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" .
            " name = \"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" . 
            //" filename = \"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: 
            base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n";
				
         $ok = mail($email_to, $email_subject, $email_message, $headers);
         
         if($ok) {
            echo "File Sent Successfully.";
            unlink($attachment); // delete a file after attachment sent.
         }else {
            die("Sorry but the email could not be sent. Please go back and try again!");
         }
      }
      move_uploaded_file($_FILES["filea"]["tmp_name"],
         'temp/'.basename($_FILES['filea']['name']));
			
      mail_attachment("$from", "youremailaddress@gmail.com", 
         "subject", "message", ("temp/".$_FILES["filea"]["name"]));
   }
?>

<html>
   <head>
      
      <script language = "javascript" type = "text/javascript">
         function CheckData45() {
            with(document.filepost) {
               if(filea.value ! = "") {
                  document.getElementById('one').innerText = 
                     "Attaching File ... Please Wait";
               }
            }
         }
      </script>
      
   </head>
   <body>
      
      <table width = "100%" height = "100%" border = "0" 
         cellpadding = "0" cellspacing = "0">
         <tr>
            <td align = "center">
               <form name = "filepost" method = "post" 
                  action = "file.php" enctype = "multipart/form-data" id = "file">
                  
                  <table width = "300" border = "0" cellspacing = "0" 
                     cellpadding = "0">
							
                     <tr valign = "bottom">
                        <td height = "20">Your Name:</td>
                     </tr>
                     
                     <tr>
                        <td><input name = "from" type = "text" 
                           id = "from" size = "30"></td>
                     </tr>
                     
                     <tr valign = "bottom">
                        <td height = "20">Your Email Address:</td>
                     </tr>
                     
                     <tr>
                        <td class = "frmtxt2"><input name = "emaila"
                           type = "text" id = "emaila" size = "30"></td>
                     </tr>
                     
                     <tr>
                        <td height = "20" valign = "bottom">Attach File:</td>
                     </tr>
                     
                     <tr valign = "bottom">
                        <td valign = "bottom"><input name = "filea" 
                           type = "file" id = "filea" size = "16"></td>
                     </tr>
                     
                     <tr>
                        <td height = "40" valign = "middle"><input 
                           name = "Reset2" type = "reset" id = "Reset2" value = "Reset">
                        <input name = "Submit2" type = "submit" 
                           value = "Submit" onClick = "return CheckData45()"></td>
                     </tr>
                  </table>
                  
               </form>
               
               <center>
                  <table width = "400">
                     
                     <tr>
                        <td id = "one">
                        </td>
                     </tr>
                     
                  </table>
               </center>
               
            </td>
         </tr>
      </table>
      
   </body>
</html>
]]>
http://virendrayadav.com/blog/sending-emails-using-php/feed/ 0
file handling in php http://virendrayadav.com/blog/file-handling-in-php/ http://virendrayadav.com/blog/file-handling-in-php/#respond Wed, 15 Mar 2017 18:04:36 +0000 http://virendrayadav.com/blog/?p=157

This chapter will explain following functions related to files −

  • Opening a file
  • Reading a file
  • Writing a file
  • Closing a file

Opening and Closing Files

The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate.

Files modes can be specified as one of the six options in this table.

Mode Purpose
r Opens the file for reading only.

Places the file pointer at the beginning of the file.

r Opens the file for reading and writing.

Places the file pointer at the beginning of the file.

w Opens the file for writing only.

Places the file pointer at the beginning of the file.

and truncates the file to zero length. If files does not

exist then it attempts to create a file.

w Opens the file for reading and writing only.

Places the file pointer at the beginning of the file.

and truncates the file to zero length. If files does not

exist then it attempts to create a file.

a Opens the file for writing only.

Places the file pointer at the end of the file.

If files does not exist then it attempts to create a file.

a Opens the file for reading and writing only.

Places the file pointer at the end of the file.

If files does not exist then it attempts to create a file.

If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file.

After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.

Reading a file

Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes.

The files length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.

So here are the steps required to read a file with PHP.

  • Open a file using fopen() function.
  • Get the file’s length using filesize() function.
  • Read the file’s content using fread() function.
  • Close the file with fclose() function.

The following example assigns the content of a text file to a variable then displays those contents on the web page.

<html>

   <head>
      <title>Reading a file using PHP</title>
   </head>
   
   <body>
      
      <?php
         $filename = "tmp.txt";
         $file = fopen( $filename, "r" );
         
         if( $file == false ) {
            echo ( "Error in opening file" );
            exit();
         }
         
         $filesize = filesize( $filename );
         $filetext = fread( $file, $filesize );
         fclose( $file );
         
         echo ( "File size : $filesize bytes" );
         echo ( "<pre>$filetext</pre>" );
      ?>
      
   </body>
</html>

It will produce the following result −

Reading File

Writing a file

A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached.

The following example creates a new text file then writes a short text heading inside it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument

<?php
   $filename = "/home/user/guest/newfile.txt";
   $file = fopen( $filename, "w" );
   
   if( $file == false ) {
      echo ( "Error in opening new file" );
      exit();
   }
   fwrite( $file, "This is  a simple testn" );
   fclose( $file );
?>
<html>
   
   <head>
      <title>Writing a file using PHP</title>
   </head>
   
   <body>
      
      <?php
         $filename = "newfile.txt";
         $file = fopen( $filename, "r" );
         
         if( $file == false ) {
            echo ( "Error in opening file" );
            exit();
         }
         
         $filesize = filesize( $filename );
         $filetext = fread( $file, $filesize );
         
         fclose( $file );
         
         echo ( "File size : $filesize bytes" );
         echo ( "$filetext" );
         echo("file name: $filename");
      ?>
      
   </body>
</html>

It will produce the following result −

Writing File

 

]]>
http://virendrayadav.com/blog/file-handling-in-php/feed/ 0
function in php http://virendrayadav.com/blog/function-in-php/ http://virendrayadav.com/blog/function-in-php/#comments Tue, 28 Feb 2017 06:49:08 +0000 http://virendrayadav.com/blog/?p=154

PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.

You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.

There are two parts which should be clear to you −

  • Creating a PHP Function
  • Calling a PHP Function

In fact you hardly need to create your own PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement.

Creating PHP Function

Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called writeMessage() and then calls it just after creating it.

Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below −

<html>
   
   <head>
      <title>Writing PHP Function</title>
   </head>
   
   <body>
      
      <?php
         /* Defining a PHP Function */
         function writeMessage() {
            echo "You are really a nice person, Have a nice time!";
         }
         
         /* Calling a PHP Function */
         writeMessage();
      ?>
      
   </body>
</html>

This will display following result −

You are really a nice person, Have a nice time!

PHP Functions with Parameters

PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like. These parameters work like variables inside your function. Following example takes two integer parameters and add them together and then print them.

<html>
   
   <head>
      <title>Writing PHP Function with Parameters</title>
   </head>
   
   <body>
   
      <?php
         function addFunction($num1, $num2) {
            $sum = $num1 + $num2;
            echo "Sum of the two numbers is : $sum";
         }
         
         addFunction(10, 20);
      ?>
      
   </body>
</html>

This will display following result −

Sum of the two numbers is : 30

Passing Arguments by Reference

It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable’s value.

Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.

Following example depicts both the cases.

<html>
   
   <head>
      <title>Passing Argument by Reference</title>
   </head>
   
   <body>
      
      <?php
         function addFive($num) {
            $num += 5;
         }
         
         function addSix(&$num) {
            $num += 6;
         }
         
         $orignum = 10;
         addFive( $orignum );
         
         echo "Original Value is $orignum<br />";
         
         addSix( $orignum );
         echo "Original Value is $orignum<br />";
      ?>
      
   </body>
</html>

This will display following result −

Original Value is 10
Original Value is 16 

PHP Functions returning value

A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.

You can return more than one value from a function using return array(1,2,3,4).

Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.

<html>
   
   <head>
      <title>Writing PHP Function which returns value</title>
   </head>
   
   <body>
   
      <?php
         function addFunction($num1, $num2) {
            $sum = $num1 + $num2;
            return $sum;
         }
         $return_value = addFunction(10, 20);
         
         echo "Returned value from the function : $return_value";
      ?>
      
   </body>
</html>

This will display following result −

Returned value from the function : 30

Setting Default Values for Function Parameters

You can set a parameter to have a default value if the function’s caller doesn’t pass it.

Following function prints NULL in case use does not pass any value to this function.

<html>
   
   <head>
      <title>Writing PHP Function which returns value</title>
   </head>
   
   <body>
      
      <?php
         function printMe($param = NULL) {
            print $param;
         }
         
         printMe("This is test");
         printMe();
      ?>
      
   </body>
</html>

This will produce following result −

This is test

Dynamic Function Calls

It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.

<html>
   
   <head>
      <title>Dynamic Function Calls</title>
   </head>
   
   <body>
      
      <?php
         function sayHello() {
            echo "Hello<br />";
         }
         
         $function_holder = "sayHello";
         $function_holder();
      ?>
      
   </body>
</html>

This will display following result −

Hello

php functions – practice makes perfect

If you are new to programming, then this lesson might or might not seem like overkill. If you are having a hard time understanding lessons, the best piece of advice would be to do your best the first time, then be sure to come back tomorrow and next week and see if it makes anymore sense. Chances are, after going through this tutorial more than once, with breaks in between, this topic will be mastered.

]]>
http://virendrayadav.com/blog/function-in-php/feed/ 1
Array in php http://virendrayadav.com/blog/array-in-php/ http://virendrayadav.com/blog/array-in-php/#comments Tue, 21 Feb 2017 05:02:41 +0000 http://virendrayadav.com/blog/?p=149

What is PHP Arrays

Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name. Let’s suppose you want to store colors in your PHP script.

An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

There are three different kind of arrays and each array value is accessed using an ID c which is called array index.

  • Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.
  • Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
  • Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices

NOTE − Built-in array functions is given in function reference PHP Array Functions.

Numeric Array

These arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero.

Example

Following is the example showing how to create and access numeric arrays.

Here we have used array() function to create array. This function is explained in function reference.

<html>
   <body>
   
      <?php
         /* First method to create array. */
         $numbers = array( 1, 2, 3, 4, 5);
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
         
         /* Second method to create array. */
         $numbers[0] = "one";
         $numbers[1] = "two";
         $numbers[2] = "three";
         $numbers[3] = "four";
         $numbers[4] = "five";
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
      ?>
      
   </body>
</html>

This will produce the following result −

Value is 1 
Value is 2 
Value is 3 
Value is 4 
Value is 5 
Value is one 
Value is two 
Value is three 
Value is four 
Value is five 

Associative Arrays

The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.

To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.

NOTE − Don’t keep associative array inside double quote while printing otherwise it would not return any value.

Example

<html>
   <body>
      
      <?php
         /* First method to associate create array. */
         $salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
         
         echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
         echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
         echo "Salary of zara is ".  $salaries['zara']. "<br />";
         
         /* Second method to create array. */
         $salaries['mohammad'] = "high";
         $salaries['qadir'] = "medium";
         $salaries['zara'] = "low";
         
         echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
         echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
         echo "Salary of zara is ".  $salaries['zara']. "<br />";
      ?>
   
   </body>
</html>

This will produce the following result −

Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

Multidimensional Arrays

A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Example

In this example we create a two dimensional array to store marks of three students in three subjects −

This example is an associative array, you can create numeric array in the same fashion.

<html>
   <body>
      
      <?php
         $marks = array( 
            "mohammad" => array (
               "physics" => 35,
               "maths" => 30,	
               "chemistry" => 39
            ),
            
            "qadir" => array (
               "physics" => 30,
               "maths" => 32,
               "chemistry" => 29
            ),
            
            "zara" => array (
               "physics" => 31,
               "maths" => 22,
               "chemistry" => 39
            )
         );
         
         /* Accessing multi-dimensional array values */
         echo "Marks for mohammad in physics : " ;
         echo $marks['mohammad']['physics'] . "<br />"; 
         
         echo "Marks for qadir in maths : ";
         echo $marks['qadir']['maths'] . "<br />"; 
         
         echo "Marks for zara in chemistry : " ;
         echo $marks['zara']['chemistry'] . "<br />"; 
      ?>
   
   </body>
</html>

This will produce the following result −

Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

 

]]>
http://virendrayadav.com/blog/array-in-php/feed/ 1
control structures in php http://virendrayadav.com/blog/control-structures-in-php/ http://virendrayadav.com/blog/control-structures-in-php/#respond Thu, 09 Feb 2017 09:35:40 +0000 http://virendrayadav.com/blog/?p=146

Control Structures

Control Structures are loops, like for, and conditionals, such as if. Most of these will be familiar to the javascript programmer, and this page is basically a list. The following exist in php:

if and else

These are exactly the same as javascript and other languages.

if ($a==$b) {

print “The same”;

}

else {

print “They aren’t the same”;

}

There is an alternative way of writing the if statement. For instance:

<script type=“text/javascript”>

<?php
$a=5;
if(
$a==5):?>alert(“It’s five!”);
<?php
endif;
?>

//result: alert saying “It’s five”

</script>

The condition, if ($a==5) is followed by a colon (:), and the end of the block of statements is followed by endif (in php tags). In this way, the statement is not php, and in this case it is javascript.

In the alternative styles, instead of having two curly brackets {} the code replaces the first with a colon and the last with an end… in the case of if, it is endif. In other cases, endwhile, endfor, etc.

If there are other conditions, such as ifelse, then this new condition acts as the closing curly bracket for the if-statement, and the the endif, at the end of the block of code, acts as the final bracket. For instance:

if($a==5): //note colon
print”a equals 5″;
print”…”;
elseif($a==6): // the elseif effectively ends the if-statement and replaces a }
//note the colon after ifelse(…)!
print”a equals 6″;
print”!!!”;
else : //This acts as the end bracket } for the elseif
print”a is neither 5 nor 6″;
endif; // The endif acts as the final curly bracket for the BLOCK of statements

Below is a more complex example:

<script type=“text/javascript”>

<?php

$a=6;

if($a==5): //note colon

?>

document.write(“It’s five!”) ;

<?php

elseif($a==6): //colon!

?>

document.write(“It’s six!”);

<?php

else:

?>

document.write(“It’s neither six nor five”);

<?php

endif;

//result: It’s six!

?>

</script>

Fundamentally, you can put elseif within the if block between the colon (:) and endif;

elseif

elseif, which you can also write else if, gives you a second if-statement. The first if-condition, if met, is run, and any other elseif conditions, even if met are not run. So in the example below, the if-statement is met, so the program outputs Hello Tom, and not Hello Tom 2, even though the relevant elseif condition has been met. That is, elseif acts like a switch, and the control structure is exited at the first match.

$a=“Tom”;

if($a==“Tom”){

print“Hello Tom”;}

elseif($a==“Beryl”){

print“Hello Beryl”;

}

else if ($a==“Tom”){

print “Hello Tom 2”;

}

else {

print“I don’t know you!”;

}

//result: Hello Tom

while

The while loop is the same as in javascript:

$i=1;

while ($i<10){

print “Hello”;

$i++;

}

Ensure the while loop will exit! Forgetting $i++ means it will go on until the browser gets bored!

The next example uses the alternative style:

<?php

$i=1;

while($i<=10): //note the colon!

?>

Hello

<?php

$i++;

endwhile; // tells php the while is done

//result: HelloHelloHelloHelloHelloHelloHelloHelloHelloHello

?>

In the alternative style, the first bracket { is replaced with a colon: the final curly bracket } is replaced with endwhile.

do..while

The do..while loop is similar to the while loop, however, the while loop will not run if the condition is not met. The do..while loop, on the contrary, will always run at least once.

In the example below, the do..while loop runs once, even though the condition is never met (1 isn’t bigger than 100):

$i=0;

do{

print “The number is $i”;

}

while($i>100);

//result: The number is 0

for

The for loop is the same as javascript’s:

for($i=1;$i<=2;$i++){

print “This is $i<br>”;

}

//This is 1

//This is 2

The for loop can be written in various ways. One additional way is as follows:

for($i=1;$i<=3;print “This time it’s $i “,$i++);

//result: This time it’s 1 This time it’s 2 This time it’s 3

Quite neat isn’t it?

foreach

This is used to access the items in an array. For instance:

$arr=array(“cat”,“dog”,“aadvark”);

foreach($arr as $value){

echo“Value: $value<br>\n;

//Value: cat
//Value: dog
//Value: aadvark

This example shows the keys and values of an associative array:

$a=array(“fruit”=>“apple”,“meat”=>“ardvaak”,“vegetables”=>“potatoes”,“sweet”=>“pecan pie”);

foreach($a as $k=>$v){

print“\$a[$k]=>$v.\n;

};

//result: $a[fruit]=>apple. $a[meat]=>ardvaak. $a[vegetables]=>potatoes. $a[sweet]=>pecan pie.

break and continue

Break and continue are familiar to javascript programmers. Break exits a for, while, or switch structure. And continue exits the current pass in the loop and begins with the next. You can determine how many loops to break out of, or to continue from.

switch

The switch statement is also the same as the one in javascript. A switch statement will continue to, in the example below, print all the statements after finding one that is true, so breaks are used to prevent this. Each statement is followed by a break, usually.

$i=1;

switch($i){ //the variable is in brackets and the cases are in curly brackets

case 0:

print “zero”;

break;

case 1:

print “one”;

break;

default: //You can do a default case where the variable is something else!

print “whatever it is, it isn’t 0, 1 or 2”;

}

//result: one

The switch statement can deal with any simple type of data such as integers, floats and strings. This next example is the same as before in structure, except it uses strings:

$i=“tomatoes”;

switch ($i){

case “potatoes”:

print “spuds”;

break;

case “tomatoes”:

print “toms”;

break;

default:

print “Well, it could be anything!”;

}

//result: toms

Finally…


In this article we have covered the two types of Control Structures that PHP supports: Conditional Statements and Control Loops. These Structures are at the core of controlling program flow; the concepts introduced here will be used extensively from now on.

Next time, we will take take a look at pre-defined and user defined functions, which also play an important roll in the logical development and execution of a script.

Things to Remember:

  • Control Structures are at the core of programming flow, allowing you to branch the execution of scripts based on input and easily handle repeatitive tasks.
  • There are two types of Control Structures in PHP: Conditional Statements and Control Loops.
  • Conditional Statements and Loops having only one nested statement do not require brackets, however programmers frequently use them to make code more understandable. Nested statements are often indented for the same reason.
  • Break; can be used to end the execution of the current case. It can also be used to break out of for loops and while loops. Exit; terminates the execution entire script, and may be used anywhere within the script.

]]>
http://virendrayadav.com/blog/control-structures-in-php/feed/ 0
Operators In PHP http://virendrayadav.com/blog/operators-in-php/ http://virendrayadav.com/blog/operators-in-php/#comments Tue, 24 Jan 2017 17:57:05 +0000 http://virendrayadav.com/blog/?p=142

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. PHP language supports following type of operators.

  • Arithmetic Operators
  • Comparison Operators
  • Logical (or Relational) Operators
  • Assignment Operators
  • Conditional (or ternary) Operators

Lets have a look on all operators one by one.

Arithmetic Operators

There are following arithmetic operators supported by PHP language −

Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example
+ Adds two operands A + B will give 30
Subtracts second operand from the first A – B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increment operator, increases integer value by one A++ will give 11
Decrement operator, decreases integer value by one A– will give 9

Comparison Operators

There are following comparison operators supported by PHP language

Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example
== Checks if the value of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

Logical Operators

There are following logical operators supported by PHP language

Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example
and Called Logical AND operator. If both the operands are true then condition becomes true. (A and B) is true.
or Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. (A or B) is true.
&& Called Logical AND operator. If both the operands are non zero then condition becomes true. (A && B) is true.
|| Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. (A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is false.

Assignment Operators

There are following assignment operators supported by PHP language −

Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C – A
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A

Conditional Operator

There is one more operator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditional operator has this syntax −

Operator Description Example
? : Conditional Expression If Condition is true ? Then value X : Otherwise value Y

Operators Categories

All the operators we have discussed above can be categorised into following categories −

  • Unary prefix operators, which precede a single operand.
  • Binary operators, which take two operands and perform a variety of arithmetic and logical operations.
  • The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.
  • Assignment operators, which assign a value to a variable.

Precedence of PHP Operators

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity
Unary ! ++ — Right to left
Multiplicative * / % Left to right
Additive + – Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= Right to left

 

]]>
http://virendrayadav.com/blog/operators-in-php/feed/ 9
PHP Variables and Constants http://virendrayadav.com/blog/php-variables-and-constants/ http://virendrayadav.com/blog/php-variables-and-constants/#comments Sat, 14 Jan 2017 17:33:14 +0000 http://virendrayadav.com/blog/?p=139

Variables are used for storing values that can change over the course of a script, whereas the constants are used for storing fixed values that doesn’t change.

The main way to store information in the middle of a PHP program is by using a variable.

Here are the most important things to know about variables in PHP.

  • All variables in PHP are denoted with a leading dollar sign ($).
  • The value of a variable is the value of its most recent assignment.
  • Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
  • Variables can, but do not need, to be declared before assignment.
  • Variables in PHP do not have intrinsic types – a variable does not know in advance whether it will be used to store a number or a string of characters.
  • Variables used before they are assigned have default values.
  • PHP does a good job of automatically converting types from one to another when necessary.
  • PHP variables are Perl-like.

PHP has a total of eight data types which we use to construct our variables −

  • Integers − are whole numbers, without a decimal point, like 4195.
  • Doubles − are floating-point numbers, like 3.14159 or 49.1.
  • Booleans − have only two possible values either true or false.
  • NULL − is a special type that only has one value: NULL.
  • Strings − are sequences of characters, like ‘PHP supports string operations.’
  • Arrays − are named and indexed collections of other values.
  • Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
  • Resources − are special variables that hold references to resources external to PHP (such as database connections).

The first five are simple types, and the next two (arrays and objects) are compound – the compound types can package up other arbitrary values of arbitrary type, whereas the simple types cannot.

We will explain only simple data type in this chapters. Array and Objects will be explained separately.

Integers

They are whole numbers, without a decimal point, like 4195. They are the simplest type .they correspond to simple whole numbers, both positive and negative. Integers can be assigned to variables, or they can be used in expressions, like so −

$int_var = 12345;
$another_int = -12345 + 12345;

Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal format is the default, octal integers are specified with a leading 0, and hexadecimals have a leading 0x.

For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).

Doubles

They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal places needed. For example, the code −

<?php
   $many = 2.2888800;
   $many_2 = 2.2111200;
   $few = $many + $many_2;
   
   print("$many + $many_2 = $few <br>");
?>

It produces the following browser output −

2.28888 + 2.21112 = 4.5

Boolean

They have only two possible values either true or false. PHP provides a couple of constants especially for use as Booleans: TRUE and FALSE, which can be used like so −

if (TRUE)
   print("This will always print<br>");

else
   print("This will never print<br>");

Interpreting other types as Booleans

Here are the rules for determine the “truth” of any value not already of the Boolean type −

  • If the value is a number, it is false if exactly equal to zero and true otherwise.
  • If the value is a string, it is false if the string is empty (has zero characters) or is the string “0”, and is true otherwise.
  • Values of type NULL are always false.
  • If the value is an array, it is false if it contains no other values, and it is true otherwise. For an object, containing a value means having a member variable that has been assigned a value.
  • Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).
  • Don’t use double as Booleans.

Each of the following variables has the truth value embedded in its name when it is used in a Boolean context.

$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";

NULL

NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it like this −

$my_var = NULL;

The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just as well have typed −

$my_var = null;

A variable that has been assigned NULL has the following properties −

  • It evaluates to FALSE in a Boolean context.
  • It returns FALSE when tested with IsSet() function.

Strings

They are sequences of characters, like “PHP supports string operations”. Following are valid examples of string

$string_1 = "This is a string in double quotes";
$string_2 = 'This is a somewhat longer, singly quoted string';
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.

<?php
   $variable = "name";
   $literally = 'My $variable will not print!';
   
   print($literally);
   print "<br>";
   
   $literally = "My $variable will print!";
   print($literally);
?>

This will produce following result −

My $variable will not print!\n
My name will print

There are no artificial limits on string length – within the bounds of available memory, you ought to be able to make arbitrarily long strings.

Strings that are delimited by double quotes (as in “this”) are preprocessed in both the following two ways by PHP −

  • Certain character sequences beginning with backslash (\) are replaced with special characters
  • Variable names (starting with $) are replaced with string representations of their values.

The escape-sequence replacements are −

  • \n is replaced by the newline character
  • \r is replaced by the carriage-return character
  • \t is replaced by the tab character
  • \$ is replaced by the dollar sign itself ($)
  • \” is replaced by a single double-quote (“)
  • \\ is replaced by a single backslash (\)

Here Document

You can assign multiple lines to a single string variable using here document −

<?php
   $channel =<<<_XML_
   
   <channel>
      <title>What's For Dinner</title>
      <link>http://menu.example.com/ </link>
      <description>Choose what to eat tonight.</description>
   </channel>
_XML_;
   
   echo <<<END
   This uses the "here document" syntax to output multiple lines with variable 
   interpolation. Note that the here document terminator must appear on a line with 
   just a semicolon. no extra whitespace!
   

END;
   
   print $channel;
?>

This will produce following result −

This uses the "here document" syntax to output
multiple lines with variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!

<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>

Variable Scope

Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types −

Variable Naming

Rules for naming a variable is −

  • Variable names must begin with a letter or underscore character.
  • A variable name can consist of numbers, letters, underscores but you cannot use characters like + , – , % , ( , ) . & , etc

There is no size limit for variables.

]]>
http://virendrayadav.com/blog/php-variables-and-constants/feed/ 4
JSON encode and decode on PHP http://virendrayadav.com/blog/json-encode-and-decode-on-php/ http://virendrayadav.com/blog/json-encode-and-decode-on-php/#comments Wed, 04 Jan 2017 18:06:05 +0000 http://virendrayadav.com/blog/?p=136

JSON makes dealing with data in your app exceptionally easy and manageable. The best part about JSON is you can look at it and understand it. It’s not like the confusing spaghetti DOM that you get with XML, it’s a lean minimal representation of your data. If you’re dealing with chunks of data in your app, you want to be using JSON.

So while your app will happily eat up all the JSON you can throw at it, you still need to make it in the first place – and/or have a server side app that is capable of reading it. If, like me, you use PHP to handle things on a server then things are pretty straightforward. You can use PHP’s json_encode and json_decode functions. Encode will take your arrays, or objects, and create a JSON string of your data. While decode will take a JSON string, sent from your app, and turn it into an array or object.

JSON encode function

In PHP, json_encode() is used to convert PHP supported data type into JSON formatted string to be returned as a result of JSON encode operation. This function accepts the following set of arguments.

  • Data to be encoded.
  • Options with JSON encode constants to reflect effects on encoding behavior.
  • Depth limit for performing recursive encoding with nested levels of input.

Predefined JSON Constants

For PHP JSON encode, the following list of constants will be used for the options parameter of json_encode() function.

    • JSON_HEX_TAG – Used to encode HTML content by replacing < and > symbol with u003C and u003E.
    • JSON_HEX_AMP – Used to encode data by replacing ampersand symbol (&) with u0026.
    • JSON_HEX_APOS – encode apostrophe (‘) with u0027.
    • JSON_HEX_QUOT – converts double quotes (“) into u0022.
    • JSON_FORCE_OBJECT – Using this, json_encode will return object for given input data except associative array.
    • JSON_NUMERIC_CHECK – PHP JSON encode function will return numbers as a result of encoding given number with string data type.
    • JSON_BIGINT_AS_STRING – This constant is used to convert the log integer value as string.
    • JSON_PRETTY_PRINT – pretty print is used for adding white space with the JSON formatted data.
    • JSON_UNESCAPED_SLASHES – It prevents from escaping slashes (/).
    • JSON_UNESCAPED_UNICODE – It prevents from escaping unicode characters.

Example

The following example shows how to convert an array into JSON with PHP −

<?php
   $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
   echo json_encode($arr);
?>

While executing, this will produce the following result −

{"a":1,"b":2,"c":3,"d":4,"e":5}

The following example shows how the PHP objects can be converted into JSON −

<?php
   class Emp {
      public $name = "";
      public $hobbies  = "";
      public $birthdate = "";
   }
	
   $e = new Emp();
   $e->name = "sachin";
   $e->hobbies  = "sports";
   $e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p");
   $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03"));

   echo json_encode($e);
?>

While executing, this will produce the following result −

{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}

Decoding JSON in PHP (json_decode)

PHP json_decode() function is used for decoding JSON in PHP. This function returns the value decoded from json to appropriate PHP type.

Syntax

mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

Paramaters

  • json_string − It is an encoded string which must be UTF-8 encoded data.
  • assoc − It is a boolean type parameter, when set to TRUE, returned objects will be converted into associative arrays.
  • depth − It is an integer type parameter which specifies recursion depth
  • options − It is an integer type bitmask of JSON decode, JSON_BIGINT_AS_STRING is supported.

Example

The following example shows how PHP can be used to decode JSON objects −

<?php
   $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

   var_dump(json_decode($json));
   var_dump(json_decode($json, true));
?>

While executing, it will produce the following result −

object(stdClass)#1 (5) {
   ["a"] => int(1)
   ["b"] => int(2)
   ["c"] => int(3)
   ["d"] => int(4)
   ["e"] => int(5)
}

array(5) {
   ["a"] => int(1)
   ["b"] => int(2)
   ["c"] => int(3)
   ["d"] => int(4)
   ["e"] => int(5)
}

Note: While passing associative array or object with key and value pair for json_decode(), the key value should be enclosed within double quotes. Otherwise, json_decode() will return NULL.

]]>
http://virendrayadav.com/blog/json-encode-and-decode-on-php/feed/ 2
User Login Session Timeout Logout in PHP http://virendrayadav.com/blog/user-login-session-timeout-logout-in-php/ http://virendrayadav.com/blog/user-login-session-timeout-logout-in-php/#comments Tue, 27 Dec 2016 18:13:46 +0000 http://virendrayadav.com/blog/?p=133

This PHP tutorial is used for setting user login session expiration time for the logged-in user. Once, this time is elapsed then the user no longer access the authenticated pages of the application. In previous tutorial, we have created session variables once an user logged in to our application.

In this tutorial we are going to add current logged-in timestamp to a session. Using this timestamp we are checking if the login session expiration time is reached. If so,  the user will be logged out.

HTML code for User Login

This code is for showing login form to the user.

<form name="frmUser" method="post" action="">
<?php if($message!="") { ?>
<div class="message"><?php echo $message; ?></div>
<?php } ?>
<table border="0" cellpadding="10" cellspacing="1" width="100%" class="tblLogin">
<tr class="tableheader">
<td align="center" colspan="2">Enter Login Details</td>
</tr>
<tr class="tablerow">
<td align="right">Username</td>
<td><input type="text" name="user_name"></td>
</tr>
<tr class="tablerow">
<td align="right">Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr class="tableheader">
<td align="center" colspan="2"><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form>

Creating User Login Session

In this code we are adding logged-in user id and logged-in time to a session variable. Then, we are invoking a PHP function to check if the login session expiration time is elapsed. If it is not reached, then the user will be redirected to the dashboard.

if(count($_POST)>0) {
	if( $_POST["user_name"] == "admin" and $_POST["password"] == "admin") {
		$_SESSION["user_id"] = 1001;
		$_SESSION["user_name"] = $_POST["user_name"];
		$_SESSION['loggedin_time'] = time();  
	} else {
		$message = "Invalid Username or Password!";
	}
}

if(isset($_SESSION["user_id"])) {
	if(!isLoginSessionExpired()) {
		header("Location:user_dashboard.php");
	} else {
		header("Location:logout.php?session_expired=1");
	}
}

PHP Function for Checking Login Session Timeout

This function will be invoked at the begining of all authenticated pages. This function returns TRUE if the user login session is expired, FALSE otherwise.

function isLoginSessionExpired() {
	$login_session_duration = 10; 
	$current_time = time(); 
	if(isset($_SESSION['loggedin_time']) and isset($_SESSION["user_id"])){  
		if(((time() - $_SESSION['loggedin_time']) > $login_session_duration)){ 
			return true; 
		} 
	}
	return false;
}

User Login Session Expiration Logout

This logout.php page will unset logged-in user session and check for the status of session_expired flag. If it is set, then the login session timeout message will be displayed to the user.

session_start();
unset($_SESSION["user_id"]);
unset($_SESSION["user_name"]);
$url = "index.php";
if(isset($_GET["session_expired"])) {
	$url .= "?session_expired=" . $_GET["session_expired"];
}
header("Location:$url");

What will this code do?

First it take time from session that we have stored recently in above line, then it will take current time and subtract it from current time. If  the result is greater than 30 minutes (you can change as your wish) it will log out the user and redirect him to our login page and if the result is less than 30 minutes it will store new time in session that is our current time.

 

 

]]>
http://virendrayadav.com/blog/user-login-session-timeout-logout-in-php/feed/ 1
PHP include and require Statements http://virendrayadav.com/blog/php-include-and-require-statements/ http://virendrayadav.com/blog/php-include-and-require-statements/#respond Tue, 20 Dec 2016 17:56:43 +0000 http://virendrayadav.com/blog/?p=130

It is possible to insert the content of one PHP file into another PHP file (before the server executes it), with the include or require statement.

The include and require statements are identical, except upon failure:

  • require will produce a fatal error (E_COMPILE_ERROR) and stop the script
  • include will only produce a warning (E_WARNING) and the script will continue

So, if you want the execution to go on and show users the output, even if the include file is missing, use the include statement. Otherwise, in case of FrameWork, CMS, or a complex PHP application coding, always use the require statement to include a key file to the flow of execution. This will help avoid compromising your application’s security and integrity, just in-case one key file is accidentally missing.

Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. Then, when the header needs to be updated, you can only update the header include file.

The include() Function

The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.

Assume you want to create a common menu for your website. Then create a file menu.php with the following content.

<a href="http://www.tutorialspoint.com/index.htm">Home</a> - 
<a href="http://www.tutorialspoint.com/ebxml">ebXML</a> - 
<a href="http://www.tutorialspoint.com/ajax">AJAX</a> - 
<a href="http://www.tutorialspoint.com/perl">PERL</a> <br />

Now create as many pages as you like and include this file to create header. For example now your test.php file can have following content.

<html>
   <body>
   
      <?php include("menu.php"); ?>
      <p>This is an example to show how to include PHP file!</p>
      
   </body>
</html>

The require() Function

The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.

So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.

You can try using above example with require() function and it will generate same result. But if you will try following two examples where file does not exist then you will get different results.

<html>
   <body>
   
      <?php include("xxmenu.php"); ?>
      <p>This is an example to show how to include wrong PHP file!</p>
      
   </body>
</html>

This will produce the following result −

This is an example to show how to include wrong PHP file!

Now lets try same example with require() function.

<html>
   <body>
       
       <?php require("xxmenu.php"); ?>
       <p>This is an example to show how to include wrong PHP file!</p>
   
   </body>
</html>

This time file execution halts and nothing is displayed.

NOTE − You may get plain warning messages or fatal error messages or nothing at all. This depends on your PHP Server configuration.

]]>
http://virendrayadav.com/blog/php-include-and-require-statements/feed/ 0