PHP Mail

PHP mail() function is used to send email in PHP. You can send text message, html message and attachment with message using PHP mail() function.

PHP mail() function

Syntax

  1. bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )  

$to: specifies receiver or receivers of the mail. The receiver must be specified one of the following forms.

  • user@example.com
  • user@example.com, anotheruser@example.com
  • User <user@example.com>
  • User <user@example.com>, Another User <anotheruser@example.com>

$subject: represents subject of the mail.

$message: represents message of the mail to be sent.

Note: Each line of the message should be separated with a CRLF ( \r\n ) and lines should not be larger than 70 characters.

$additional_headers (optional): specifies the additional headers such as From, CC, BCC etc. Extra additional headers should also be separated with CRLF ( \r\n ).


PHP Mail Example

<?php  
   ini_set("sendmail_from", "sonoojaiswal@javatpoint.com");  
   $to = "sonoojaiswal1987@gmail.com";//change receiver address  
   $subject = "This is subject";  
   $message = "This is simple text message.";  
   $header = "From:sonoojaiswal@javatpoint.com \r\n";  
  
   $result = mail ($to,$subject,$message,$header);  
  
   if( $result == true ){  
      echo "Message sent successfully...";  
   }else{  
      echo "Sorry, unable to send mail...";  
   }  
?>  

If you run this code on the live server, it will send an email to the specified receiver.


PHP Mail: Send HTML Message

To send HTML message, you need to mention Content-type text/html in the message header.

<?php  
   $to = "abc@example.com";//change receiver address  
   $subject = "This is subject";  
   $message = "<h1>This is HTML heading</h1>";  
  
   $header = "From:xyz@example.com \r\n";  
   $header .= "MIME-Version: 1.0 \r\n";  
   $header .= "Content-type: text/html;charset=UTF-8 \r\n";  
  
   $result = mail ($to,$subject,$message,$header);  
  
   if( $result == true ){  
      echo "Message sent successfully...";  
   }else{  
      echo "Sorry, unable to send mail...";  
   }  
?>  

PHP Mail: Send Mail with Attachment

To send message with attachment, you need to mention many header information which is used in the example given below.

<?php  
  $to = "abc@example.com";  
  $subject = "This is subject";  
  $message = "This is a text message.";  
  # Open a file  
  $file = fopen("/tmp/test.txt", "r" );//change your file location  
  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@example.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  
  $result = mail ( $to, $subject, "", $header );  
  if( $result == true ){  
      echo "Message sent successfully...";  
   }else{  
      echo "Sorry, unable to send mail...";  
   }  
?>  

How to count all elements in an array in PHP?

To count all the elements in an array, PHP offers count() and sizeof() functions. The count() and sizeof() both functions are used to count all elements in an array and return 0 for a variable that has been initialized with an empty array. These are the built-in functions of PHP. We can use either count() or sizeof() function to count the total number of elements present in an array.

For example

We will discuss the program implementation for all the array elements using both count() and sizeof() methods.

Example 1: Counting using count()

<?php  
    $ele = array("Ryan", "Ahana", "Ritvik", "Amaya");  
    $no_of_ele = count($ele);  
    echo "Number of elements present in the array: ".$no_of_ele;  
?>

Output

Number of elements present in the array: 4

Example 2

<?php  
    $ele = array(14, 89, 26, 90, 36, 48, 67, 75);  
    $no_of_ele = sizeof($ele);  
    echo " Number of elements present in the array: ".$no_of_ele;  
?>  

Output

Number of elements present in the array: 8

Example 3: Counting using sizeof()

<?php  
    $ele = array("Jan", "Feb", "Mar", "Apr", "May", "Jun");  
    $no_of_ele = sizeof($ele);  
    echo " Number of elements present in the array: ".$no_of_ele;  
?>

Output

Number of elements present in the array: 6

Example 4

<?php  
    $ele = array(14, 89, 26, 90, 36, 48, 67);  
    $no_of_ele = sizeof($ele);  
    echo " Number of elements present in the array: ".$no_of_ele;  
?>

Output

Number of elements present in the array: 7

Example 5: Example using 2D array

<?php  
    $snacks = array('drinks' => array('cold coffee', 'traffic jam', 'Espresso',  
    'Americano'), 'bevrage' => array('spring rolls', 'nuddles'));  
    echo count($snacks, 1);  
    echo "</br>";  
    echo sizeof($snacks, 1);      
?>  

Output

8
8

PHP is_null() function

By using the is_null function, we can check whether the variable is NULL or not. This function was introduced in PHP 4.0.4.

SYNATX:

  1. bool is_null ( mixed $var )  

Parameter

ParameterDescriptionIs compulsory
varThe variable being evaluated.compulsory

Return Type:

The PHP is_null() function returns true if var is null, otherwise false.

Important Note:

We can unset the variable value by using the unset function.

Example 1

<?php  
    $var1 = TRUE;  
    if (is_null($var1))  
        {  
            echo 'Variable is  NULL';  
        }  
        else  
        {  
            echo 'Variable is not NULL';  
        }  
?>  

output

Variable is not NULL

Example 2

<?php  
    $x= 100;  
    unset($x);  
    echo is_null($x);  
?>  

output

1

Example 3

<?php    
    $x = NULL;   
    $y = "\0";  
    is_null($x) ? print_r("True\n") : print_r("False\n");  
    echo "<br/>";  
    is_null($y) ? print_r("True\n") : print_r("False\n");  
?>  

output

Ture

False

PHP functions

1. get_class: By using this, we can get the class name of an object.

Example 1

<?php  
    class cls1  
    {  
          
    }  
    $obj=new cls1();  
    echo get_class($obj);  
?>  

Output:

cls1

2. get_class_vars: It is used to get all variables of a class as Array elements.

Example 2

<?php  
    class cls1  
    {  
        var $x=100;  
        var $y=200;  
    }  
    print_r(get_class_vars("cls1"));  
?>  

Output:

Array([x] => 100[y]=>200)

3. get_class_methods: To get the all methods of a class as an array.

Example 3

<?php  
    class cls1  
    {  
        function fun1()  
        {  
        }  
        function fun2()  
        {  
        }  
    }  
    print_r(get_class_methods("cls1"));  
?>  

Output:

Array([0] => fun1[1] =>fun2 )

4. get_declare_classes: To get the all declare classes in current script along with predefined classes.

Example 4

<?php  
    class cls1  
    {  
      
    }  
    print_r(get_declared_classes());  
?>  

Output:

Some Helpful Functions in PHP to get the Information About Class and Object

5. get_object_vars: To get all variables of an object as an array.

Example 5

<?php  
    class cls1  
    {  
        var $x=100;  
        var $y=200;  
    }  
    $obj= new cls1();  
    print_r(get_object_vars($obj));  
?>  

Output:

Array([x] => 100[y]=>200)

6. class_exists: To check whether the specified class is existed or not.

Example 6

<?php  
    class cls1  
    {  
          
    }  
    echo class_exists("cls1");  
?>  

Output:

1

7. is_subclass_of: By using this function we can check whether the 1st class is subclass of 2nd class or not.

Example 7

<?php  
    class cls1  
    {  
          
    }  
    class cls2 extends cls1  
    {  
    }  
    echo is_subclass_of("cls2","cls1");  
?>  

Output:

1

8. method_exists: By using this function we can check whether the class method is existed or not.

Example 8

<?php  
    class cls1  
    {  
        function fun1()  
        {  
        }  
    }  
    echo method_exists("cls1","fun1");  
?>  

Output:

1

Final Keyword

  • In PHP, Final keyword is applicable to only class and class methods. We cannot declare as Final in PHP.
  • So if we declare class method as a Final then that method cannot be override by the child class.
  • Same as method if we declare class as a Final then that class cannot be extended any more.

Example 1

<?php  
      
    class base  
    {  
        final public function dis1()  
        {  
            echo "Base class..";  
        }     
    }  
    class derived extends base  
    {  
        public function dis1()  
        {  
            echo "derived class";  
        }  
    }  
    $obj = new derived();  
    $obj->dis1();  
  
?>  

Output:

Final Keyword

Abstract Class

An abstract class is a mix between an interface and a class. It can be define functionality as well as interface.

  • Classes extending an abstract class must implement all of the abstract methods defined in the abstract class.
  • An abstract class is declared the same way as classes with the addition of the ‘abstract’ keyword.

SYNTAX:

abstract class MyAbstract  
{  
    //Methods  
}  
//And is attached to a class using the extends keyword.  
class Myclass extends MyAbstract  
{  
    //class methods  
}  

Example 1

<?php  
abstract class a  
{  
abstract public function dis1();  
abstract public function dis2();  
}  
class b extends a  
{  
public function dis1()  
    {  
        echo "tutorialspro";  
    }  
    public function dis2()  
    {  
        echo "tech";     
    }  
}  
$obj = new b();  
$obj->dis1();  
$obj->dis2();  
?>  

Output:

tutorialsprotech

Example 2

<?php  
abstract class Animal  
{  
    public $name;  
    public $age;  
public function Describe()  
        {  
                return $this->name . ", " . $this->age . " years old";      
        }  
abstract public function Greet();  
    }  
class Dog extends Animal  
{  
public function Greet()  
        {  
                return "Woof!";      
        }  
      
        public function Describe()  
        {  
                return parent::Describe() . ", and I'm a dog!";      
        }  
}  
$animal = new Dog();  
$animal->name = "Bob";  
$animal->age = 7;  
echo $animal->Describe();  
echo $animal->Greet();  
?>  

Output:

Bob,7 years old,and I’m a dog!woof!

PHP Download File

PHP enables you to download file easily using built-in readfile() function. The readfile() function reads a file and writes it to the output buffer.


PHP readfile() function

Syntax

  1. int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )  

$filename: represents the file name

$use_include_path: it is the optional parameter. It is by default false. You can set it to true to the search the file in the included_path.

$context: represents the context stream resource.

int: it returns the number of bytes read from the file.


PHP Download File Example: Text File

  

<?php  
   $file_url = 'http://www.tutorialspro.com/f.txt';  
   header('Content-Type: application/octet-stream');  
   header("Content-Transfer-Encoding: utf-8");   
   header("Content-disposition: attachment; filename=\"" . 
   basename($file_url) . "\"");   
   readfile($file_url);  
?>

PHP Download File Example: Binary File

<?php  
   $file_url = 'http://www.myremoteserver.com/file.exe';  
    header('Content-Type: application/octet-stream');  
   header("Content-Transfer-Encoding: Binary");   
   header("Content-disposition: attachment; filename=\"" . 
   basename($file_url) . "\"");   
   readfile($file_url);  
?>  

PHP File Upload

PHP allows you to upload single and multiple files through few lines of code only.

PHP file upload features allows you to upload binary and text files both. Moreover, you can have the full control over the file to be uploaded through PHP authentication and file operation functions.


PHP $_FILES

The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we can get file name, file type, file size, temp file name and errors associated with file.

Here, we are assuming that file name is filename.

$_FILES[‘filename’][‘name’]

returns file name.

$_FILES[‘filename’][‘type’]

returns MIME type of the file.

$_FILES[‘filename’][‘size’]

returns size of the file (in bytes).

$_FILES[‘filename’][‘tmp_name’]

returns temporary file name of the file which was stored on the server.

$_FILES[‘filename’][‘error’]

returns error code associated with this file.


move_uploaded_file() function

The move_uploaded_file() function moves the uploaded file to a new location. The move_uploaded_file() function checks internally if the file is uploaded thorough the POST request. It moves the file if it is uploaded through the POST request.

Syntax

  1. bool move_uploaded_file ( string $filename , string $destination )  

PHP File Upload Example

<form action="uploader.php" method="post" enctype="multipart/form-data">  
    Select File:  
    <input type="file" name="fileToUpload"/>  
    <input type="submit" value="Upload Image" name="submit"/>  
</form>
<?php  
$target_path = "e:/";  
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);   
  
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {  
    echo "File uploaded successfully!";  
} else{  
    echo "Sorry, file not uploaded, please try again!";  
}  
?>  

PHP Append to File

You can append data into file by using a or a+ mode in fopen() function. Let’s see a simple example that appends data into data.txt file.

Let’s see the data of file first.

welcome to php file write

PHP Append to File – fwrite()

The PHP fwrite() function is used to write and append data into file.

Example

 

<?php  
$fp = fopen('data.txt', 'a');//opens file in append mode  
fwrite($fp, ' this is additional text ');  
fwrite($fp, 'appending data');  
fclose($fp);  
  
echo "File appended successfully";  
?>

Output:

welcome to php file write this is additional text appending data

PHP Math

PHP provides many predefined math constants and functions that can be used to perform mathematical operations.

PHP Math: abs() function

The abs() function returns absolute value of given number. It returns an integer value but if you pass floating point value, it returns a float value.Syntax

  1. number abs ( mixed $number )  

Example

 

<?php  
echo (abs(-7)."<br/>"); // 7 (integer)  
echo (abs(7)."<br/>"); //7 (integer)  
echo (abs(-7.2)."<br/>"); //7.2 (float/double)  
?> 

Output:

7 
7 
7.2

PHP Math: ceil() function

The ceil() function rounds fractions up.Syntax

  1. float ceil ( float $value )  

Example

<?php  
echo (ceil(3.3)."<br/>");// 4  
echo (ceil(7.333)."<br/>");// 8  
echo (ceil(-4.8)."<br/>");// -4  
?>  

Output:

4
8
-4

PHP Math: floor() function

The floor() function rounds fractions down.Syntax

  1. float floor ( float $value )  

Example

<?php  
echo (floor(3.3)."<br/>");// 3  
echo (floor(7.333)."<br/>");// 7  
echo (floor(-4.8)."<br/>");// -5  
?>  

Output:

3
7
-5

PHP Math: sqrt() function

The sqrt() function returns square root of given argument.Syntax

  1. float sqrt ( float $arg )  

Example

<?php  
echo (sqrt(16)."<br/>");// 4  
echo (sqrt(25)."<br/>");// 5  
echo (sqrt(7)."<br/>");// 2.6457513110646  
?>  

Output:

4
5
2.6457513110646

PHP Math: decbin() function

The decbin() function converts decimal number into binary. It returns binary number as a string.Syntax

  1. string decbin ( int $number )  

Example

<?php  
echo (decbin(2)."<br/>");// 10  
echo (decbin(10)."<br/>");// 1010  
echo (decbin(22)."<br/>");// 10110  
?>  

Output:

10
1010
10110

PHP Math: dechex() function

The dechex() function converts decimal number into hexadecimal. It returns hexadecimal representation of given number as a string.Syntax

  1. string dechex ( int $number )  

Example

 

<?php  
echo (dechex(2)."<br/>");// 2  
echo (dechex(10)."<br/>");// a  
echo (dechex(22)."<br/>");// 16  
?> 

Output:

2
a
16

PHP Math: decoct() function

The decoct() function converts decimal number into octal. It returns octal representation of given number as a string.Syntax

  1. string decoct ( int $number )  

Example

<?php  
echo (decoct(2)."<br/>");// 2  
echo (decoct(10)."<br/>");// 12  
echo (decoct(22)."<br/>");// 26  
?>  

Output:

2
12
26

PHP Math: base_convert() function

The base_convert() function allows you to convert any base number to any base number. For example, you can convert hexadecimal number to binary, hexadecimal to octal, binary to octal, octal to hexadecimal, binary to decimal etc.Syntax

  1. string base_convert ( string $number , int $frombase , int $tobase )  

Example

<?php  
$n1=10;  
echo (base_convert($n1,10,2)."<br/>");// 1010  
?>  

Output:

1010

PHP Math: bindec() function

The bindec() function converts binary number into decimal.Syntax

  1. number bindec ( string $binary_string )  

Example

  

<?php  
echo (bindec(10)."<br/>");// 2  
echo (bindec(1010)."<br/>");// 10  
echo (bindec(1011)."<br/>");// 11  
?>

Output:

2
10
11

PHP Math Functions

Let’s see the list of important PHP math functions.

FunctionDescription
abs()It is used to find the absolute (positive) value of a number.
sin()It is used to return the sine of a number.
sinh()It is used to return the hyperbolic sine of a number.
asin()It is used to find the arc sine of a number.
asinh()It is used to find the inverse hyperbolic sine of a number.
cos()It is used to find the cosine of a number.
cosh()It is used to return the cosh of a number.
acos()It is used to return the arc cosine of a number.
acosh()It is used to return the inverse hyperbolic cosine of a number.
tan()It is used to return the tangent of a number.
tanh()It is used to return the hyperbolic tangent of a number.
atan()It is used to return the arc tangent of a number in radians.
atan2()It is used to return the arc tangent of two variables x and y.
atanh()It is used to return the inverse hyperbolic tangent of a number.
base_convert()It is used to convert a number from one number base to another.
bindec()It is used to convert a binary number to a decimal number.
ceil()It is used to find round a number up to the nearest integer.
pi()It returns the approximation value of PI.
decbin()It converts a decimal number to a binary number.
dechex()It converts a decimal number to a hexadecimal number.
decoct()It converts a decimal number to an octal number
deg2rad()It converts a degree value to a radian value.
rad2deg()It converts a radian value to a degree value.
exp()It is used to calculate the exponent of e.
expm1()It is used to return exp(x) – 1.
floor()It converts round a number down to the nearest integer.
fmod()It returns the remainder of x/y.
getrandmax()It returns the largest possible value returned by rand().
hexadec()It is used to convert a hexadecimal number to a decimal number.
hypot()It is used to calculate the hypotenuse of a right-angle triangle.
is_finite()To check whether a value is finite or not.
is_infinite()It is used to check whether a value is infinite or not.
is_nan()It is used to check whether a value is ‘not-a-number’.
lcg_value()It is used to return a pseudo random number in a range between 0 and 1.
log()It is used to return the natural logarithm of a number.
log10()It is used to return the base-10 logarithm of a number.
log1p()It is used to return log(1+number).
max()It is used to return the highest value in an array, or the highest value of several specified values.
min()It returns the lowest value in an array, or the lowest value of several specified values.
getrandmax()It is used to return the maximum value by using rand().
mt_getrandmax()Returns the largest possible value returned by mt_rand().
mt_rand()Generates a random integer using Mersenne Twister algorithm.
mt_srand()Seeds the Mersenne Twister random number generator.
octdec()It is used to converts an octal number to a decimal number.
pow()It is used to return x raised to the power of y.
intdivIt returns the integer quotient of the division of dividend by divisor.
rand()It is used to generates a random integer.
round()It is used to round a floating-point number.
fmod()It is used to return the floating point remainder of the division of the argument.
sqrt()It is used to return the square root of a number.