<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PHP Chunk</title>
	<atom:link href="http://phpchunk.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://phpchunk.net</link>
	<description>Brings you good chunks of PHP code and practices</description>
	<lastBuildDate>Sun, 12 Feb 2012 17:12:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Speed up your sessions, part 2 – Performance</title>
		<link>http://phpchunk.net/2012/02/speed-up-your-sessions-part-2-performance/</link>
		<comments>http://phpchunk.net/2012/02/speed-up-your-sessions-part-2-performance/#comments</comments>
		<pubDate>Sun, 12 Feb 2012 17:10:49 +0000</pubDate>
		<dc:creator>maximem</dc:creator>
				<category><![CDATA[Performance]]></category>
		<category><![CDATA[memcached]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[sqlite]]></category>

		<guid isPermaLink="false">http://phpchunk.net/?p=208</guid>
		<description><![CDATA[If it&#8217;s not already done, I suggest you to read the first part of this serie of two posts to learn how to use properly PHP sessions. Well, now that everyone knows what to do and not do with sessions, &#8230; <a href="http://phpchunk.net/2012/02/speed-up-your-sessions-part-2-performance/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If it&#8217;s not already done, I suggest you to read <a href="http://phpchunk.net/2011/06/speed-up-your-sessions-part-1-best-practices/" title="Speed up your sessions, part 1 – Best practices">the first part</a> of this serie of two posts to learn how to use properly PHP sessions.</p>
<p>Well, now that everyone knows what to do and not do with sessions, we can try to improve performance a little more.<br />
The rule is to determine how sessions will be used in the application and then choose a better handler than the default one : <em>files</em>.<br />
<span id="more-208"></span></p>
<h2>SQLite : fast read / slow write</h2>
<p><strong>SQLite</strong> for handling sessions is used to <strong>improve significantly read accesses</strong>. On the other hand, <strong>write processing will be slown and time-consuming</strong>.<br />
In fact, instead of using one file per session like the default &#8220;files&#8221; handler, all of them will be stored in a single file, which is a database. So any write action will lock the file resulting in other access tries to be put in a queue.</p>
<p>Balance the pros and the cons, if the application need huge write accesses don&#8217;t use SQLite to manage sessions. But, <strong>if writes are limited SQLite is really appropriate</strong>.</p>
<p>Moreover, it&#8217;s quick and simple to setup.<br />
Install SQLite on the server if it is not already done :</p>
<pre class="brush: plain; title: ; notranslate">
apt-get install php5-sqlite
</pre>
<p>Then just tell PHP, in the <strong>php.ini</strong> file, to use SQLiteas the session handler and the file path where to store them :</p>
<pre class="brush: plain; title: ; notranslate">
session.save_handler = sqlite
session.save_path = &quot;/path/sessions.db&quot;
</pre>
<p>You don&#8217;t even need to worry if the file exists or not, it will be automatically created. The first <em>session_start()</em> query will initiate the database with a table which contains 3 columns &#8220;sess_id&#8221;, &#8220;value&#8221; and &#8220;updated&#8221;.<br />
Remember to restart your web server to apply the modifications.</p>
<h2>Memcached : fast but RAM consuming</h2>
<p>For people who doesn&#8217;t know about <strong>Memcached</strong>, it&#8217;s a distributed memory object caching system. Just visit the official website to learn more : <a href="http://memcached.org/" title="Memcached website">http://memcached.org/</a>. In a few words, <strong>Memcached allows to store data in memory</strong>.</p>
<p>Disk I/O are one of the slowest elements in applications workflow. So, if frequently used data are put in RAM, a lot of disk reads and writes will be saved. This can be applied to your application common data and to users sessions as well.</p>
<p>The installation is very simple, in most case rely on the package manager of the host OS is sufficient.<br />
For example, in a debian based system :</p>
<pre class="brush: plain; title: ; notranslate">
apt-get install memcached
apt-get install php5-memcache
</pre>
<p>Then, if no specific configuration has to be done in the Memcached configuration file, just change the session save handler in the <strong>php.ini</strong> :</p>
<pre class="brush: plain; title: ; notranslate">
session.save_handler = memcache
session.save_path = &quot;tcp://127.0.0.1:11211&quot;
</pre>
<p>Restart Apache (or nginx, lighttpd, etc.) and that&#8217;s it. Now the session processing will be really fast.</p>
<p>But, even if using Memcached for handling sessions has good pros, there are also cons.<br />
In fact, session data are now saved into the server RAM. That means that the storage limit is equal to the available memory on the web server. And <strong>the more RAM is used to save session data the less is available for web applications execution</strong>. So be careful in what is stored in sessions, that&#8217;s where <a href="http://phpchunk.net/2011/06/speed-up-your-sessions-part-1-best-practices/" title="Speed up your sessions, part 1 – Best practices">the best practices</a> become handful. Moreover, data stored in RAM will not survive in a power outage or reboot.</p>
<p>To go further, a single dedicated Memcached server can be shared between several application servers. For example, if you want to do load balancing with multiple web servers, they can use the same Memcached server to cache data. Just change the IP address in the <strong>php.ini</strong> configuration file with the cache server one and you&#8217;re done.</p>
<h2>Other leads</h2>
<p>Instead of using Memcached, you can set up a <strong>RAMDisk</strong> to store sessions in RAM without changing the default <em>files</em> handler. But this solution requires some adminsys skills.</p>
<p>Another possibility is to use the <a href="http://php.net/manual/en/session.installation.php" title="Shared memory allocation for session storage">shared memory module</a> of PHP. I have never tried this method and didn&#8217;t manage to find a good tutorial to implement it. So if anyone has ever done this, please leave a comment <img src='http://phpchunk.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://phpchunk.net/2012/02/speed-up-your-sessions-part-2-performance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reorder numeric keys of an array from &#8220;0&#8243; onwards</title>
		<link>http://phpchunk.net/2012/02/reorder-numeric-keys-of-an-array-from-0-onwards/</link>
		<comments>http://phpchunk.net/2012/02/reorder-numeric-keys-of-an-array-from-0-onwards/#comments</comments>
		<pubDate>Thu, 09 Feb 2012 14:24:48 +0000</pubDate>
		<dc:creator>maximem</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[index]]></category>
		<category><![CDATA[key]]></category>
		<category><![CDATA[order]]></category>
		<category><![CDATA[shift]]></category>

		<guid isPermaLink="false">http://phpchunk.net/?p=193</guid>
		<description><![CDATA[Back in the game with another PHP quick tip Ever faced the problem of needing to loop through an array but it has non-consecutive numeric keys ? There are some easy ways to reassign array keys from 0 onwards. Supposing &#8230; <a href="http://phpchunk.net/2012/02/reorder-numeric-keys-of-an-array-from-0-onwards/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Back in the game with another PHP quick tip <img src='http://phpchunk.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Ever faced the problem of needing to loop through an array but it has non-consecutive numeric keys ?<br />
There are some easy ways to reassign array keys from 0 onwards.<br />
<span id="more-193"></span></p>
<p>Supposing that I have an array with numeric keys as below :</p>
<pre class="brush: php; title: ; notranslate">
$array = array(
    'zero',
    'one',
    'two',
    'three',
    'four',
    'five'
);

print_r($array);

/*
Output :

Array
(
    [0] =&gt; zero
    [1] =&gt; one
    [2] =&gt; two
    [3] =&gt; three
    [4] =&gt; four
    [5] =&gt; five
)
*/
</pre>
<p>For some reasons I unset one of the array elements :</p>
<pre class="brush: php; title: ; notranslate">
unset($array[2]);

print_r($array);

/*
Output :

Array
(
    [0] =&gt; zero
    [1] =&gt; one
    [3] =&gt; three
    [4] =&gt; four
    [5] =&gt; five
)
*/
</pre>
<p>Keys ordering is now broken.<br />
But it&#8217;s really simple to reorder them. No need to do kind of tricky foreach() loop, just use <strong>array_values()</strong> PHP built-in function :</p>
<pre class="brush: php; title: ; notranslate">
$array = array_values($array);

print_r($array);

/*
Output :

Array
(
    [0] =&gt; zero
    [1] =&gt; one
    [2] =&gt; three
    [3] =&gt; four
    [4] =&gt; five
)
*/
</pre>
<p>Ta-da <img src='http://phpchunk.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>To go a little further, the first or last element of an array can be removed without breaking keys order.<br />
It can be done very easily by using <strong>array_shift()</strong> and <strong>array_pop()</strong> functions :</p>
<pre class="brush: php; title: ; notranslate">
$array = array(
    'zero',
    'one',
    'two',
    'three',
    'four',
    'five'
);
print_r($array);

/*
Array
(
    [0] =&gt; zero
    [1] =&gt; one
    [2] =&gt; two
    [3] =&gt; three
    [4] =&gt; four
    [5] =&gt; five
)
*/

array_shift($array);
print_r($array);

/*
Array
(
    [0] =&gt; one
    [1] =&gt; two
    [2] =&gt; three
    [3] =&gt; four
    [4] =&gt; five
)
*/

array_pop($array);
print_r($array);

/*
Array
(
    [0] =&gt; one
    [1] =&gt; two
    [2] =&gt; three
    [3] =&gt; four
)
*/
</pre>
<p>Hope it helps <img src='http://phpchunk.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://phpchunk.net/2012/02/reorder-numeric-keys-of-an-array-from-0-onwards/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Make objects iterable and countable using the SPL, part 1</title>
		<link>http://phpchunk.net/2011/06/objects-iterable-countable-spl-part-1/</link>
		<comments>http://phpchunk.net/2011/06/objects-iterable-countable-spl-part-1/#comments</comments>
		<pubDate>Wed, 29 Jun 2011 22:40:59 +0000</pubDate>
		<dc:creator>maximem</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[interface]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[object]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[SPL]]></category>

		<guid isPermaLink="false">http://phpchunk.net/?p=155</guid>
		<description><![CDATA[Since its 5th version, PHP brings a full object model and offers a lot of features for OOP (Object-oriented programming). Unlike PHP 4, PHP 5 implements concepts such as visibility (public, private, protected), abstract classes and methods, interfaces&#8230; Moreover, it &#8230; <a href="http://phpchunk.net/2011/06/objects-iterable-countable-spl-part-1/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Since its 5th version, PHP brings a full object model and offers a lot of features for OOP (<a title="Object-oriented_programming Wikipedia definition" href="http://en.wikipedia.org/wiki/Object-oriented_programming">Object-oriented programming</a>). Unlike PHP 4, PHP 5 implements concepts such as visibility (public, private, protected), abstract classes and methods, interfaces&#8230;</p>
<p>Moreover, it provides a large set of ready-to-use and useful classes, abstract classes and interfaces. This ressources collection composes the <strong>SPL</strong> : <a title="SPL official documentation" href="http://www.php.net/~helly/php/ext/spl/main.html">Standard PHP Library</a>. Among those, array overloading classes, iterators and additional exceptions may be found.</p>
<p>This post don&#8217;t cover all the SPL features but offer <strong>a good overview of the powerful iterators</strong> to enrich your own classes.</p>
<p>Yet, if you are curious, you may list all the classes and interfaces contained in the SPL with the two following functions :</p>
<pre class="brush: php; title: ; notranslate">
// Display the SPL classes
var_dump(spl_classes());

// Display the declared interfaces
var_dump(get_declared_interfaces());
</pre>
<p><span id="more-155"></span></p>
<h2>What is an iterator ?</h2>
<p>Ok, let&#8217;s start by giving a definition of what an <strong>iterator</strong> is. I have picked up and summerized the one from Wikipedia :</p>
<blockquote><p>In computer programming, an iterator is an object that enables a programmer to traverse a container. [...] Note that an iterator performs traversal and also gives access to data elements in a container, but does not perform iteration [...]. An iterator is behaviorally similar to a database cursor.</p></blockquote>
<p>In PHP, generally, the container is an array or an object which provides methods to be traversed. Then, it may be loop through by a <strong>foreach</strong> structure.</p>
<h2>The basics</h2>
<p>As you surely know, the <strong>foreach</strong> structure allows to iterate over arrays :</p>
<pre class="brush: php; title: ; notranslate">
$arr = array('one' =&gt; 1, 'two' =&gt; 2, 'three' =&gt; 3);

foreach ($arr as $key =&gt; $value){
    echo 'the key &quot;', $key, '&quot; is set to &quot;', $value, '&quot;.', &quot;\n&quot;;
}

/* Output :
the key &quot;one&quot; is set to &quot;1&quot;.
the key &quot;two&quot; is set to &quot;2&quot;.
the key &quot;three&quot; is set to &quot;3&quot;.
*/
</pre>
<p>But what does happen exactly when the <strong>foreach</strong> loop is starting ?</p>
<p>If you read the <a title="foreach documentation" href="http://php.net/manual/en/control-structures.foreach.php">documentation</a>, you will learn that when <strong>foreach</strong> starts :</p>
<ul>
<li>PHP performs a reset on the specified array to put its internal pointer on the first element</li>
<li>then check if the pointer position in the array is valid</li>
<li>reads the key, value pair at that position</li>
<li>assigns the values to the $key and $value variables</li>
<li>then the pointer is advanced by one</li>
<li>if the position is still valid, the loop will continue so on</li>
</ul>
<p>You may reproduce this behavior by using these following array iterative functions : <strong>reset()</strong>, <strong>array_key_exists()</strong>, <strong>key()</strong>, <strong>current()</strong>, <strong>next()</strong>.</p>
<pre class="brush: php; title: ; notranslate">
$arr = array('one' =&gt; 1, 'two' =&gt; 2, 'three' =&gt; 3);

reset($arr);
while (array_key_exists(key($arr), $arr) === true){
    echo 'the key &quot;', key($arr), '&quot; is set to &quot;', current($arr), '&quot;.', &quot;\n&quot;;
    next($arr);
}

/* Output :
the key &quot;one&quot; is set to &quot;1&quot;.
the key &quot;two&quot; is set to &quot;2&quot;.
the key &quot;three&quot; is set to &quot;3&quot;.
*/
</pre>
<p>In PHP 4, <strong>foreach</strong> worked only on arrays, but with PHP 5 it is possible to iterate objects.</p>
<h2>The Traversable abstract interface</h2>
<p>In fact, PHP is able to iterate on any object that implements the <a title="Traversable interface documentation" href="http://php.net/manual/en/class.traversable.php">Traversable</a> interface. Yet, all classes implement this interface by default.<br />
So, you may use any object in <strong>foreach</strong>, it will loop through its public properties :</p>
<pre class="brush: php; title: ; notranslate">
class MyClass
{
    public $public1 = 'public value 1';
    public $public2 = 'public value 2';
    public $public3 = 'public value 3';

    protected $protected = 'protected value';

    private $private = 'private value';
}

$Class = new MyClass();

foreach ($Class as $key =&gt; $value){
    echo $key, ' =&gt; ', $value, &quot;\n&quot;;
}

/* Output :
public1 =&gt; public value 1
public2 =&gt; public value 2
public3 =&gt; public value 3
*/
</pre>
<p>Nevertheless, as <strong>Traversable</strong> is an abstract interface, it cannot be implemented alone. It is just use as an internal engine interface. Either <strong>Iterator</strong> or <strong>IteratorAggregate</strong> have to be used instead.</p>
<h2>The Iterator and IteratorAggregate interfaces</h2>
<p>To personalize the way an object is traversed, you can implement the <a title="Iterator interface documentation" href="http://php.net/manual/en/class.iterator.php">Iterator</a> interface. This one force the class which implements it to define five specific methods : <strong>rewind</strong>, <strong>valid</strong>, <strong>key</strong>, <strong>next</strong>.</p>
<p>Remember the while syntax above in the &#8220;Basics&#8221; part ?<br />
The <strong>foreach</strong> statement will use the <strong>Iterator</strong> interface methods as well to iterate the object  :</p>
<pre class="brush: php; title: ; notranslate">
class AnIterator implements Iterator
{
    private $_list = array(
        'one',
        'two',
        'three'
    );
    private $_key = 0;

    public function __construct()
    {
        $this-&gt;_key = 0;
    }

    public function rewind()
    {
        $this-&gt;_key = 0;
    }

    public function valid()
    {
        return array_key_exists($this-&gt;_key, $this-&gt;_list);
    }

    public function key()
    {
        return $this-&gt;_key;
    }

    public function current()
    {
        return $this-&gt;_list[$this-&gt;_key];
    }

    public function next()
    {
        ++$this-&gt;_key;
    }

}

$Iterator = new AnIterator();
foreach ($Iterator as $key =&gt; $value){
    echo $key, ' =&gt; ', $value, &quot;\n&quot;;
}

/* Output :
0 =&gt; one
1 =&gt; two
2 =&gt; three
*/
</pre>
<p>The official documentation have a good example to see when each method is called during the <strong>foreach</strong> statement : See <a title="Iterator implementation example" href="http://php.net/manual/en/class.iterator.php">Example #2 Basic usage</a>.</p>
<p>Now, if you don&#8217;t want to put the <strong>Iterator</strong> methods inside your class, you may implement <a title="IteratorAggregate interface documentation" href="http://php.net/manual/en/class.iteratoraggregate.php">IteratorAggregate</a> instead. Then, the class just need to define a <strong>getIterator()</strong> method that must return an iterator which will be used by <strong>foreach</strong> :</p>
<pre class="brush: php; title: ; notranslate">
class MyClass implements IteratorAggregate
{
    private $_list = array();

    public function addElement($mixed)
    {
        $this-&gt;_list[] = $mixed;
    }

    public function getIterator()
    {
        return new ArrayIterator($this-&gt;_list);
    }
}

$Class = new MyClass();
$Class-&gt;addElement('one');
$Class-&gt;addElement('two');
$Class-&gt;addElement('three');

foreach ($Class as $key =&gt; $value){
    echo $key, ' =&gt; ', $value, &quot;\n&quot;;
}

/* Output :
0 =&gt; one
1 =&gt; two
2 =&gt; three
*/
</pre>
<p>The <strong>foreach</strong> statement automatically calls the <strong>getIterator()</strong> method of the <em>$Class</em> object to check how to iterate it.<br />
Instead of returning an <strong>ArrayIterator</strong>, you may make your own iterator, as seen above with the <strong>AnIterator</strong> class, an return it.</p>
<h2>Make a class countable with the Countable interface</h2>
<p>As arrays, it is useful to be able to know the size of iterable objects. That&#8217;s where the <a title="Coutable interface documentation" href="http://php.net/manual/en/class.countable.php">Countable</a> interface takes place. It allows to define a <strong>count()</strong> method to your class that will be used by the <strong>count(</strong>) or <strong>sizeof()</strong> function :</p>
<pre class="brush: php; title: ; notranslate">
class MyClass implements IteratorAggregate, Countable
{
    private $_list = array();

    public function addElement($mixed)
    {
        $this-&gt;_list[] = $mixed;
    }

    public function getIterator()
    {
        return new ArrayIterator($this-&gt;_list);
    }

    public function count()
    {
         return sizeof($this-&gt;_list);
    }
}

$Class = new MyClass();
$Class-&gt;addElement('one');
$Class-&gt;addElement('two');
$Class-&gt;addElement('three');

if (sizeof($Class) &gt; 1){
    foreach ($Class as $key =&gt; $value){
        echo $key, ' =&gt; ', $value, &quot;\n&quot;;
    }
}

/* Output :
0 =&gt; one
1 =&gt; two
2 =&gt; three
*/
</pre>
<h2>Dummy iterator example</h2>
<p>Now that you know how to make iterable and coutable objects, let&#8217;s see an example. This one is just for fun, don&#8217;t implement it as it in one of your application&#8230;</p>
<p>The following abstract class just easily allow to count and traverse all rows contained in a database table. I have taken table names from a classic WordPress database :</p>
<pre class="brush: php; title: ; notranslate">
abstract class SimpleSqlTableIterator implements IteratorAggregate, Countable
{
    protected static $_Dao;

    protected $_tableName;
    protected $_tableRows = array();

    static public function setDao(PDO $Dao)
    {
        static::$_Dao = $Dao;
    }

    public function getIterator()
    {
        if (sizeof($this-&gt;_tableRows) &lt; 1){
            $this-&gt;_getData();
        }

        return new ArrayIterator($this-&gt;_tableRows);
    }

    public function count()
    {
        if (sizeof($this-&gt;_tableRows) &lt; 1){
            $this-&gt;_getData();
        }

        return sizeof($this-&gt;_tableRows);

    }

    protected function _getData()
    {
        $Stmt = static::$_Dao-&gt;query(&quot;SELECT * FROM {$this-&gt;_tableName}&quot;);
        $this-&gt;_tableRows = $Stmt-&gt;fetchAll(PDO::FETCH_ASSOC);
    }
}

class UserTable extends SimpleSqlTableIterator
{
    protected $_tableName = 'wp_users';
}

class PostTable extends SimpleSqlTableIterator
{
    protected $_tableName = 'wp_posts';
}

$Db = new PDO (
    'mysql:host=localhost;dbname=your_wp_db',
    'your_user',
    'youor_passwd'
);
SimpleSqlTableIterator::setDao($Db);

$Users = new UserTable();

var_dump(sizeof($Users));

foreach ($Users as $user){
    var_dump($user);
}

$Posts = new PostTable();

var_dump(sizeof($Posts));

foreach ($Posts as $post){
    var_dump($post);
}
</pre>
<h2>Next Time</h2>
<p>In a future entry, we will see other useful iterators such as <strong>SeekableIterator</strong>, <strong>FilterIterator</strong>, <strong>LimitIterator</strong>&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://phpchunk.net/2011/06/objects-iterable-countable-spl-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get the number of days in a month</title>
		<link>http://phpchunk.net/2011/06/get-the-number-of-days-in-a-month/</link>
		<comments>http://phpchunk.net/2011/06/get-the-number-of-days-in-a-month/#comments</comments>
		<pubDate>Mon, 27 Jun 2011 22:21:11 +0000</pubDate>
		<dc:creator>maximem</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[calendar]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[day]]></category>
		<category><![CDATA[month]]></category>

		<guid isPermaLink="false">http://phpchunk.net/?p=145</guid>
		<description><![CDATA[Ever wonder how many days there are in a specific month ? Your quest is over, I have what you need : the cal_days_in_month() function from the Calendar PHP extension. This function can work with different calendars : gregorian, julian, &#8230; <a href="http://phpchunk.net/2011/06/get-the-number-of-days-in-a-month/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Ever wonder how many days there are in a specific month ?</p>
<p>Your quest is over, I have what you need : the <strong>cal_days_in_month()</strong> function from the <a title="Official documentation of the Calendar extension" href="http://php.net/manual/en/book.calendar.php">Calendar PHP extension</a>. <span id="more-145"></span>This function can work with different calendars : gregorian, julian, jewish&#8230; Then just specified a month of a particular year and it will return the number of days :</p>
<pre class="brush: php; title: ; notranslate">
$days = cal_days_in_month(CAL_GREGORIAN, 2, 2024);
echo $days; // output : 29

$days = cal_days_in_month(CAL_GREGORIAN, date('n'), date('Y'));
echo $days; // output : 30
</pre>
<p>To list the available calendars, you may use <strong>cal_info()</strong> :</p>
<pre class="brush: php; title: ; notranslate">
print_r(cal_info());
</pre>
<p>See &#8220;sources&#8221; links for more informations <img src='http://phpchunk.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://phpchunk.net/2011/06/get-the-number-of-days-in-a-month/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Validate and sanitize data with PHP Filter, part 1</title>
		<link>http://phpchunk.net/2011/06/validate-sanitize-data-php-filter-part-1/</link>
		<comments>http://phpchunk.net/2011/06/validate-sanitize-data-php-filter-part-1/#comments</comments>
		<pubDate>Sat, 25 Jun 2011 13:34:50 +0000</pubDate>
		<dc:creator>maximem</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[filter]]></category>
		<category><![CDATA[injection]]></category>
		<category><![CDATA[input]]></category>
		<category><![CDATA[regexp]]></category>
		<category><![CDATA[validator]]></category>

		<guid isPermaLink="false">http://phpchunk.net/?p=94</guid>
		<description><![CDATA[When coding websites or web applications, working on security is important. To prevent all kinds of injections (XSS, SQL, CSRF&#8230;), you have to check all data coming from a foreign source. The typical example is when a user send data &#8230; <a href="http://phpchunk.net/2011/06/validate-sanitize-data-php-filter-part-1/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>When coding websites or web applications, working on security is important. To prevent all kinds of injections (<a title="Cross-site scripting" href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a>, <a title="SQL injection" href="http://en.wikipedia.org/wiki/Sql_injection">SQL</a>, <a title="Cross-site request forgery" href="http://http://en.wikipedia.org/wiki/Csrf">CSRF</a>&#8230;), you have to check all data coming from a foreign source. The typical example is when a user send data to your server from an HTML form. But it&#8217;s also the case when getting your visitors&#8217; HTTP REFERER or USER AGENT, a value from a cookie or calling an API.<br />
<strong>The basic rule is to never trust data which don&#8217;t come from your own code</strong>.</p>
<p>To help you keep your applications safe, since its 5.2 version, PHP provides the <strong>Filter extension</strong> which supplies a couple of handy functions to validate and sanitize data.<br />
The two main functions are <a title="Official PHP documentation for the filter_var function" href="http://www.php.net/manual/en/function.filter-var.php">filter_var</a> and <a title="Official PHP documentation for the filter_input function" href="http://www.php.net/manual/en/function.filter-input.php">filter_input</a>. The first simply filters a specified variable with the given filter whereas the second is able to directly target an external variable (such as a <em>$_POST</em> or <em>$_GET</em> key) and to return it, possibly after having filtered it.<br />
Both come with the same list of filters allowing you to validate or sanitize data.</p>
<p>In this first part we&#8217;re going to overview the <strong>validate filters</strong>. The sanitize ones will be exposed in a second part post.<span id="more-94"></span></p>
<h2>Validate basic values</h2>
<p>So, how it works ?<br />
PHP has defined a list of constants which contain the ID (an integer) of all the available filters. Then, just specified the value to validate and the filter ID to the <strong>filter_var()</strong> function and you&#8217;re done.</p>
<p>It&#8217;s important to understand that filters don&#8217;t act like the PHP <strong>is_*()</strong> functions. They don&#8217;t check the type of the specified value but return the value itself or false if this one is not validate.<br />
Plus, they come with some extra features that are very useful.</p>
<h4>Validate an integer</h4>
<p>For example, integer values may be validated with the constant <strong>FILTER_VALIDATE_INT</strong> :</p>
<pre class="brush: php; title: ; notranslate">
$var = 1;
$result = filter_var($var, FILTER_VALIDATE_INT);
var_dump($result); // output : int(1)

$var = '1024';
$result = filter_var($var, FILTER_VALIDATE_INT);
var_dump($result); // output : int(1024)

$var = 'abc';
$result = filter_var($var, FILTER_VALIDATE_INT);
var_dump($result); // output : bool(false)

$var = '42x';
$result = filter_var($var, FILTER_VALIDATE_INT);
var_dump($result); // output : bool(false)
</pre>
<p>Octal and hexadecimal value may also be checked :</p>
<pre class="brush: php; title: ; notranslate">
$var = 0755;
$result = filter_var($var, FILTER_VALIDATE_INT);
var_dump($result); // output : int(493)

$var = 0xFF;
$result = filter_var($var, FILTER_VALIDATE_INT);
var_dump($result); // output : int(255)
</pre>
<p>After defining two simple options, you may also be more restrictive and specified an allowed range of values :</p>
<pre class="brush: php; title: ; notranslate">
$var = 5;
$result = filter_var(
    $var,
    FILTER_VALIDATE_INT,
    array(
    	'options' =&gt; array(
    	    'min_range' =&gt; 1,
    	    'max_range' =&gt; 10
        )
    )
);
var_dump($result); // output : int(5)

$var = 0x1E;
$result = filter_var(
    $var,
    FILTER_VALIDATE_INT,
    array(
    	'options' =&gt; array(
    	    'min_range' =&gt; 1,
    	    'max_range' =&gt; 100
        )
    )
);
var_dump($result); // output : int(30)
</pre>
<h4>Validate a float</h4>
<p>Float numbers have also their validator, <strong>FILTER_VALIDATE_FLOAT</strong> :</p>
<pre class="brush: php; title: ; notranslate">
$var = 3.14;
$result = filter_var($var, FILTER_VALIDATE_FLOAT);
var_dump($result); // output : float(3.14)

$var = '3.14';
$result = filter_var($var, FILTER_VALIDATE_FLOAT);
var_dump($result); // output : foat(3.14)

$var = '10';
$result = filter_var($var, FILTER_VALIDATE_FLOAT);
var_dump($result); // output : float(10)

$var = 'Not a float';
$result = filter_var($var, FILTER_VALIDATE_FLOAT);
var_dump($result); // output : bool(false)
</pre>
<p>The decimal separator may be defined with an option :</p>
<pre class="brush: php; title: ; notranslate">
$options = array('decimal' =&gt; ',');
$var = '3,14';
$result = filter_var(
    $var,
    FILTER_VALIDATE_FLOAT,
    array(array('options' =&gt; $options))
);
var_dump($result); // output : float(3.14)
</pre>
<h4>Validate a boolean</h4>
<p>The <strong>FILTER_VALIDATE_BOOLEAN</strong> allows to check not only a boolean but more generaly a truthy or falsy value.</p>
<pre class="brush: php; title: ; notranslate">
$boolean = filter_var($var, FILTER_VALIDATE_BOOLEAN);
</pre>
<p>The code above will return <em>true</em> if <em>$var</em> has one of the following value :</p>
<ul>
<li>true</li>
<li>1</li>
<li>&#8217;1&#8242;</li>
<li>&#8216;yes&#8217;</li>
<li>&#8216;on&#8217;</li>
<li>&#8216;true&#8217;</li>
</ul>
<p>Any others value will result in a <em>false</em>, unless you specify the <strong>FILTER_NULL_ON_FAILURE</strong> flag in a third argument :</p>
<pre class="brush: php; title: ; notranslate">
$boolean = filter_var($var, FILTER_VALIDATE_BOOLEAN, array('flags' =&gt; FILTER_NULL_ON_FAILURE));

// The following works too
$boolean = filter_var($var, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
</pre>
<p>Then <em>false</em> will be return if <em>$var</em> is equal to :</p>
<ul>
<li>false</li>
<li>NULL</li>
<li>0</li>
<li>&#8217;0&#8242;</li>
<li>&#8216;false&#8217;</li>
<li>&#8216;off&#8217;</li>
<li>&#8221;</li>
</ul>
<p>Otherwise <em>NULL</em> will be return.</p>
<h2>Validate more complex values</h2>
<p>The three following validators will make you save some times by avoiding the use of complex regexp to validate URL, email and IP addresses.</p>
<h4>Validate an URL</h4>
<p>Don&#8217;t misunderstand, this validator doesn&#8217;t check if an URL exsits or not, it just validates the syntax of the value :</p>
<pre class="brush: php; title: ; notranslate">
$var = 'http://domain.tld';
$result = filter_var($var, FILTER_VALIDATE_URL);
var_dump($result); // output : string(17) &quot;http://domain.tld&quot;

$var = 'http://domain';
$result = filter_var($var, FILTER_VALIDATE_URL);
var_dump($result); // output : string(13) &quot;http://domain&quot;

$var = 'http:domain';
$result = filter_var($var, FILTER_VALIDATE_URL);
var_dump($result); // output : bool(false)
</pre>
<p>If you want to force the URL to have a path or a query string, you may add some flags :</p>
<pre class="brush: php; title: ; notranslate">
$var = 'http://domain.tld';
$result = filter_var($var, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED);
var_dump($result); // output : bool(false)

$var = 'http://domain.tld/';
$result = filter_var($var, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED);
var_dump($result); // output : string(18) &quot;http://domain.tld/&quot;

$var = 'http://domain.tld/path/';
$result = filter_var($var, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED);
var_dump($result); // output : string(23) &quot;http://domain.tld/path/&quot;

$var = 'http://domain.tld/?id=1';
$result = filter_var($var, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED);
var_dump($result); // output : string(23) &quot;http://domain.tld/?id=1&quot;
</pre>
<h4>Validate an email</h4>
<p>As the URL validator, <strong>FILTER_VALIDATE_EMAIL</strong> allow to check an email address without using a single regexp :</p>
<pre class="brush: php; title: ; notranslate">
$var = 'email@domain.tld';
$result = filter_var($var, FILTER_VALIDATE_EMAIL);
var_dump($result); // output : string(16) &quot;email@domain.tld&quot;

$var = 'email@domain';
$result = filter_var($var, FILTER_VALIDATE_EMAIL);
var_dump($result); // output : bool(false)
</pre>
<h4>Validate an IP address</h4>
<p><strong>FILTER_VALIDATE_IP</strong> is also very handy, allowing you to validate IPv4, IPv6 addresses and check if they are not in a private range :</p>
<pre class="brush: php; title: ; notranslate">
$var = '10.10.1.127';
$result = filter_var($var, FILTER_VALIDATE_IP);
var_dump($result); // output : string(11) &quot;10.10.1.127&quot;

$var = '2001:0db8:0000:85a3:0000:0000:ac1f:8001';
$result = filter_var($var, FILTER_VALIDATE_IP);
var_dump($result); // output : string(39) &quot;2001:0db8:0000:85a3:0000:0000:ac1f:8001&quot;

$var = '2001:0db8:0000:85a3:0000:0000:ac1f:8001';
$result = filter_var($var, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
var_dump($result); // output : bool(false)

$var = '192.168.0.2';
$result = filter_var($var, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE);
var_dump($result); // output : bool(false)
</pre>
<h2>Validate inputs with filter_input()</h2>
<p>Idealy, your application should never work directly with <em>$_GET</em>, <em>$_POST</em> or <em>$_COOKIE</em> array. The only lines of code that may contain them should be those that do the filtering.<br />
So, let&#8217;s see how to use the validate filters to directly interact with input data.</p>
<p>Suppose you have built a newsletter system on your website. Then, you have made an HTML form with a text field allowing your visitors to subscribe by keying their email address. When an email address is submitted, your script has to check that it is valid before store it in the database.<br />
If you use to do something like the following :</p>
<pre class="brush: php; title: ; notranslate">
if (preg_match('\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b', $_POST['email']) &gt; 0) {
    $some_sql_query = &quot;INSERT INTO newsletter (email) VALUES (' {$_POST['email']}')&quot;;
    $result = mysql_query($some_sql_query);
    // ...
}
</pre>
<p><strong>It&#8217;s a bad practice</strong>, you should never rely on super global variable. This way you avoid configuration differences and PHP evolution problems. Moreover, the use of an regexp to validate the email address isn&#8217;t really safe, unless you are absolutely sure of what it does and that it respects the syntax defined in <a href="http://tools.ietf.org/html/rfc5322">RFC 5322</a>&#8230;</p>
<p>A better practice would be to use PHP built-in filter :</p>
<pre class="brush: php; title: ; notranslate">
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email !== false &amp;&amp; $email !== NULL){
    $some_sql_query = &quot;INSERT INTO newsletter (email) VALUES ('$email')&quot;;
    // Do what you want
}
</pre>
<p>Much simple, isn&#8217;t it ?</p>
<h2>Go further</h2>
<p>For more informations, examples and functions read the official documentation :</p>
<ul>
<li><a title="Official PHP documentation about validate filters" href="http://www.php.net/manual/en/filter.filters.validate.php">Validate filters list</a></li>
<li><a title="Official PHP documentation about filter flags" href="http://www.php.net/manual/en/filter.filters.flags.php">Filter flags list</a></li>
<li><a title="Official PHP documentation about filter functions" href="http://www.php.net/manual/en/ref.filter.php">Filter funcions list</a></li>
</ul>
<p>Happy reading <img src='http://phpchunk.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://phpchunk.net/2011/06/validate-sanitize-data-php-filter-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Easy string to array conversion</title>
		<link>http://phpchunk.net/2011/06/easy-string-to-array-conversion/</link>
		<comments>http://phpchunk.net/2011/06/easy-string-to-array-conversion/#comments</comments>
		<pubDate>Wed, 22 Jun 2011 15:16:12 +0000</pubDate>
		<dc:creator>maximem</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[hexadecimal]]></category>
		<category><![CDATA[string]]></category>

		<guid isPermaLink="false">http://phpchunk.net/?p=59</guid>
		<description><![CDATA[As you may know, in the C language a string is in fact an array of characters, terminated by the null character \0. In PHP, the idea is still here but it&#8217;s a little bit different. Strings are not considered &#8230; <a href="http://phpchunk.net/2011/06/easy-string-to-array-conversion/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>As you may know, in the C language a string is in fact an array of characters, terminated by the null character <strong>\0</strong>.<br />
In PHP, the idea is still here but it&#8217;s a little bit different. Strings are not considered as array but each characters are easily reachable using the following syntax :</p>
<pre class="brush: php; title: ; notranslate">
$str = 'Hello World!';
$char = $str{4};

echo $char; // output : o
</pre>
<p>So, you may iterate on string characters to build an array :</p>
<pre class="brush: php; title: ; notranslate">
$str = 'Hello World!';
$n = strlen($str);
$arr = array();
for ($i = 0; $i &lt; $n; $i++){
    $arr[$i] = $str{$i};
}
</pre>
<p>But, it&#8217;s by far not the easiest way to convert a string into an array <img src='http://phpchunk.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> <span id="more-59"></span><br />
PHP has already a built-in function to do the job : <strong>str_split</strong>.</p>
<pre class="brush: php; title: ; notranslate">
$str = 'Hello World!';
$arr = str_split($str);

print_r($arr);
/*
Array
(
    [0] =&gt; H
    [1] =&gt; e
    [2] =&gt; l
    [3] =&gt; l
    [4] =&gt; o
    [5] =&gt;
    [6] =&gt; W
    [7] =&gt; o
    [8] =&gt; r
    [9] =&gt; l
    [10] =&gt; d
    [11] =&gt; !
)
*/
</pre>
<p>Plus, <strong>str_split</strong> has another cool feature : if the optional second parameter is specified, the returned array will be broken down into chunks with each the length you have chosen.</p>
<pre class="brush: php; title: ; notranslate">
$str = 'Hello World!';
$arr = str_split($str, 2);

print_r($arr);
/*
Array
(
    [0] =&gt; He
    [1] =&gt; ll
    [2] =&gt; o
    [3] =&gt; Wo
    [4] =&gt; rl
    [5] =&gt; d!
)
*/
</pre>
<p>Now, let&#8217;s make an example with a very simple string to hexadecimal representation function&nbsp;:</p>
<pre class="brush: php; title: ; notranslate">
function str_to_hex($str)
{
    $n = strlen($str);
    $str = str_split($str);
    for ($i = 0; $i &lt; $n; $i++){
        $str[$i] = dechex(ord($str[$i]));
    }
    return implode($str);
}

echo str_to_hex('Hello'); // output : 48656c6c6f
</pre>
<p>The reverse :</p>
<pre class="brush: php; title: ; notranslate">
function hex_to_str($str)
{
    $str = str_split($str, 2);
    $n = sizeof($str);
    for ($i = 0; $i &lt; $n; $i++){
         $str[$i] = chr(hexdec($str[$i]));
    }
    return implode($str);
}

echo hex_to_str('48656c6c6f'); // output : Hello
</pre>
<p>Enjoy <img src='http://phpchunk.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://phpchunk.net/2011/06/easy-string-to-array-conversion/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Speed up your sessions, part 1 &#8211; Best practices</title>
		<link>http://phpchunk.net/2011/06/speed-up-your-sessions-part-1-best-practices/</link>
		<comments>http://phpchunk.net/2011/06/speed-up-your-sessions-part-1-best-practices/#comments</comments>
		<pubDate>Tue, 21 Jun 2011 15:55:33 +0000</pubDate>
		<dc:creator>maximem</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[session]]></category>

		<guid isPermaLink="false">http://phpchunk.net/?p=36</guid>
		<description><![CDATA[This entry is the first part of two posts which will cover session performance in PHP, in a software point of view. So today, you will learn what to do and not do with sessions and how to optimize their &#8230; <a href="http://phpchunk.net/2011/06/speed-up-your-sessions-part-1-best-practices/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This entry is the first part of two posts which will cover session performance in PHP, in a software point of view.<br />
So today, you will learn what to do and not do with sessions and how to optimize their setup with some simple best practices.</p>
<p>The following guidelines suppose that PHP is configured to use the <a href="http://www.php.net/manual/en/session.configuration.php#ini.session.save-handler">default session save handler files</a> and <a href="http://www.php.net/manual/en/session.configuration.php#ini.session.use-cookies">uses cookies</a> to send tokens. Other handlers will be seen in the second part.<span id="more-36"></span></p>
<h2>Session, what is it for ?</h2>
<p>In a few words, the session is used to keep track of a visitor and store data about it across requests to your server. A token is sent to the visitor in a cookie and the user will return it at each of its requests. Then the session allows you to register data to be preserved.</p>
<p>From here, you are able to store the user id for example, which may be used to retrieve its related data through some SQL queries. Also, you may store its access rights, names, last visited URL, shopping cart etc&#8230; Everything that helps defining its application environnement and avoid unneedful SQL queries.</p>
<h2>What you shouldn&#8217;t do</h2>
<p>As seen above, the session must be used to store data concerning an authenticated user.<br />
<strong>You should not use it as a data cache</strong> or store template part in it.</p>
<p>For example, HTML elements such as navigation menu or footer, is surely not specific to an user, so if you store these pieces of code in sessions, the contents will be duplicated in each session file&#8230;<br />
As well, if you store SQL queries results in the session, this will increase significantly their file size and degrading performance. Moreover, retrieve query results from a session is not necessarily faster than calling the database.</p>
<p>Even if, at first sight, the session setup is not the most expensive part of a HTML page generation, it&#8217;s useful to work on it to avoid big performance hits.<br />
<strong>The most you keep your session files small and less numerous, the most your website will be fast</strong>.</p>
<p>If you want to make data caching there are several dedicated solutions available such as <a href="http://php.net/manual/en/book.apc.php">APC</a> or <a href="http://php.net/manual/en/book.memcache.php">Memcached</a>, so don&#8217;t use the session for this task.</p>
<h2>Optimization</h2>
<p>Now that you know how to properly use sessions, we can start to optimize our PHP configuration and code <img src='http://phpchunk.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>First, keep in mind that when a session is started in your script, PHP :</p>
<ul>
<li>tries to read the token contained in the cookie</li>
<li> opens or creates a file on-disk</li>
<li>locks it, so you can write in it</li>
<li>reads its contents</li>
<li>puts the data in the global array $_SESSION</li>
<li>sets caching headers</li>
<li>returns a cookie to the client</li>
<li>etc&#8230;</li>
</ul>
<p>All these actions are just a summary of what PHP does, I don&#8217;t know the exact internal mechanisms&#8230;<br />
But they set out one thing, the setup of a session have a cost in terms of performance.<br />
So <strong>you should always keep the control of the session initialization</strong>.</p>
<p>For that purpose, the php flag <a href="http://www.php.net/manual/en/session.configuration.php#ini.session.auto-start">session.auto_start</a> in your <strong>php.ini</strong> must be set to <strong>0</strong>. Otherwise, a session will be mount at the begining of each request for each user and even when it&#8217;s not necessarily. If a visitor has no need to be logged, why setting a session for him ?<br />
I admit that for 1 or 2 visitors per day it&#8217;s surely not significant but what if your website must handle thousands visits at the same time ?</p>
<p>You have to determine where and when a session has to be set up. Then you may start it explicitly with :</p>
<pre class="brush: php; title: ; notranslate">
$boolean = session_start();
</pre>
<p>At that point, the session is running. That means its file is locked to prevent concurrent writes and only your current script may make operations on it. Other access tries will be denied, resulting in your other scripts to stall, waiting for the session file to be available.<br />
So, <strong>if you don&#8217;t need to save data into the session, close it as soon as possible</strong>. Then data you set in the <em>$_SESSION</em> array is written in the storage and all of the global <em>$_SESSION</em> array contents are still avalaible in read-only mode :</p>
<pre class="brush: php; title: ; notranslate">
session_start();

$_SESSION['foo'] = 'This will be stored in the session';
session_write_close();

echo $_SESSION['foo'];

// Other data that has been stored before the current script
// are still available in read mode
echo $_SESSION['bar'];
</pre>
<p>Voilà !</p>
<p>Applying these few best practices is a good start to not slow your web applications when implementing session support.</p>
<p>In the second part of this serie, we will see how to increase even more performance by using others session handler instead of files.</p>
]]></content:encoded>
			<wfw:commentRss>http://phpchunk.net/2011/06/speed-up-your-sessions-part-1-best-practices/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The best way to get a file extension</title>
		<link>http://phpchunk.net/2011/06/the-best-way-to-get-a-file-extension/</link>
		<comments>http://phpchunk.net/2011/06/the-best-way-to-get-a-file-extension/#comments</comments>
		<pubDate>Sun, 19 Jun 2011 11:27:11 +0000</pubDate>
		<dc:creator>maximem</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[directory]]></category>
		<category><![CDATA[extension]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[path]]></category>

		<guid isPermaLink="false">http://phpchunk.net/?p=26</guid>
		<description><![CDATA[For my first post I suggest you a quick tips to easily get a file extension from a filename or a file path. If you are used to do something like this : Stop reinventing the wheel, there&#8217;s a simple &#8230; <a href="http://phpchunk.net/2011/06/the-best-way-to-get-a-file-extension/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>For my first post I suggest you a quick tips to easily get a file extension from a filename or a file path.<br />
If you are used to do something like this :</p>
<pre class="brush: php; title: ; notranslate">
$filename = '/path/to/your/file.php';
$ext = substr($filename, strrpos($filename, '.') + 1);

echo $ext; // display : php
</pre>
<p>Stop reinventing the wheel, there&#8217;s a simple PHP function to get informations from a file path, among them the file extension.<span id="more-26"></span><br />
The <strong>pathinfo</strong> function parses and returns in an array :</p>
<ul>
<li>the directory name</li>
<li>the file name</li>
<li>the extension</li>
<li>the file name without the extension</li>
</ul>
<p>To get only the file extension you can pass a second argument like the following :</p>
<pre class="brush: php; title: ; notranslate">
$filename = '/path/to/your/file.php';
$ext = pathinfo($filename, PATHINFO_EXTENSION);

echo $ext; // display : php
</pre>
<p>And you&#8217;re done <img src='http://phpchunk.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
See the <a title="pathinfo documentation" href="http://php.net/manual/en/function.pathinfo.php">official documentation</a> for more information about the <strong>pathinfo</strong> function.</p>
]]></content:encoded>
			<wfw:commentRss>http://phpchunk.net/2011/06/the-best-way-to-get-a-file-extension/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hello world!</title>
		<link>http://phpchunk.net/2011/06/hello-world/</link>
		<comments>http://phpchunk.net/2011/06/hello-world/#comments</comments>
		<pubDate>Fri, 17 Jun 2011 19:39:43 +0000</pubDate>
		<dc:creator>maximem</dc:creator>
				<category><![CDATA[Blog Life]]></category>

		<guid isPermaLink="false">http://phpchunk.net/?p=1</guid>
		<description><![CDATA[Hi everyone, PHP Chunk intends to bring you quick tips, code snippets and best practices in PHP coding. It is aimed at beginner developers and more experimented coders as well. Visit my about page to learn more about me and &#8230; <a href="http://phpchunk.net/2011/06/hello-world/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Hi everyone,</p>
<p>PHP Chunk intends to bring you quick tips, code snippets and best practices in PHP coding. It is aimed at beginner developers and more experimented coders as well.<br />
Visit my <a title="About" href="http://phpchunk.net/about/">about page</a> to learn more about me and this blog.</p>
<p>Hope you will learn some good stuff.<br />
Happy reading <img src='http://phpchunk.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
echo 'Hello World!';
?&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://phpchunk.net/2011/06/hello-world/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
