Saturday, 31 January 2015

Form

In php form use to collect information and get or post it on the given page we will discuss later what is get or post? first check example for form

Example:


<html>
<head></head>
<body>
<form action="other_or_samepage.php" method="post">
Enter your text: <input type="text" name="txt" size="30">
<input type="submit" value="Send">
</form>
</body>
</html>

Action attribute is use to set where you want to post your data and method attribute specifies how data will passed.

Exception Example

<?php
// PHP 5
// try this code 
try { 
    $myfile = 'file.txt'; 

    // open file 
    if (!$file = fopen($myfile, 'r')) { 
        throw new Exception('Could not open file!'); 
    } 

    // read file contents 
    if (!$data = fread($file, filesize($myfile))) { 
        throw new Exception('Could not read file!'); 
    } 

    // close file 
    fclose($file); 

    // print file contents 
    echo $data; 

// catch errors if any 
catch (Exception $e) { 
    print 'Exception Custom Errors...'; 

?>

Exception

Exception in php use to control the errors(Exceptions) and throw a custom messages to user ,because of this state of code will remain same.Exception syntax in php as below :

try {
    code to handle the eceptions in this block
}
catch (exception type 1) {
    execute this block to resolve exception type 1
}
catch (exception type 2) {
    execute this block to resolve exception type 2
}
 and etc.. 

Error Handling

Errors handling can be done by using set_error_handler() method we can display custom errors by using this method eg:


<?php

//  custom error handler
set_error_handler('custom_error');

// this will genrate notice
echo $myvariable;
// custom error handler
function custom_error($type, $msg, $file, $line, $context) {
    switch ($type) {
        // notices
        case E_NOTICE:
           print "Notice Custom Message on  line $line of  $file: $msg <br />"; 
            break;
        
        // warnings
        case E_WARNING:
            // report error
            print "Non-fatal error Custom Message on line $line of $file: $msg <br />";
            break;

        // other or fatal 
        default:
            print "Fatal Error Custom Message  of type  $type on line  $line of $file: $msg <br />"; 
            break;
    }
}

?>