Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Monday, 3 April 2017

what’s an error?

what’s an error?
An error is a type of mistake. We can say an error is a condition of having incorrect or false knowledge or an error is defined as an unexpected, invalid program state from which it is impossible to recover.
Error can also be defined as "a deviation from accuracy or correctness".
A "mistake" is an error caused by a fault: the fault being misjudgment, carelessness, or forgetfulness. An error message with filename, line number and a message describing the error is sent to the browser.
What are the different kinds of errors in PHP?
Basically there are four kinds of errors in PHP, which are as follows:
·         Parse Error (Syntax Error): The parse error occurs if there is a syntax mistake in the script; the output is Parse error. A parse error stops the execution of the script. There are many reasons for the occurrence of parse errors in PHP. The common reasons for parse errors are as follows:
1.       Unclosed quotes
2.      Missing or Extra parentheses
3.      Unclosed braces
4.      Missing semicolon
Example:
<?php
echo
 "Cat";
echo
 "Dog"
echo
 "Lion";
?>
Output:
In the above code we missed the semicolon in the second line. When that happens there will be a parse or syntax error which stops execution of the script.
·         Fatal Error: Fatal errors are caused when PHP understands what you've written, however what you're asking it to do can't be done. Fatal errors stop the execution of the script. If you are trying to access the undefined functions, then the output is a fatal error.
Example:
<?php
function fun1()
{
echo "Vineet Saini";
}
fun2();
echo "Fatal Error !!";
?>
Output:
In the above code we defined a function fun1 but we call another function fun2 i.e. func2 is not defined. So a fatal error will be produced that stops the execution of the script.
·         Warning Error: Warning errors will not stop execution of the script. The main reason for warning error is to include a missing file or using the incorrect number of parameters in a function.
Example:
<?php 
echo "Warning Error!!";
include ("Welcome.php");
?>
Output:


In the above code we include a welcome.php file, however the welcome.php file does not exist in the directory. So there will be a warning error produced but that does not stop the execution of the script i.e. you will see a message Warning Error!!
·         Notice Error: Notice error is the same as a warning error i.e. in the notice error, execution of the script does not stop. Notice that the error occurs when you try to access the undefined variable, then produce a notice error.

Example:
<?php
$a="Vineet kumar saini";
echo "Notice Error !!";
echo $b;
?>
Output:
In the above code we defined a variable which named $a. But we call another variable i.e. $b, which is not defined. So there will be a notice error produced but execution of the script does not stop, you will see a message Notice Error!! 

What are the different types of errors in PHP?
Basically there are 13 types of errors in PHP, which are as follows:
1.       E_ERROR: A fatal error that causes script termination
2.      E_WARNING: Run-time warning that does not cause script termination
3.      E_PARSE: Compile time parse error
4.      E_NOTICE: Run time notice caused due to error in code
5.       E_CORE_ERROR: Fatal errors that occur during PHP’s initial startup (installation)
6.      E_CORE_WARNING: Warnings that occur during PHP’s initial startup
7.       E_COMPILE_ERROR: Fatal compile-time errors indication problem with script
8.      E_USER_ERROR: User-generated error message
9.      E_USER_WARNING: User-generated warning message
10.   E_USER_NOTICE: User-generated notice message
11.    E_STRICT: Run-time notices
12.   E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
13.   E_ALL: Catches all errors and warnings



Send Email From Server Side

//if "email" variable is filled out, send email
  if (isset($_REQUEST['email']))  {
 
  //Email information
  $admin_email = "someone@example.com";
  $email = $_REQUEST['email'];
  $subject = $_REQUEST['subject'];
  $comment = $_REQUEST['comment'];
 
  //send email
  mail($admin_email, "$subject", $comment, "From:" . $email);
 
  //Email response
  echo "Thank you for contacting us!";
  }
 
  //if "email" variable is not filled out, display the form
  else  {
?>

 <form method="post">
  Email: <input name="email" type="text" /><br />
  Subject: <input name="subject" type="text" /><br />
  Message:<br />
  <textarea name="comment" rows="15" cols="40"></textarea><br />
  <input type="submit" value="Submit" />
  </form>
 
<?php
  }
?>


Inheritance

Inheritance is a mechanism of extending an existing class by inheriting a class we create a new class with all functionality of that existing class, and we can add new members to the new class.
When we inherit one class from another we say that inherited class is a subclass and the class who has inherit is called parent class.
-We declare a new class with additional keyword extends.
- PHP only supports multilevel inheritance.
Best example of multilevel inheritance in PHP

1.       class grandParent
2.       {
3.       //Body of grand parent class
4.       }
5.       class parent extends grandParent
6.       {
7.       //Body Of parent class
8.       }
9.       class child extends parent
10.    {
11.    //Body of child class
12.    }

Above example is so clear to understand, child class is extending parent class and parent class is extending grand parent.This was a very basic example to understand the concept of multilevel inheritance in php oops.

Constructor

Constructor
void __construct ([ mixed $args = "" [, $... ]] )
The constructor is the most useful of the two, especially because it allows you to send parameters along when creating a new object, which can then be used to initialize variables on the object
PHP  allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

class Animal
{
    public $name = "No-name animal";
   
    public function __construct()
    {
        echo "I'm alive!";       
    }
}

Output


$animal = new Animal(); 

Sunday, 26 March 2017

PHP Error Handling

PHP Error Handling:-
The default error handling in PHP is very simple. An error message with filename, line number and a message describing the error are sent to the browser.

PHP Error Handling:-
When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.
This tutorial contains some of the most common error checking methods in PHP.
We will show different error handling methods:
 Simple "die()" statements
 Custom errors and error triggers
 Error reporting
Basic Error Handling : Using the die() function :-
The first example shows a simple script that opens a text file: <?php $file=fopen("welcome.txt","r"); ?>
If the file does not exist you might get an error like this:
Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:
No such file or directory in C:\webfolder\test.php on line 2

To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it: <?php if(!file_exists("welcome.txt")) { die("File not found"); } else { $file=fopen("welcome.txt","r"); } ?>
Now if the file does not exist you get an error like this:
File not found
The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.
However, simply stopping the script is not always the right way to go. Let's take a look at alternative PHP functions for handling errors.
Creating a Custom Error Handler:-
Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP.
This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context):
Syntax:-
error_function(error_level,error_message,error_file,error_line,error_context)
Parameter Description:-
error_level
Required. Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels
error_message
Required. Specifies the error message for the user-defined error
error_file
Optional. Specifies the filename in which the error occurred
error_line
Optional. Specifies the line number in which the error occurred
error_context
Optional. Specifies an array containing every variable, and their values, in use when the error occurred
Error Report levels:-
These error report levels are the different types of error the user-defined error handler can be used for: Value Constant Description:-
2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted.
8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally
256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
8191 E_ALL All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)
Now lets create a function to handle errors:-
 function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br />"; echo "Ending Script"; die(); }
The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script.
Now that we have created an error handling function we need to decide when it should be triggered.

Friday, 24 March 2017

PHP 10 Maths Function

1. PHP abs() Function:-
Definition and Usage
The abs() function returns the absolute value of a number.
Syntax
abs(x)
Parameter
Description
x
Required. A number. If the number is of type float, the return type is also float, otherwise it is integer
Example:-
<?php echo(abs(6.7) . "<br />"); echo(abs(-3) . "<br />"); echo(abs(3)); ?>
The output of the code above will be:
6.7 3 3
2. PHP base_convert() Function:-
Definition and Usage
The base_convert() function converts a number from one base to another.
Syntax
base_convert(number,frombase,tobase)
Parameter
Description
number
Required. Original value
frombase
Required. Original base of number. Frombase has to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35.
tobase
Required. The base to convert to. Tobase has to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35.
Example 1:-
Convert an octal number to a decimal number:
<?php $oct = "0031"; $dec = base_convert($oct,8,10); echo "$oct in octal is equal to $dec in decimal."; ?>
The output of the code above will be:
0031 in octal is equal to 25 in decimal.
Example 2:-
Convert an octal number to a hexadecimal number:
<?php $oct = "364"; $hex = base_convert($oct,8,16); echo "$oct in octal is equal to $hex in hexadecimal."; ?>
The output of the code above will be:
364 in octal is equal to f4 in hexadecimal.
3. PHP Ceil() Function:-
Definition and Usage
The ceil() function returns the value of a number rounded UPWARDS to the nearest integer.
Syntax
ceil(x)
Parameter
Description
x
Required. A number
Example:-
In the following example we will use the ceil() function on different numbers:
<?php echo(ceil(0.60) . "<br />"); echo(ceil(0.40) . "<br />"); echo(ceil(5) . "<br />"); echo(ceil(5.1) . "<br />"); echo(ceil(-5.1) . "<br />"); echo(ceil(-5.9)) ?>
The output of the code above will be:
1 1 5 6 -5 -5
4. PHP exp() Function:-
Definition and Usage
The exp() function returns the value of Ex, where E is Euler's constant (approximately 2.7183) and x is the number passed to it.
Syntax
exp(x)
Parameter
Description
x
Required. A number
Tips and Notes
Tip: E is the Euler's constant, which is the base of natural logarithms (approximately 2.7183).
Example
In the following example we will use the exp() function on different numbers:
<?php echo(exp(1) . "<br />"); echo(exp(-1) . "<br />"); echo(exp(5) . "<br />"); echo(exp(10)) ?>
The output of the code above will be:
2.718281828459045 0.36787944117144233 148.4131591025766 22026.465794806718
5. PHP floor() Function:-
Definition and Usage
The floor() function returns the value of a number rounded DOWNWARDS to the nearest integer.
Syntax
floor(x)
Parameter
Description
x
Required. A number
Example:-
In this example we will use the floor() function on different numbers:
<?php echo(floor(0.60) . "<br />");
echo(floor(0.40) . "<br />"); echo(floor(5) . "<br />"); echo(floor(5.1) . "<br />"); echo(floor(-5.1) . "<br />"); echo(floor(-5.9)) ?>
The output of the code above will be:
0 0 5 5 -6 -6
6. PHP fmod() Function:-
Definition and Usage
The fmod() function divides x by y and returns the remainder (modulo) of the division.
Syntax
fmod(x,y)
Parameter
Description
x
Required. A number
y
Required.
Example:-
In the following example we will use the fmod() function to return the remainder of 5/2:
<?php $r = fmod(5,2); echo $r ?>
The output of the code above will be:
1
7. PHP is_finite() Function:-
Definition and Usage
The is_finite() function returns true if the specified value is a finite number, otherwise it returns nothing.
The value is finite if it is within the allowed range for a PHP float on this platform.
Syntax
is_finite(x)
Parameter
Description
X
Required. The value to check
Example:-
<?php echo is_finite(2) . "<br />"; echo is_finite(log(0)) . "<br />"; echo is_finite(2000); ?>
The output of the code above will be:
1 1
8. PHP is_infinite() Function:-
Definition and Usage
The is_infinite() function returns true if the specified value is an infinite number, otherwise it returns nothing.
The value is infinite if it is too big to fit into a PHP float on this platform.
Syntax
is_infinite(x)
Parameter
Description
X
Required. The value to check
Example:-
<?php echo is_infinite(2) . "<br />"; echo is_infinite(log(0)) . "<br />"; echo is_infinite(2000); ?>
The output of the code above will be:
1
9. PHP lcg_value() Function:-
Definition and Usage
The lcg_value() function returns a pseudo random number in the range of 0 and 1.
Syntax
Lcg_value()
Example:-
<?php echo lcg_value(); ?>
The output of the code above could be:
0.408212029326
10. PHP log() Function:-
Definition and Usage
The log() function returns the natural logarithm (base E) of a number.
Syntax
Log(x,base)
Parameter
Description:-
X
Required. A number
base
Optional. If the base parameter is specified, log() returns logbase x. Note: The base parameter became available in PHP 4.
Tips and Notes
Note: If the parameter x is negative, -1.#IND is returned.
Example:-
In the following example we will use the log() function on different numbers:
<?php echo(log(2.7183) . "<br />"); echo(log(2) . "<br />"); echo(log(1) . "<br />"); echo(log(0) . "<br />"); echo(log(-1)) ?>
The output of the code above will be:
1.00000668491 0.69314718056 0 -1.#INF -1.#IND