Wednesday, 6 April 2016

Tuesday, 5 April 2016

PHP 5 File Upload

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

PHP - Sessions

Make test.php in your root folder.

<?php
   session_start();
   if( isset( $_SESSION['counter'] ) ) {
      $_SESSION['counter'] += 1;
   }else {
      $_SESSION['counter'] = 1;
   }
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
?>
<html>
   <head>
      <title>Setting up a PHP session</title>
   </head>
   <body>
      <?php  echo ( $msg ); ?>
   </body>
</html>

What is the difference between $message and $$message?


It is a classic example of PHP’s variable variables. take the
following example.$message = “Mizan”;$$message = “is a moderator of PHPXperts.”;$message is a simple PHP variable that we are used to. But the
$$message is not a very familiar face. It creates a variable name $mizan
with the value “is a moderator of PHPXperts.” assigned. break it like
this${$message} => $mizanSometimes it is convenient to be able to have variable variable
names. That is, a variable name which can be set and used dynamically.

What is the difference between mysql_fetch_object and mysql_fetch_array?

mysql_fetch_object() is similar tomysql_fetch_array(), with one difference –
an object is returned, instead of an array. Indirectly, that means that
you can only access the data by the field names, and not by their
offsets (numbers are illegal property names).

Monday, 4 April 2016

Functions in PHP

  1. Besides control and variables are PHP scripts through function calls. If the same code is executing this program code is often outsourced to a function. So instead of having the same code every time you call in the appropriate places on only the function, which then performs the actual work.
    The behavior of a function is affected by their parameters. A function can have any number of parameters, including parameters not exactly as an infinite number of parameters. Further, a function return value. This is also the standard use of a function, it will pass parameters and the function returns a value based on this back. For example, the sin function returns the sine of the given radian value.
    <?php
    sin(3.1415);
    ?>
  2. Define your own functions
    Sooner or later we want not only the functionality provided by using special PHP define your own functions. A function definition starts with the keyword function in PHP.
    <? Php
    function
    ?>
    This is followed by the actual name of the function. The name itself is subject to common rules such as not begin with numbers. Furthermore, the functions have two underscores (__) begin special functionality. You should use this function only when they want exactly the functionality that is described in the manual.
    <? Php
    function myFunction
    ?>
    Like a function call now follows an open parenthesis (. According to the clamp can now variables for the parameters are given. With the number of variables (comma separated) so you need to decide the number of parameters. However if you are planning a function with any to define many parameters you are at this point no parameters at all and use the functions in the function body func_get_args, func_get_arg and func_num_args. The parameter list is then finished with the closing parenthesis).
    <? Php
    function myFunction ($ param1, $ param2)
    ?>
    The contents of the function starts with an opening curly brace {. Now you can write any PHP code. At the end of the function body ends with a closing curly chamber }.
    <? Php
    function myFunction ($ param1, $ param2) {
       / / Here now follows
       / / Normal php code
    }
    ?>
    For typical programming style to indent the code within the function by 4 spaces. Thus it can be seen where the function starts (the function keyword) and where it ends (at the closing brace}).
    Within the function, the parameter variables can be used. In addition to the superglobal variables no further variables are otherwise available. This is called also variable scope. The variable parameters are then filled in accordance with the values ​​of the function call. If the parameters for the function are variables whose values ​​are passed, but not the variable itself in first place, it is therefore not possible to change variables that are used outside the function.
    <? Php
    function myFunction () {
       echo $ var / / help, where is defined $ var?
    }
    $ Var = 'HTML';
    myFunction () / / will not work because the only function parameters and variables
                    / / Super globals are available
    ?>
    3 Optional parameters
    In PHP, it is allowed to define which one is not used later in a function call parameters. Thus it is e.g. possible to call the function although theoretically supports 3 parameters a function with only one parameter. So as to define a function assigns default values ​​to the parameters in the parameter list. It is done by specifying an assignment for the parameter. When the function is called with a parameter value that is used for the variable parameters. When the function is called without the parameter as the parameter variable contains the specified default value.
    <? Php
    function myFunction ($ x, $ test = 'foobar') {
       echo 'x has the value: "' $ x.. '" test and has the value: "' $ test.. '"';
    }
    myFunction (4, 'word') / / outputs 4 and word of
    myFunction (5) / / outputs 5 and foobar
    myFunction () / / not possible since at least one parameter is required
    myFunction (1, 2, 3) / / possible, but the third parameter is lost
    ?>
    4 Return value of functions
    Although you use any functions in PHP code, as well as echo, it is customary return a calculated value for a function. This is implemented in PHP with the language construct return. It got to a value or a variable that you want to return.
    <? Php
    function myFunction () {
       do_that () / / is still running
       return 300;
       mach_das () / / is not running, as was leaving the function / closed
    }
    echo myFunction () / / outputs 300 from
    ?>
    With the return function is terminated at the same time. This can be done at any point, if it makes sense. In calculating the sine of the value 0 for example be expected not great but there is a case distinction quite early to the value 0 is returned.
    It is also possible to exit a function and return with it to indicate no return value. This makes only sense if not expected is that a function has a return value.
    <? Php
    function myFunction () {
       / / Code anderere
       return;
    }
    myFunction () / / works without problems
    My $ var = function () / / works, $ var got the value NULL (a special data type)
    ?>
    5 Documentation of own functions
    Functions that are provided by PHP described in detail on the official website. Accordance with specially created features missing such a documentation. You may guess the functionality of the function name. For complex functions are hoping for a good documentation. For this purpose they PHPDocs. Before the actual function to add a PHPDoc comment which describes the function.
    <? Php
    / **
    * Returns a square number.
    *
    * This function is passed a parameter and returns
    * Square of this function back.
    *
    * @ Param x The value of the you want to have a perfect square
    * @ Return The number of square
    * /
    function square ($ x) {
       return $ x * $ x;
    }
    ?>

Arrays in PHP

An array is a collection of values in a single variable name.The variables in an array is called the array elements.Array elements are accessed using a single name and an indexed number represending the postion of the elements with in the array.The lenght of an array will be less than the actual length.Since index is starts with zero.We can insert the values for each elemnets in an array by using a subscript as follows,
<?php
$a [0] = "apple";
$a [1] = "cherry";
$a [2] = "plum";
?>
We can also use array() function to declare an array of predifined values
<?php
$a = array("apple","cherry","plum");
?>
Values taken from the array is similar to assign values to the array.
<?php
$abc = $a[2];
?>
Now the value of the variable $abc will be "plum" , Loops are widely used to manipulate the arrays.The following code is used for assigning and printing the values in an array.
<?php
for($i=1;$i<=10;$i++) { $arr [$i] = $i*$i; echo $arr [$i]; }
?>
There are three types of arrays in php:-
  1. Numeric(Indexed) array - An array with a numeric index
  2. Associative array - An array where each ID key is associated with a value
  3. Multidimensional array - An array containing one or more arrays

Numeric Array

Numeric or Indexed array has numeric keys that start with zero.Any kind of values can be assigned in the elements of the array.The following code shows how to assigning values to an indexed array. 
<?php
$a = array("apple","cherry","plum"); 
?>
Or 
<?php
$a [0] = "apple";
$a [1] = "cherry";
$a [2] = "plum"; 
?>

Associative Array

In associative array we can use user defined keys (named keys) for assigning values to the array.The usage of associative array is given below. 
<?php
$a["apple"]="Rs.72";
$a["grape"]="Rs.152";
$a["cherry"]="Rs.350"; 
?>

Multidimensional Array

A multidimensional array is an array that contains at least one other array as the value of one of the indexes.
<?php
$MDA= array(
"A" => array(0 => "red", 2 => "blue", 3 => "green"),
"B" => array(1 => "orange", 2 => "black"),
"C" => array(0 => "white", 4 => "purple", 8 => "grey")
);

echo $MDA["A"][3]; // green
echo "<br>";
echo $MDA["C"][8]; // grey
?>

PHP echo and print Statements

echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.

Thursday, 31 March 2016