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;
    }
}

?>

Friday, 30 January 2015

Errors In Php

There are three basics errors in php:

Notices:

These are non-critical errors means, if accessing a variable which never defined php show notice error for it.

<?php

echo $myvaiable; 
// print output
//Notice: Undefined variable: myvariable

?>

Warnings:

These are not critical but these are serious errors mean if user include file but it has some problem in  loading so php show warning errors.

<?php

// including file
include 'file_name.php'

 
// this will generate a warning or E_WARNING because file loading is fail 
//print output 
//Warning: include(filname.php): failed to open stream: No such file or directory
//Warning: include(): Failed opening 'filname.php' for inclusion 

?>

Fatal:

These are critial and important errors means if user call a function which not exits then its show fatal error and stop the script

<?php

// call a non-existent function
// this will generate a fatal error (E_ERROR)
callmyfunction(); 

/print output
//Fatal error: Call to undefined function callmyfunction() 

?>

Include Vs Require

The only difference in Include & Require:


  • Include show warning if any problem in file loading and script will continue.
  • Require show fatal error and if any problem in file loading its stop the script.

Tips:

  • Use Include when file is not necessary in application so its continue script if there is any problem in file.
  • Use Require when file is important for an application so its stop the script if there is any problem in file.

Require Methods

Two different method for require

Require():

Require() method use for including multiple files,its takes all content of file and copies it in the specified.
syntax for require() method as below:

<?php
require 'file_name.php';
?>

file_name.php means path of file




Require_once():

Require_once is similar as require() method ,only different is that if the code from a file has already been included, it will not be included again
syntax for require_once method as below:

<?php
require_once 'file_name.php';
?>



Include Methods



Two different methods for including files:



Include():


In php include() method use for including multiple files,its takes all content of file and copies it in the specified.

syntax for include() method as below:

<?php

include 'file_name.php';

?>


file_name.php means path of file



Include_once():


Include_once is similar as include() method ,only different is that if the code from a file has already been included, it will not be included again

syntax for include_once method as below:

<?php

include_once 'file_name.php';

?>






Thursday, 29 January 2015

Explode Vs Implode

Explode

 explode() function splits a string into  components, based on a  delimiter given by users, and create an array according to  delimiters. 

<?php

// define CSV string
$mystring= 'val1, val2val3'; 

// split into individual words 
$myarray = explode(', ', $mystring); 

print_r($myarray); 

//print output Array ( [0] => val1 [1] => val2 [2] => val3 )
?>



Implode

 implode() function, which creates a single string from all the elements of an array by joining them together with a  delimiter given  by users. eg:




<?php

// define array
$myarray= array ('val1', 'val2'); 

// join into single string with ' - ' 

$mystring= implode(' - ', $colors); 

echo $mystring; 


//print output val1 - val2
?>

Wednesday, 28 January 2015

Add & Remove Value In Array



<?php
//array_push use to add element in an array :

// define an array
$myarray = array('element1', 'element2', 'element3');

// add an element to the end
array_push($myarray, 'element4');

print_r($myarray);


//print output Array ( [0] => element1 [1] => element2 [2] => element3 [3] => element4 )

//array_pop use to remove value from an array :

// define an array
$myarray = array('element1', 'element2', 'element3'); 

// remove an element from the end
array_pop($myarray); 

print_r($myarray); 


//print output Array ( [0] => element1 [1] => element2  )

?>

Sort Array

As discussed in previous example about B.I.F (built in functions) php also have some bif for sort an  array:

  • sort() - sort arrays in ascending order
  • rsort() - sort arrays in descending order
  • asort() - sort associative arrays in ascending order, according to the value
  • ksort() - sort associative arrays in ascending order, according to the key
  • arsort() - sort associative arrays in descending order, according to the value
  • krsort() - sort associative arrays in descending order, according to the key.

Method to use them:
 declare array first , write method which one want to use eg:
sort($arrayname);
it will sort array in ascending order


Array Declaration Alternative Method

Arrays can also declare as:

<?php

// define an array
$myarray[0] = 'element1';
$myarray[1] = 'element2';
$myarray[2] = 'element3'; 

print_r($myarray);
//print output Array ( [0] => element1 [1] => element2 [2] => element3 )
 // OR

// define an array
$myarray[keyname0] = 'element1'; 
$myarray[keyname1] = 'element2'; 
$myarray[keyname2] = 'element3'; 

print_r($myarray);

//print output Array ( [0] => element1 [1] => element2 [2] => element3 )

?>

Arrays Key

In php we can also set keys for each element in array as below:

<?php

// define an array
$arraykeys = array('keyname1' => 'element1', 'keyname2' => 'element2', 'keyname3' => 'element3', 'keyetc' => 'etc..');
print_r($arraykeys); 

//print output Array ( [keyname1] => element1 [keyname2] => element2 [keyname3] => element3 [keyetc] => etc.. )

//we can also get single key as follow:

print_r($arraykeys['keyname1']); 

// print output element1



?>

Array Declaration

In php Array declare as below:

<?php

// define an array
$firstarray = array('firstelement', 'secondelement', 'thirdelement', 'etc..');
print_r($firstarray);
// printout  Array ( [0] => firstelement [1] => secondelement [2] => thirdelement [3] => etc.. )

?>

Sunday, 4 January 2015

Get Vs Post

These two methods used for requests responses between server and client.

Get:

In get we request data from a particular url or resource eg:mypage.php?variable=msg&varibale2=msg2  this method not useful when dealing with secure data

Post:

In post we submit data to specific resource or page,its more secure method than get it has no limit for data length.

Friday, 2 January 2015

Concatenation In PHP of Variables

In php concatenation operator represented by (.) Example:
<?php

$first="php";
$second="-guidelines.blogspot.com";

echo"$first"."$second"; // print output php-guidelines.blogspot.com

?>