Friday, February 27

Check if PHP Session has already started

Recommended way for versions of PHP >= 5.4.0

<?PHP
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
?>

Source: http://www.php.net/manual/en/function.session-status.php

For versions of PHP < 5.4.0

<?PHP
    if(session_id() == '') {
        session_start();
    }
?>

Tips on Web Application Session practices

    1. Use a database for sessions.
 
    2. Regenerate the session on when the permissions change (e.g., when a user logs in).
 
    3. Regenerate the session on every page load (optional).
 
    4. Don't expose the session ID in the URL.
 
    5. Don't expose any sensitive data to the session.
 
    6. Only use the session through secure transport, otherwise someone could sniff the cookie and hijack the session.
 
    7. Expire your session after a reasonable amount of time.

In addition to VirtuosiMedia's list:

    1. Use TLS (SSL) across the entire site. Use the HSTS header.
 
    2. Use a session cookie, rather than adding a session token to every link-href and form-action.
 
    3. Use the secure and httpOnly flags on the cookie.
 
    4. Use the X-Frame-Options header.
 
    5. Keep the content of the session minimal. E.g., store only the user-id. If caching is needed, cache in a general caching layer, not the session.
 
    6 Cryptographically sign the session cookie with a secret key known only to the server. Include an expiration datetime in the signed data. Check the signature and the expiration at the server on every request.

Prepared Statements using PHP or Fix SQL Injection.

PHP coders should use the PDO module if possible as it supports prepared statements across various databases. MySQL users should in particular avoid the old "mysql" module which does not support prepared statements. As of PHP 5, mysqli is available and it supports prepared statements.

Secure Usage:

<?PHP
    $oDB=new PDO('... your connection details... ');
    $hStmt=$oDB->prepare("select name, age from users where userid=:userid");
    $hStmt->execute(array(':userid',$nUserID));
?>

Vulnerable Usage

<?PHP
    // Example #1 (using old mysql library)
    $q=$_GET["q"];
    $con = mysql_connect('localhost', 'peter', 'abc123');
    mysql_select_db("ajax_demo", $con);
    $sql="SELECT * FROM user WHERE id = '".$q."'";
    $result = mysql_query($sql);
?>
(code copied from http://www.w3schools.com/PHP/php_ajax_database.asp )

This code is vulnerable to SQL injection. It uses the old mysql library, which does not support prepared statements. However, the vulnerability could still be avoided by either properly escaping or validating the user input.

<?PHP
    // Example #2 (incorrectly preparing a statement with PDO)
    $oDB=new PDO('... your connection details...');
    $hStmt=$oDB->prepare("select name, age from users where userid=".$_GET['userid']);
    $hStmt->execute();
?>

The second vulnerable example looks just like the secure one above. But instead of properly binding the user data, it assembles dynamic SQL and prepared it after adding user data.

Thursday, February 26

Send Email to Multiple Recipients using PHP

You can send email to multiple recipient at one shot using php. When you submit, this file will be sent an email immediately to the target emails from your database.

First create a DB

Database "mail" and table "email_list" with 3 fields: id(auto_increment), name(varchar, 50), email (varchar, 50) and put some records into this table.

<?php
    // Check, if submitted.
    if($Submit){
     
        // Get variables from POST method form.
        $subject=$_POST['subject'];
        $note=$_POST['note'];
         
        $sender="admin@yourdomain.ext"; // Your Email here.
         
        echo "Email has been sent to:";
         
        // Connect database
        mysql_connect("localhost","","");
        mysql_select_db("mail");
         
        $rs=mysql_query("select * from email_list order by id asc");
         
        // Do while loop to send email.
        while($row=mysql_fetch_assoc($rs)){
            $to=$row['email'];
            $mail_from="From:$email n";
            $mail_from .="Content-Type: text/html; charset=utf-8 n";
             
            mail($to,$subject,$note,$mail_from);
             
            // Show sent emails.
            echo "$row[email]<br>";
        }
    }else{
     
        // Do following codes if not found "Submit" value.(Not submitted)
        ?>
        <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            </head>
            <title>Email Form</title>
            <body>
                <form action="<? echo $PHP_SELF; ?>" method="post" name="form" id="form">
                    <table>
                        <tr>
                            <td align="right">Subject : </td>
                            <td><input name="email" type="text" id="email" /></td>
                        </tr>
                        <tr>
                            <td align="right" valign="top">Note : </td>
                            <td><textarea name="comment" cols="60" rows="5" id="comment"></textarea></td>
                        </tr>
                    </table>
                    <input type="submit" name="Submit" value="Send Email" />
                </form>
            </body>
        </html>
    <?php
    }
?>

Tuesday, February 24

How do PHP sessions work in PHP, and how are they used?

In the general situation :

    1. the session id is sent to the user when his session is created.
    2. it is stored in a cookie (called, by default, PHPSESSID)
    3. that cookie is sent by the browser to the server with each request
    4. the server (PHP) uses that cookie, containing the session_id, to know which file corresponds to that user.
    5. The data in the sessions files is the content of $_SESSION, serialized (ie, represented as a string -- with a function such as serialize) ; and is un-serialized when the file is loaded by PHP, to populate the $_SESSION array.


Sometimes, the session id is not stored in a cookie, but sent in URLs, too -- but that's quite rare, nowadays.


For more informations, you can take a look at the Session Handling section of the manual, that gives some useful informations.

For instance, there is a page about Passing the Session ID, which explains how the session id is passed from page to page, using a cookie, or in URLs -- and which configuration options affect this.


Start a PHP Session:

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.


<?php

    // Start the session
    session_start();
    
    // Set session variables
    $_SESSION["favcolor"] = "green";

?>

Get PHP Session Variable Values:

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

Modify a PHP Session Variable:

To change a session variable, just overwrite it:

<?php
    // 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():

<?php
    // remove all session variables
    session_unset(); 
    
    // destroy the session 
    session_destroy(); 
?>

Monday, February 23

Sort Multi-dimensional Array by Value using PHP

Take a look at en.wikipedia.org/wiki/Sorting_algorithm for sorting algoritms to be able to sort your data as efficient as possible

<?php
    function aasort (&$array, $key) {
        $sorter=array();
        $ret=array();
        reset($array);
        foreach ($array as $ii => $va) {
            $sorter[$ii]=$va[$key];
        }
        asort($sorter);
        foreach ($sorter as $ii => $va) {
            $ret[$ii]=$array[$ii];
        }
        $array=$ret;
    }
    
    aasort($your_array,"order");
?>

Better alternative

<?php
    function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
        $sort_col = array();
        foreach ($arr as $key=> $row) {
            $sort_col[$key] = $row[$col];
        }
    
        array_multisort($sort_col, $dir, $arr);
    }    
    
    array_sort_by_column($array, 'order');
?>

Find out if two files are identical using PHP.

If you just need to find out if two files are identical, comparing file hashes can be inefficient, especially on large files.  There's no reason to read two whole files and do all the math if the second byte of each file is different.  If you don't need to store the hash value for later use, there may not be a need to calculate the hash value just to compare files.  This can be much faster:

    <?php
    define('READ_LEN', 4096);
    
    if(files_identical('file1.txt', 'file2.txt'))
        echo 'files identical';
    else
        echo 'files not identical';

    //   pass two file names
    //   returns TRUE if files are the same, FALSE otherwise
    function files_identical($fn1, $fn2) {
        if(filetype($fn1) !== filetype($fn2))
            return FALSE;
    
        if(filesize($fn1) !== filesize($fn2))
            return FALSE;
    
        if(!$fp1 = fopen($fn1, 'rb'))
            return FALSE;
    
        if(!$fp2 = fopen($fn2, 'rb')) {
            fclose($fp1);
            return FALSE;
        }
    
        $same = TRUE;
        while (!feof($fp1) and !feof($fp2))
            if(fread($fp1, READ_LEN) !== fread($fp2, READ_LEN)) {
                $same = FALSE;
                break;
            }
    
        if(feof($fp1) !== feof($fp2))
            $same = FALSE;
    
        fclose($fp1);
        fclose($fp2);
    
        return $same;
    }
    ?>



Source: php.net