Tuesday, July 19, 2016

How to preview a image before upload

How to preview a image before upload ?


<\script type="text/javascript">
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    $('#blah').attr('src', e.target.result);
                }

                reader.readAsDataURL(input.files[0]);
            }
        }
    <\/script>

<\body>
    <\form id="form1" runat="server">
        <\input type='file' onchange="readURL(this);" />
        <\img id="blah" src="#" alt="your image" />
    <\/form>
<\/body>

Note :- Before using this code remove "\" from the tags

Thursday, May 19, 2016

Magic Methods in PHP




Magic methods in php are some predefined function by php compiler which executes on some event. Magic methods start with prefix __, for example __call, __get, __set.

List of List of Magic Methods in PHP

Magic Method
Description
__construct
This magic methods is called when someone create object of your class. Usually this is used for creating constructor in php5.
__destruct
This magic method is called when object of your class is unset. This is just opposite of __construct.
__get
This method called when your object attempt to read property or variable of the class which is inaccessible or unavailable.
__set
This method called when object of your class attempts to set value of the property which is really inaccessible or unavailable in your class.
__isset
This magic methods trigger when isset() function is applied on any property of the class which isinaccessible or unavailable.
__unset
__unset is something opposite of isset method. This method triggers when unset() function called on inaccessible or unavailable property of the class.
__call
__call magic method trigger when you are attempting to call method or function of the class which is either inaccessible or unavailable.
__callstatic
__callstatic execture when inaccessible or unavailable method is in static context.
__sleep
__sleep methods trigger when you are going to serialize your class object.
__wakeup
__wakeup executes when you are un serializing any class object.
__toString
__toString executes when you are using echo on your object.
__invoke
__invoke called when you are using object of your class as function
Above list is the most conman used magic methods in php object oriented programming. Above magic methods of php executes on some specif  events occur on your class object. For example if you simply echo your object then __toString method trigger. Let us create group of related magic method and analyze how it is working.

__construct and __destruct magic method in PHP
__construct method trigger on creation of object. And __destruct triggers of deletion of object. Following is very basic example of __construct and __destruct magic method in php:

class test{
function __construct(){
echo 1;
}
function __destruct(){
echo 2;
}
}
$objT = new test(); //__construct get automatically executed and print 1 on screen
unset($objT);//__destruct triggers and print 2.

__get __set __call and __callStatic Magic Methods

__get, __set, __call and __callStatic all magic methods in php directly related with no accessible method and property of the class.
__get takes one argument and executes when any inaccessible property of the method is called. It takes name of the property as argument.
__set takes two property and executes when object try to set value in inaccessible property. It take first parameter as name of the property and second as the value which object is try to set.
__call method fires when object of your class is trying to call method of property which is either non accessible or not available. It takes 2 parameter  First parameter is string and is name of function. Second parameter is an array which is arguments passed in the function.
__callStatic is a static magic method. It executes when any method of your class is called by static techniques.

Following is example of __get , __set , __call and __callStatic magic methods

class test {
function __get($name){
echo "__get executed with name $name ";
}

function __set($name , $value){
echo "__set executed with name $name , value $value";
}

function __call($name , $parameter){
$a = print_r($parameter , true); //taking recursive array in string
echo "__call executed with name $name , parameter $a";
}

static function __callStatic($name , $parameter){
$a = print_r($parameter , true); //taking recursive array in string
echo "__callStatic executed with name $name , parameter $a";
}
}

$a = new test();
$a->abc = 3;//__set will executed
$app = $a->pqr;//__get will triggerd
$a->getMyName('ankur' , 'techflirt', 'etc');//__call willl be executed
test::xyz('1' , 'qpc' , 'test');//__callstatic will be executed
__isset and __unset magic methods
__isset and __unset magic methods in php are opposite of each other.
__isset magic methods executes when function isset() is applied on property which is not available or not defined. It takes name of the parameter as an argument.
__unset magic method triggers when unset() method is applied on the property which is either not defined or not accessible. It takes name of the parameter as an argument.
Following is example of __isset and __unset magic method in php

class test {
function __isset($name){
echo "__isset is called for $name";
}

function __unset($name){
echo "__unset is called for $name";
}
}

$a = new test();
isset($a->x);
unset($a->c);

What is a PHP Session?




When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.
So; Session variables hold information about one single user, and are available to all pages in one application.
Tip: If you need a permanent storage, you may want to store the data in a database.

Start a PHP Session

A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session and set some session variables:

Example

<\?php
// Start the session
session_start();

// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
Note: The session_start() function must be the very first thing in your document. Before any HTML tags.

Get PHP Session Variable Values

Next, we create another page called "demo_session2.php". From this page, we will access the session information we set on the first page ("demo_session1.php").
Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()).
Also notice that all session variable values are stored in the global $_SESSION variable:

Example

<\?php
session_start();

// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".
";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
Another way to show all the session variable values for a user session is to run the following code:

Example

<\?php
session_start();

print_r($_SESSION);
?>

How does it work? How does it know it's me?
Most sessions set a user-key on the user's computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key. If there is a match, it accesses that session, if not, it starts a new session.

Modify a PHP Session Variable

To change a session variable, just overwrite it:

Example

<\?php
session_start();

// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

Destroy a PHP Session

To remove all global session variables and destroy the session, use session_unset() and session_destroy():

Example

<\?php
session_start();

// remove all session variables
session_unset();

// destroy the session
session_destroy();
?>

Cookies In PHP




A cookie is often used to identify a user. ( Cookie is used for identify users)

What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
A Cookie Size is : 4 KB
Maximum Cookies save in a Browser : 400
A Website save maximum Cookies : 20

Create Cookies With PHP

A cookie is created with the setcookie() function.

Syntax

setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.

PHP Create/Retrieve a Cookie

The following example creates a cookie named "user" with the value "John Doe". The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set:

Example

<\?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

if(!isset($_COOKIE[$cookie_name])) {
    echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
    echo "Cookie '" . $cookie_name . "' is set!
";
    echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
Note: The setcookie() function must appear BEFORE the tag.
Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

Modify a Cookie Value

To modify a cookie, just set (again) the cookie using the setcookie() function:

Example

<\?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
if(!isset($_COOKIE[$cookie_name])) {
    echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
    echo "Cookie '" . $cookie_name . "' is set!<\br>";
    echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

Delete a Cookie

To delete a cookie, use the setcookie() function with an expiration date in the past:

Example

<\?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
echo "Cookie 'user' is deleted.";
?>

Check if Cookies are Enabled

The following example creates a small script that checks whether cookies are enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:

Example

<\?php
setcookie("test_cookie", "test", time() + 3600, '/');

if(count($_COOKIE) > 0) {
    echo "Cookies are enabled.";
} else {
    echo "Cookies are disabled.";
}
?>
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.

Join In CakePHP



There are two main ways that you can do this. One of them is the standard CakePHP way, and the other is using a custom join.

The CakePHP Way
You would create a relationship with your User model and Messages Model, and use the containable behavior:

class User extends AppModel {
    public $actsAs = array('Containable');
    public $hasMany = array('Message');
}

class Message extends AppModel {
    public $actsAs = array('Containable');
    public $belongsTo = array('User');
}

You need to change the messages.from column to be messages.user_id so that cake can automagically associate the records for you.
Then you can do this from the messages controller:

$this->Message->find('all', array(
    'contain' => array('User')
    'conditions' => array(
        'Message.to' => 4
    ),
    'order' => 'Message.datetime DESC'
));

The (other) CakePHP way
I recommend using the first method, because it will save you a lot of time and work. The first method also does the groundwork of setting up a relationship which can be used for any number of other find calls and conditions besides the one you need now. However, cakePHP does support a syntax for defining your own joins. It would be done like this, from the MessagesController:

$this->Message->find('all', array(
    'joins' => array(
        array(
            'table' => 'users',
            'alias' => 'UserJoin',
            'type' => 'INNER',
            'conditions' => array(
                'UserJoin.id = Message.from'
            )
        )
    ),
    'conditions' => array(
        'Message.to' => 4
    ),
    'fields' => array('UserJoin.*', 'Message.*'),
    'order' => 'Message.datetime DESC'
));
Note, I've left the field name messages.from the same as your current table in this example.

Using two relationships to the same model
Here is how you can do the first example using two relationships to the same model:

class User extends AppModel {
    public $actsAs = array('Containable');
    public $hasMany = array(
        'MessagesSent' => array(
            'className'  => 'Message',
            'foreignKey' => 'from'
         )
    );
    public $belongsTo = array(
        'MessagesReceived' => array(
            'className'  => 'Message',
            'foreignKey' => 'to'
         )
    );
}

class Message extends AppModel {
    public $actsAs = array('Containable');
    public $belongsTo = array(
        'UserFrom' => array(
            'className'  => 'User',
            'foreignKey' => 'from'
        )
    );
    public $hasMany = array(
        'UserTo' => array(
            'className'  => 'User',
            'foreignKey' => 'to'
        )
    );
}
Now you can do your find call like this:
$this->Message->find('all', array(
    'contain' => array('UserFrom')
    'conditions' => array(
        'Message.to' => 4
    ),
    'order' => 'Message.datetime DESC'
));