jump to navigation

Sending emails Using Zend_Mail and Google Smtp February 8, 2013

Posted by Tournas Dimitrios in PHP.
3 comments

mailboThe Zend Framework provides the Zend_Mail component to compose and send both text and MIME-compliant multipart e-mail messages . Due to ZF’s loosely coupled architecture , each component can be used as an supplementary part into other Frameworks or libraries . Mail can be sent with Zend_Mail’s default transport layer (Zend_Mail_Transport_Sendmail) or alternatively , using another transport layer  (Zend_Mail_Transport_Smtp) . This article will present a simple way to use the Smtp  layer for sending mails via our Google account . A custom Class encapsulates the basic functionality , this allows us to reuse the code in other projects (instead of copy/paste) . This Class depends on  ZF’s components , it is assumed that this Framework is already installed into your server . I always prefer to download the whole Framework , as its size is 35-MegaBytes (these days , it would be considered as negligible) .  You could of course only download  the needed modules (instead of the whole Framework) from this website .

Note: Google has smtp sending limits, you can only send up to 500 emails using a Google standard account. Read the Google answer on this limiting issue, for more info .

Straight to the code :

<?php
/**
 * Created by Tournas Dimitrios
 * Date: 2/7/13
 * Time: 10:38 PM
 */

class GoogleMailer
{
    protected $_parameters = array();

    public function __construct(array $mailComponents = array())
    {
     $this->_parameters = $mailComponents;
    }

    public function composeMail(array $mailComponents)
    {
    $mailer = $this->_getMailer() ;
 list($fromAddress , $fromName) = explode(",", $mailComponents['fromMail']);
    $mailer->setBodyText($mailComponents['plainTextMessage'])
           ->setFrom($fromAddress , $fromName)
           ->addTo($mailComponents['addTo'])
           ->setSubject($mailComponents['subject']);
    if (array_key_exists('HtmlMessage', $mailComponents) &&
        !empty($mailComponents['HtmlMessage']))
       {
    $mailer->setBodyHtml($mailComponents['HtmlMessage']) ;
       }
    if (array_key_exists('replyTo', $mailComponents) &&
        !empty($mailComponents['replyTo']))
       {
 list($replyAddress , $replyName) = explode(",", $mailComponents['replyTo']);
    $mailer->setReplyTo($replyAddress , $replyName );
       }
    return $mailer ;
    }

    private  function _getMailer()
    {
    $mailer = new Zend_Mail();
    $mailer->setDefaultTransport($this->_getSmtpTransport());
    return $mailer ;
    }

    private  function _getSmtpTransport()
    {
    return new Zend_Mail_Transport_Smtp('smtp.gmail.com', array(
            'auth'     => 'login',
            'username' => $this->_parameters['Google.username'],
            'password' => $this->_parameters['Google.password'],
            'ssl'      => 'ssl',
            'port'     => 465 ,
        ));
    }
}

A quick overview  :

  • The constructor demands an array , which contains our Google credentials (Username , password)
  • Two private functions ( _getMailer  and _getSmtpTransport ) are handling the initialization process of the Classes .
  • A public function (composeMail) , is responsible for triggering the initialization of the two required Classes  and composing the mail object with our custom information ( From , Subject , Message , MailTo  , ReplyTo) . The  information is passed into this function as an associative array .
  • Besides the required parts of the mail message , optional fields can also be defined (HtmlMessage and replyTo ) . Two “if-statements” will recognize their existence and will take care to set the mail object .  Gmail automatically replaces whatever “setFrom”  or “setReplyTo” fields you have specified with the account you are authenticating with (yourname@gmail.com) . To define another “setReplyTo”  mail-address , you must allow Gmail to send using that email address by following these steps  .

The implementation :

<?php
/**
 * Created by Tournas Dimitrios
 * Date: 2/7/13
 * Time: 11:16 PM
 */
include 'GoogleMailer.php' ;
require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
$googleMail = new GoogleMailer(array(
    'Google.username' => 'YOUR-GOOGLE_USERNAME',
    'Google.password' => 'YOUR_GOOGLE_PASSWORD'));
$plainTextMessage = 'Lorem ipsum ....Vut integer et, nisi enim! Nisi lectus pid, nunc, eu aliquam aliquam sit montes cras. Aliquam mus non montes diam magnis placerat arcu augue, ' ;
$HtmlMessage = '<h3>Important message !!!</h3>' ;
$mailComponents = array(
    'plainTextMessage'=> $plainTextMessage ,
    'fromMail' => 'tournasdimitrios@gmail.com , Tournas Dimitrios ' ,
    'subject'  => 'Testing Zend_Mail with Google\'s SNMTP' ,
    'HtmlMessage' => $HtmlMessage . $plainTextMessage ,
    'replyTo'  => 'replytothisaddress@gmail.com , Tournas Dimitrios' ,
    'addTo' => 'sendtothisaddress@gmail.com');
    try
    {
     $mailer = $googleMail->composeMail($mailComponents)
                          ->send() ;
    echo 'Message send successfully' ;
    } catch(Exception $e) {
     echo $e->getMessage();
    }

A quick overview :

  •  First we have to include our custom GoogleMailer Class
  • Zend Framework’s components must also be included . Instead of separate “include” statements for each component , I have chosen to instantiate ZF’s  autoloader Class .
  • A “try-catch” block will handle possible errors .
  • Everything else is self-explanatory (if not , drop me a comment) .

Using Array-syntax to Access PHP-object Values January 24, 2013

Posted by Tournas Dimitrios in PHP.
add a comment

Since PHP 5 we can “cast” an object to an array and use array-like syntax to manipulate its content . This works fine on simple data-structures . However , often we write object-oriented code in which data isn’t necessarily represented as simple key/values (one dimension array) , but by more complex data structures  (ie hierarchical data — multi-dimensional arrays–) . Just casting an Object , which contains complex data structures , to an array won’t  lead to the desired results . The following code demonstrates my earlier definition :

<?php
/**
 * Created by Tournasdimitrios.
 * Date: 1/24/13
 * Time: 21:26 PM
 */
class TestCasting
{
    public $pubArray = array(
                'pubArray-one' ,
                'pubArray-two' ,
                'pubArray-three' ,
        array(
                'pubArray-nested-one',
                'pubArray-nested-two')) ;
    private $_privArray = array(
                'privArray-one' ,
                'privArray-two' ,
                'privArray-three') ;
    protected $_protArray = array(
                'protArray-one' ,
                'protArray-two' ,
                'protArray-three') ;
    public $pubVar = 'Content of Public variable' ;
    private $_privVar = 'Another value' ;
    protected $_protVar = "xyz" ;

    public function __construct()
    {
    echo 'Class', __CLASS__ . " is instantiated" ;
    }
    public function castToArray() {
    return get_object_vars($this) ;
    }

}

$casting = new TestCasting() ;
$results = (array) $casting ;
echo '<pre>' ;
print_r($results) ;

echo '<h3>Looping the results</h3>' ;
foreach($results as $k => $v) {
    if(is_array($v)){
        foreach($v as $kNested => $vNested){
          if(is_array($vNested))  continue ;
         echo '-----', $kNested , 'has value of  : ', $vNested , '<br>';
        } // End of inner loop
    } else {
        echo $k , 'has value of :' , $v , '<br>' ;

    } // End of if-statement
} // End of Outer loop
echo 'Public variable : ' , $results['pubVar'] , '<br>' ;

/*
 * Result on Browser
ClassTestCasting is instantiated
Array
(
    [pubArray] => Array
        (
            [0] => pubArray-one
            [1] => pubArray-two
            [2] => pubArray-three
            [3] => Array
                (
                    [0] => pubArray-nested-one
                    [1] => pubArray-nested-two
                )

        )

    [TestCasting_privArray] => Array
        (
            [0] => privArray-one
            [1] => privArray-two
            [2] => privArray-three
        )

    [*_protArray] => Array
        (
            [0] => protArray-one
            [1] => protArray-two
            [2] => protArray-three
        )

    [pubVar] => Content of Public variable
    [TestCasting_privVar] => Another value
    [*_protVar] => xyz
)
Looping the results

-----0has value of  : pubArray-one
-----1has value of  : pubArray-two
-----2has value of  : pubArray-three
-----0has value of  : privArray-one
-----1has value of  : privArray-two
-----2has value of  : privArray-three
-----0has value of  : protArray-one
-----1has value of  : protArray-two
-----2has value of  : protArray-three
pubVarhas value of :Content of Public variable
TestCasting_privVarhas value of :Another value
*_protVarhas value of :xyz
Public variable : Content of Public variable
 */

As seen on the results , casting an object (to an array) has some important gotchas :

  • The member-names of the object (properties , methods) are represented by the keys on the resulting array
  •  private variables have the class name prepended to the variable name and protected variables have a ‘*‘ prepended to the variable name .
  • data of private and protected “members” are not accessible .

One could implement variety of solutions , all depends on the desired result . For instance , do we want to reach only publicly accessible components of the instantiated Class (object) , or do we need accessibility to all components (public , private and protected) . The following code demonstrates both scenarios . (more…)

Exploring SPL : An Overview of the Iterator and IteratorAgreggate Interface January 23, 2013

Posted by Tournas Dimitrios in PHP.
add a comment

My previous article (introduction to Iterators) made a short introduction about Iterators and the basic concepts of their functionality . This article , and all articles that will follow , will present practical examples as an attempt to emphasize specific features of SPL’s Iterators . Usually  Iterators transform “simple objects” (arrays or instantiated Classes)  into “looping structures” with enhanced functionality , other times , Iterators replace standard loop tasks (foreach) with its own looping capabilities (exaggerating somehow … , creating loops on steroids ) . SPL’s “Iterator part” (my definition) has a hierarchical structure  of Interfaces and Classes . Knowing the general characteristics of each “component” on the aforementioned hierarchy is crucial , as it will determine which component is best suited for our application . The graph that follows presents the hierarchical “relationship” of  all components that constitute SPLs Iterator puzzle .

SPL--inherit_graph_

This article is an overview of the Iterator and IteratorAgreggate Interface . The best approach (IMO) to describe their functionality is by using practical examples , notice through , my attempt is to demystify the basic concepts by using simplified examples . The benefits that might be gained from these techniques may not be obvious at first view , but on production (with large data-sets) , they can boost the performance of an application .

By observing the above graph , one thing is immediately evident , all Classes (and four Interfaces — Countable , OuterIterator , RecursiveIterator , SeekableIterator –) inherit their features from Iterator and IteratorAgreggate Interface . The only exception to this ,  a stand-alone Class (SplInfo) , which is used as a basis for other Classes (SplObject and DirectoryIterator)  . Classes derived from SplInfo though , inherit from Iterator all its features . Traversable Interface is the root of SPL’s Iterator puzzle , its an internal-only Abstraction Interface , so trying to implement it in  “userland” Classes will simply result in an error . We can only implement Iterator or IteratorAggregate Interface into our code . (more…)

Exploring SPL : An Introduction to Iterators January 21, 2013

Posted by Tournas Dimitrios in PHP.
5 comments

The Standard PHP Library (SPL) is a set of functions , Classes and Interfaces built into PHP since version 5.0 , and as of PHP 5.3 it cannot even be disabled . Each new PHP-release , expands this library with new features (by adding new Classes and Interfaces) . SPL has a broad range of build-in functionality , ranging from auto-loading and Exception-handling ,  up to event driven code (Observer design pattern) . One part of SPL’s functionality is devoted to iterations , which is achieved by implementing the Iterator design pattern . The term “Iterator” is used in different aspects of the software development process , conceptually : it describes a general reusable solution to achieve the iteration functionality  . From the implementation “point of view” , an Iterator is an object that traverses a data-structure (eg: an array , a directory listing or possibly a set of database result sets or other resource)  . Lastly , PHP uses the term “Iterator”  to label all these Classes (or Interfaces) that have build-in iteration functionality (which is guaranteed by extending the Iterator Interface , or one of its derivatives) .

Iteration in simple words : it’s basically all about loops (one of the most common building-blocks of all programming languages) . SPL  provides a plethora of specialized tools (Interfaces , Classes) that affect the behavior of the loop . Just to mention a few : FilterIterator , CachingIterator , LimitIterator , RegexIterator  (hope the name is self-explanatory ) . Future articles will present practical examples of all these filters .

The iterator is best understood if we have a firm knowledge of how arrays are iterated in PHP . First, let’s refresh ourselves with an actual foreach loop construct .

$elements = array(
    "firstelement",
    "secondelement",
    "lastelement",
);
foreach($elements as $k => $v) {
  echo $k , '   ' , $v , '<br>' ;
}

All actions that the “foreach-loop” performs internally are available as functions , so we could actually write our own foreach using the following code .

<?php
/**
 * Created by Tournasdimitrios.
 * Date: 1/20/13
 * Time: 4:51 PM
 */

class myIterator {
    private $_position = 0;
    private $_elements = array() ;
    public function __construct($elements) {
    $this->_position = 0;
    $this->_elements = $elements ;
    echo '<b>constructor instantiated</b><br>' ;
    }

    function rewind() {
    echo __METHOD__;
    $this->_position = 0;
    echo '<br>' ;
    }

    function current() {
    echo __METHOD__;
    return '----> Data is :'. $this->_elements[$this->_position];

    }

    function key() {
    echo '<br>' ;
    echo __METHOD__ ;
    return $this->_position;

    }

    function next() {
    echo __METHOD__;
    ++$this->_position;
    echo '<br>' ;
    }

    function valid() {
    echo __METHOD__;
    return isset($this->_elements[$this->_position]);

    }
}
 $elements = array(
        "firstelement",
        "secondelement",
        "lastelement",
    );

$it = new myIterator($elements) ;
echo '========== Using For-Loop  ===========<br>' ;
for ( $it->rewind(); $it->valid(); $it->next() ) {
  echo '--------Strarting the loop-------' ;
  echo  $it->current()   ;
  $key = $it->key() ;
  echo '<br>' ;
  echo '-------Stopping the loop---------' ;

}

The loop is implemented in five steps :

  1. Initialize the loop by resetting the key-pointer
    ($it->rewind()
  2. Is the condition valid , ie can we have another loop ?
    ($it->valid() )
  3. If valid (see previous step) , get content of current key-position
    ($it->current() )
  4. Increase the current position
    ($it->key() )
  5. Goto next key-position and repeat the loop , ie step 2
    ($it->next() )

The outcome of previous code is illustrated in the following screenshot :

Exploring SPL

One may ask , why should we write all this code by hand while the foreach loop does everything behind the scenes for us ? (more…)

Writing PHP Classes with “Callback-aware” functionality January 12, 2013

Posted by Tournas Dimitrios in PHP.
7 comments

Many PHP Classes and core-functions have a “callback-aware” functionality , for instance : array_walk , usort , preg_replace_callback  , header_register_callback , SPL’s CallbackFilterIterator are a representative sample  .These functions (and Classes) allow you to plug custom functionality into a component at run-time that is not directly related to that component’s core task . This clever architectural design could also be implemented into our code (library , framework) and transform it into a flexible component . Couldn’t we directly customize the code ,  one may ask …  Well yes , but by separating (delegating) some parts of our code to external functions , we give others the power to extend our code in contexts we don’t yet know about . The “consumer” of our library wouldn’t need to care about our code , as their code is isolated  and future updates to our component will not overwrite their custom code .

Before “digging” into a practical example , a bit of theory will uncover the mystery of callback functions . It’s absolute necessary (especially for new PHP developers) , otherwise  the whole concept  won’t make any sense  .

The term “callback” is typically used to describe functions that are passed as parameters to other functions . Callbacks are frequently used in event handling architectures , where you designate code to be invoked at a later time . PHP makes using callbacks extremely simple using two helper functions (is_callable() and call_user_func() )  . There are three ways to use callbacks :

  1. By defining the custom code into a stand-alone function and assigning its name as a parameter into PHP’s callback helper function .
    function myCallback($msg) {
    echo 'Your message is  : ' . $msg ;
        }
    $callback = 'myCallback' ;
    if(is_callable($callback)) {
    call_user_func($callback , 'Bla-bla') ;
    }
    
    /*
    Defining mulitple arguments into the callback-function
    */
    function myCallback2($msg1 , $msg2 , $msg3) {
    echo "Your message is  :  $msg1  and  $msg2  and $msg3"  ;
        }
    $callback2 = 'myCallback2' ;
    if(is_callable($callback2)) {
    call_user_func($callback2 , 'Bla-bla' , 'xxxxx' , 'zzzzz' ) ;
    }
    
  2. By defining the custom code as a “static” method into a Class . (more…)

An Introduction on How Variables Are Handled by the PHP Interpreter December 30, 2012

Posted by Tournas Dimitrios in PHP.
7 comments

Typically we think of  PHP variables as  named containers of  a value , their content could be any type of data , for instance :  a Boolean , an array ,  an integer , a resource or even  a  10-Megabits string  . We often write our code in such a way  where the same variable has to be copied several times during the execution process of the script . Copying of a variable can be done with a “straightforward” process (explicitly) , by assigning its content into another variable ($a = $b) . A variable is also  copied , implicitly  , during some programming conditions  (when passing a variable into a function , when a function is returning a variable , when iteration occur on a variable — for/while/foreach loops — ) .  By default , PHP-variables are assigned by value , except if we overwrite this functionality with a “by-reference-assignment” ($a =& $b ) . One might say , when a variable is copied (implicitly or explicitly) , its entire content is copied into the destination variable . That makes sense , you might say . Well , no ……   What would happen If every time  a copy of a variable was needed and it was done by just duplicating it ? Simple , it would occupy extra memory locations , and that can lead to severe memory duplication (which can result into performance issues )  . The way that PHP solves this “problem” is by implementing the copy-on-write strategy , in simple words , data-blocks are stored in  buckets (zval containers) . Each bucket is initially shared by all variables (borrowers) that would need a copy of that bucket . This state of affairs can be maintained until a “borrower”  tries to modify its “copy” , instantly the bucket is duplicated and assigned to that specific borrower . Now , the borrower becomes the owner of the newly created bucket and can modify the contents as his desire .
PHP implements this intuitive technique by separating the variable-name (also called symbol) from its value (content) . All symbols are stored in a symbol table  of which there is one per scope . There is a scope for the main script (i.e. , the one requested through the browser) , as well as one for every function or method . Content is stored in a container called a “zval” , which also stores three additional bits of meta-information  :

  1. type  : Represents the type of data : Boolean , int , string
  2. is_ref : Is a Boolean , indicates whether or not the variable was copied by a “copy-by-reference” assignment . From this bit of information  the PHP interpreter knows how to differentiate the two “variable models” (assign-by-value , assign-by-reference) .
  3. refcount : Is a number , representing how many variable-names (symbols) point to this one zval container .

What PHP actually does , is separating the variable (name) from its value (content) and that a variable name is nothing more than a pointer to a container . Each time a variable is copied , only its pointer is copied , not the zval container (of course , up to the point where the borrower wants to modify that copy ) .

Just  a reminder : When a variable is copied with the  “copy-by-reference”  assignment , it shares a common  bucket with equal rights . The “copy-on-write-strategy” is only applicable to copies made with the “copy-by-value” assignment .

Later on , 10 screenshots will clarify all these concepts . A couple of paragraphs with “boring” theory is absolute necessary , before these screenshots make any sense to you .  Also , knowing how PHP handles variables “behind the scenes” might prove a time saver when dealing with debugging tools like Xdebug  .
Let’s recap :

  • we have variables (symbols) that act as pointers to zval-containers , each zval-container is referenced by one or more pointers (depending from how many times a variable was copied ) .
  • Initializing  of a variable is actually done by creating a symbol (pointer) with a corresponding container (zval) , each subsequent need for copying of that variable is only done by copying of its  pointer and assigning to it a new name .
  • Each “zval” container stores a “is_ref”  indicator (Boolean) , it designates how the copy was made .  If the indicator has a value of “FALSE” (0)  , the PHP-interpreter applies the “copy-on-write-strategy” . A “TRUE” value designates the container as “common bucket” .
  • Each “zval” container also stores a “refcount” value (integer)  . This value indicates how many symbols (pointers) are referring to it (how many copies were made)  . Variables can also be deleted (with the unset($varName) command) . A  “refcount” indicator can also have a zero value (just because the script was designed at some point to totally delete a variable )  , in this case , “symbol” and “zval” container are designated as candidates for garbage collection .

Hooray …… boring theory is at the end , let’s present  a few practical examples . Xdebug will be used to mirror the internal functionality of the PHP interpreter .  Xdebug is a PHP extension which provides debugging and profiling capabilities . A future article will go into more details of how to install and use this excellent PHP- tool , but for now , just follow along .

(more…)

A PHP Script to Backup Mysql Databases (for Shared Hosted Websites) December 9, 2012

Posted by Tournas Dimitrios in PHP.
8 comments

Backup should be an essential part of our web-administration tasks , there are too many stories of people who have lost all of their files due to system crashes . We shouldn’t fall into the old paradigm of “it will never happen to me.” or “my web-host handles these kind of tasks for me” or “I don’t know how to backup data” . There is no reason not to implement our own backup-strategy , even if our web-host claims to have the most advanced computer systems that prevent any disaster . This multi-part article will present simple practical code-examples to carry out our own backup’s . This first part handles our database files , I have chosen MySQL as an example , as this is the most used Database in use today (especially on shared hosts) . MySQL has  excellent tools for backups ,  but for security reasons , shared hosts disable directly access to these tools and offer only a graphical interface (for instance , PHPMyAdmin ) as an alternative solution . This multi-part article  uses “native” PHP functions which are part of every PHP installation (common modules like : SPL  , Zip , Curl and mysqli )  .

Prerequisites : Actually there are no special requirements to understand the logic of the following PHP-script . The reader should already have a basic knowledge of a FTP-clients (to upload the script into the server) and he/she should know how to find information  on PHP’s official manual .

A quick view how the script is structured :

  • The configuration section : Configure your own Database credentials and customize the name of the stored archive .
  • createNewArchive function : Creates an archive of a Mysql database
  • getFileSizeUnit function : gets an integer value and returns a proper Unit (Bytes , KB , MB)
  • getNameOfLastArchieve function: Scans the “BackupDir” and returns the name of last created Archive
  • allowCreateNewArchive function  : Compares two time-stamps (Yesterday , lastArchive) . Returns “TRUE” , If the latest Archive is older than 24Hours .

The script :

<?php

#####################
//CONFIGURATIONS
#####################
// Define the name of the backup directory
define('BACKUP_DIR', './myBackups' ) ;
// Define  Database Credentials
define('HOST', 'localhost' ) ;
define('USER', 'root' ) ;
define('PASSWORD', '' ) ;
define('DB_NAME', 'test' ) ;
/*
Define the filename for the Archive
If you plan to upload the  file to Amazon's S3 service , use only lower-case letters .
Watever follows the "&" character should be kept as is , it designates a timestamp , which will be used by the script .
*/
$archiveName = 'mysqlbackup--' . date('d-m-Y') . '@'.date('h.i.s').'&'.microtime(true) . '.sql' ;
// Set execution time limit
if(function_exists('max_execution_time')) {
if( ini_get('max_execution_time') > 0 ) 	set_time_limit(0) ;
}

//END  OF  CONFIGURATIONS

/*
 Create backupDir (if it's not yet created ) , with proper permissions .
 Create a ".htaccess" file to restrict web-access
*/
if (!file_exists(BACKUP_DIR)) mkdir(BACKUP_DIR , 0700) ;
if (!is_writable(BACKUP_DIR)) chmod(BACKUP_DIR , 0700) ;
// Create an ".htaccess" file , it will restrict direct access to the backup-directory .
$content = 'deny from all' ;
$file = new SplFileObject(BACKUP_DIR . '/.htaccess', "w") ;
$written = $file->fwrite($content) ;
// Verify that ".htaccess" is written , if not , die the script
if($written <13) die("Could not create a \".htaccess\" file , Backup task canceled")  ;
// Check timestamp of the latest Archive . If older than 24Hour , Create a new Archive
$lastArchive = getNameOfLastArchieve(BACKUP_DIR)  ;
$timestampOfLatestArchive =  substr(ltrim((stristr($lastArchive , '&')) , '&') , 0 , -8)  ;
if (allowCreateNewArchive($timestampOfLatestArchive)) {
// Create a new Archive
createNewArchive($archiveName) ;
} else {
echo 'Sorry the latest Archive is not older than 24Hours , try a few hours later '  ;
}

###########################
// DEFINING  THE FOUR  FUNCTIONS
// 1) createNewArchive : Creates an archive of a Mysql database
// 2) getFileSizeUnit  : gets an integer value and returns a proper Unit (Bytes , KB , MB)
// 3) getNameOfLastArchieve : Scans the "BackupDir" and returns the name of last created Archive
// 4) allowCreateNewArchive : Compares two timestamps (Yesterday , lastArchive) . Returns "TRUE" , If the latest Archive is onlder than 24Hours .
###########################
// Function createNewArchive
function createNewArchive($archiveName){
$mysqli = new mysqli(HOST , USER , PASSWORD , DB_NAME) ;
if (mysqli_connect_errno())
{
   printf("Connect failed: %s", mysqli_connect_error());
   exit();
}
 // Introduction information

$return = "--\n";
$return .= "-- A Mysql Backup System \n";
$return .= "--\n";
$return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n";
$return .= "--\n";
$return .= "-- Database : " . DB_NAME . "\n";
$return .= "--\n";
$return .= "-- --------------------------------------------------\n";
$return .= "-- ---------------------------------------------------\n";
$return .= 'SET AUTOCOMMIT = 0 ;' ."\n" ;
$return .= 'SET FOREIGN_KEY_CHECKS=0 ;' ."\n" ;
$tables = array() ;
// Exploring what tables this database has
$result = $mysqli->query('SHOW TABLES' ) ;
// Cycle through "$result" and put content into an array
while ($row = $result->fetch_row())
{
$tables[] = $row[0] ;
}
// Cycle through each  table
 foreach($tables as $table)
 {
// Get content of each table
$result = $mysqli->query('SELECT * FROM '. $table) ;
// Get number of fields (columns) of each table
$num_fields = $mysqli->field_count  ;
// Add table information
$return .= "--\n" ;
$return .= '-- Tabel structure for table `' . $table . '`' . "\n" ;
$return .= "--\n" ;
$return.= 'DROP TABLE  IF EXISTS `'.$table.'`;' . "\n" ;
// Get the table-shema
$shema = $mysqli->query('SHOW CREATE TABLE '.$table) ;
// Extract table shema
$tableshema = $shema->fetch_row() ;
// Append table-shema into code
$return.= $tableshema[1].";" . "\n\n" ;
// Cycle through each table-row
while($rowdata = $result->fetch_row())
{
// Prepare code that will insert data into table
$return .= 'INSERT INTO `'.$table .'`  VALUES ( '  ;
// Extract data of each row
for($i=0; $i<$num_fields; $i++)
{
$return .= '"'.$rowdata[$i] . "\"," ;
 }
 // Let's remove the last comma
 $return = substr("$return", 0, -1) ;
 $return .= ");" ."\n" ;
 }
 $return .= "\n\n" ;
}
// Close the connection
$mysqli->close() ;
$return .= 'SET FOREIGN_KEY_CHECKS = 1 ; '  . "\n" ;
$return .= 'COMMIT ; '  . "\n" ;
$return .= 'SET AUTOCOMMIT = 1 ; ' . "\n"  ;
//$file = file_put_contents($archiveName , $return) ;
$zip = new ZipArchive() ;
$resOpen = $zip->open(BACKUP_DIR . '/' .$archiveName.".zip" , ZIPARCHIVE::CREATE) ;
if( $resOpen ){
$zip->addFromString( $archiveName , "$return" ) ;
    }
$zip->close() ;
$fileSize = getFileSizeUnit(filesize(BACKUP_DIR . "/". $archiveName . '.zip')) ;
$message = <<<msg
  <h2>BACKUP  completed ,</h2><br>
  the archive has the name of  : <b>  $archiveName  </b> and it's file-size is :   $fileSize  .

 This zip archive can't be accessed via a web browser , as it's stored into a protected directory .

  It's highly recomended to transfer this backup to another filesystem , use your favorite FTP client to download the archieve .
msg;
echo $message ;
} // End of function creatNewArchive

// Function to append proper Unit after a file-size .
function getFileSizeUnit($file_size){
switch (true) {
    case ($file_size/1024 < 1) :
        return intval($file_size ) ." Bytes" ;
        break;
    case ($file_size/1024 >= 1 && $file_size/(1024*1024) < 1)  :
        return round(($file_size/1024) , 2) ." KB" ;
        break;
	default:
	return round($file_size/(1024*1024) , 2) ." MB" ;
}
} // End of Function getFileSizeUnit

// Funciton getNameOfLastArchieve
function getNameOfLastArchieve($backupDir) {
$allArchieves = array()  ;
$iterator = new DirectoryIterator($backupDir) ;
foreach ($iterator as $fileInfo) {
   if (!$fileInfo->isDir() && $fileInfo->getExtension() === 'zip') {
        $allArchieves[] = $fileInfo->getFilename() ;

    }
}
	return  end($allArchieves) ;
} // End of Function getNameOfLastArchieve

// Function allowCreateNewArchive
function allowCreateNewArchive($timestampOfLatestArchive , $timestamp = 24) {
	$yesterday =  mktime() - $timestamp*3600 ;
	return ($yesterday >= $timestampOfLatestArchive) ? true : false ;
} // End of Function allowCreateNewArchive

Final thoughts :

Upload the script into a publicly available directory and access it via a browser (for instance http://www.example.com/mybackup.php) . Prior the backup , it will check the time elapsed from the last backup and cancel the process if it’s lesser that 24-Hours . The compressed Archive (zip) is stored into the “myBackups” directory and protected from public access with a “.htaccess” file . A good security measure would be to transfer the archive to another file-system . A later part  of this article  will present a practical example that transfers the archive to an online-backup service ( Amazon’s S3 or DropBox) .

How to Create Expiring Links for Amazon’s S3 with PHP December 4, 2012

Posted by Tournas Dimitrios in Amazon-aws, PHP.
15 comments

Amazon’s Simple Storage Service (Amazon S3) is a web-based service for storing and retrieving any amount of data at any time , from anywhere on the web . These tasks (storing / retrieving of data) can be accomplished using various tools . For instance , browser-plugin , web-interface , command-line , programming libraries  or a REST  API .  I recommend the first two tools (browser-plugin , web-interface) as a starting point for those that doesn’t have familiarity with Amazon’s web-storage , but at some point , more sophisticated tools are needed to accomplish  customized functionality  or automated tasks (via scripts)  . This article will present a practical example , how to use the S3-REST-API service to download a specific object (in Amazon’s parlance , an object is any file-type ) . PHP will be used to generate a link to download a specific s3-object (and what’s the interest , you might think) , well  , the link will have a custom expiration time (preferable a few minutes ) . A practical example could be an on-line store that sells downloadable goods (books , software applications ) , the purchaser will charge his/her credit card with the relevant amount ( for instance via PayPal) and after the successful process he/she will be redirected to the web-site of the purchased product to finish his/her shopping experience .  Finally ,  a download link (which will expire in a predefined time )  will allow  the buyer to acquire his ownership .

I have to admit , it wasn’t a simple task for me to write the code . Although the basic concepts seem simple to understand , the implementation wasn’t .The picture below is a flow-chart I drew to make the concepts more understandable by me .  Finally , this code-snippet gave me a good starting point ,  I don’t now the name of the creator , but he certainly deserves a good citation . If someone happens to knows his name , let me know and I’ll update this article .

hmac algorithm

Prerequisites :  The reader should already have an Amazon account (credit card is required for signing up , new members get a one year free AWS Free Usage Tier ) .
A basic understanding of PHP and Amazon’s web-services is also a requirement . I won’t even explain what the following keywords mean : awsAccessKeyawsSecretKeybucketNameobjectPath . If these aforementioned keywords sounds cryptic to you , this article will not make any sense to you . Try first to get familiar with these words before continuing reading . Promise , this article will stay in “published status” , until WordPress.com decides to shut-down the platform 🙂  .

My code examples will be presented in procedural and OOP (Object oriented) format , use the format that suits your needs . Firstly , some basic security concepts should be clarified before the code can be “digested”  from all of you . Let’s get started …….

(more…)

Disable Dangerous Functions in PHP November 30, 2012

Posted by Tournas Dimitrios in PHP.
3 comments

PHP is often characterized as an “easy to learn programming language  and is used as a footstep into web programming . Most of this misunderstanding is due to authors that write tutorials about PHP and often concentrate only on how to present an achievement ( a specific  programs task in PHP ) , while forgetting to mention that their script wasn’t meant for production . Beginners then go on to use these “easy” scripts on production servers and find themselves subject to many forms of attacks . The following chart is just  a representation of the most common PHP-vulnerabilities (listed by type)  .

php-vulnarebility-graph

As shown on the chart , the champion is the “Execute Code” vulnerability . The number represents the reported different ways this vulnerability was used to attack a PHP-application .

PHP  has build-in functionality to execute underlying shell commands on the system itself  (were PHP is installed on) . It provides a number of functions for executing external commands , among them shell_execexecpassthru , the backtricks (` `)  and system . It’s important to note that pretty much whatever you can do on the UNIX command line or in a shell script is allowed here . For example , you can use pipes to string together commands . Each of these commands spawns a child process to run the command or script you designate , and each captures the output of your command as it’s written to standard output (stdout) .

Many common attacks on PHP applications involve attackers uploading so-called “Web Shells”, which are scripts that give the attacker access to system functions for the purpose of taking over the web server . These Shells typically use the dangerous PHP functions for access to system commands . Disabling dangerous PHP functions makes using Web Shells more difficult , thus adding an extra layer of protection  .

How to disable these dangerous commands :

Very simple , open PHP’s ini-file and append the following command (don’t forget to restart Appache so that these configuration changes can be activated) :

disable_functions = shell_exec , show_shource , system , exec,  popen, proc_open , parse_ini_file,  passthru ,  symlink

Most likely , a shared host will have disabled shell access . This article only applies to PHP-code hosted on Cloud servers (like Amazon’s EC2) , VPS or on dedicated-servers  .

Final thoughts : 

I remember the words of my professor “great power must be accompanied with equal responsibilities” . My golden rule is to find alternative ways to accomplish a specific task that was meant to be run through the command shell . For instance , PHP has a “bunch” of build-in file-system function that can be used instead of shell-commands . Another example , I have seen in the past fellow coders using shell commands  to “ping” a remote server (echo exec(“ping “.$ip);) , with a little bit of code the same functionality can be done with PHP’s build-in functionality (fsockopen function) .  Which commands should you use and when ? This is entirely up to you and the needs you have . If you’re accepting user input and passing that information along to the shell , you better sanitize that user input . Strip out any commands that you think might be harmful , disallow users from sending in open requests and only allow them to choose from a list of possible alternatives . Make sure that each case of using a dangerous function is absolute necessary and is done in accordance with best practices . For code that passes arguments to shell commands, use escapeshellarg to prevent command injection vulnerabilities . Use absolute paths when executing external commands , don’t let users execute arbitrary commands . Be particularly careful with the backtick (`) operator (this operator is disabled if shell_exec is disabled) .

The Modulus Operator in PHP November 13, 2012

Posted by Tournas Dimitrios in PHP.
3 comments

In mathematics the modulus operation is used to find the remainder of division between two numbers . Given two positive numbers , the dividend (x) and the divisor (y) , a modulo is the remainder of the Euclidean division of x by y (x/y) . For instance , the expression “5 modulus 3” would evaluate to 2 because 5 divided by 3 leaves a quotient of 1 and a remainder of 2 . Another example ,  “9 modulus 3” would evaluate to 0 because the division of 9 by 3 has a quotient of 3 and leaves a remainder of 0 ( there is nothing to subtract from 9 after multiplying 3 times 3) .We’ve been doing this since our fourth grade in elementary school , when we first learned long divisions and remainders . That’s essentially modulus — simply we didn’t knew what we did then 🙂 . For some unexplained reason , modulus is sometimes a hard concept to grasp , even by adults  .

Modulus is the “fifth” arithmetic operator that we have in our PHP toolbox . It’s a lesser known operator because it isn’t highly useful at first glance . However , it can be very useful in some cases . the following six code-snippets present posible practical implementations :

  • Evaluating a number  (is it odd or even)
    <?php
    $numbers = array(66 , 57 , 89 , 33 , 22 ) ;
    foreach($numbers as $num)
    {
    $m = ($num % 2);
    if ($m==0)
    {
    echo $num , "  is even " , "<br>";
    }else {
    echo $num , "  is odd " , "<br>";
    }
    }
    // Further simplified code
    foreach($numbers as $num)
    {
    if($num % 2) {
    echo "$num is odd<br />";
    } else {
    echo "$num is even<br />";
    	}
    }
    
  • Evaluating the thousands of a number (more…)