<?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>possible solution &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/possible-solution/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Graph Best-First Search</title>
		<link>/2012/09/24/computer-algorithms-graph-best-first-search/</link>
		<comments>/2012/09/24/computer-algorithms-graph-best-first-search/#comments</comments>
		<pubDate>Mon, 24 Sep 2012 10:44:53 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Adjacency matrix]]></category>
		<category><![CDATA[Algebraic graph theory]]></category>
		<category><![CDATA[Breadth-first search]]></category>
		<category><![CDATA[Depth-first search]]></category>
		<category><![CDATA[Graph]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[graph traversal algorithms]]></category>
		<category><![CDATA[Hopcroft–Karp algorithm]]></category>
		<category><![CDATA[Matching]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Path decomposition]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[possible solution]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[two algorithms]]></category>
		<category><![CDATA[typical greedy algorithm]]></category>
		<category><![CDATA[USD]]></category>

		<guid isPermaLink="false">/?p=3347</guid>
		<description><![CDATA[Introduction So far we know how to implement graph depth-first and breadth-first search. These two approaches are crucial in order to understand graph traversal algorithms. However they are just explaining how we can walk through in breadth or depth and sometimes this isn&#8217;t enough for an efficient solution of graph traversal. In the examples so &#8230; <a href="/2012/09/24/computer-algorithms-graph-best-first-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Graph Best-First Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Depth-First Search">Computer Algorithms: Graph Depth-First Search </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>So far we know how to implement graph <a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" title="Computer Algorithms: Graph Depth-First Search">depth-first</a> and <a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" title="Computer Algorithms: Graph Breadth First Search">breadth-first</a> search. These two approaches are crucial in order to understand graph traversal algorithms. However they are just explaining how we can walk through in breadth or depth and sometimes this isn&#8217;t enough for an efficient solution of graph traversal.</p>
<p>In the examples so far we had an undirected, unweighted graph and we were using adjacency matrices to represent the graphs. By <a href="/2012/08/31/computer-algorithms-graphs-and-their-representation/" title="Computer Algorithms: Graphs and their Representation">using adjacency matrices</a> we store <strong>1</strong> in the A[i][j] if there’s an edge between vertex i and vertex j. Otherwise we put a <strong>0</strong>. However the value of <strong>1</strong> gives us only the information that we have an edge between two vertices, which is not always enough when designing graphs.</p>
<p>Indeed graphs can be weighted. Sometimes the path between two vertices can have a value. Thinking of a road map we know that distances between cities are represented in miles or kilometers. Thus often representing a road map as a graph, we don’t put just 1 between city A and city B, to say that there is a path between them, but also we put some meaningful information – let’s say the distance in miles between A and B. </p>
<p>Note that this value can be the distance in miles, but it can be something else, like the time in hours we’ve to walk between those two cities. In general this value is a function of A and B. So if we keep the distance between A and B we can say this function is F(A, B) = X, or distance(A, B) = X miles.</p>
<p>Of course in this particular example F(A, B) = F(B, A), but this isn’t always true in practice. We can have a directed graph where F(A, B) != F(B, A).</p>
<p>Here I talk about distance between two cities and it is the edge that brings some additional information. However sometimes we have to store the value of the vertices. Let&#8217;s say I&#8217;m playing a game (like chess) and each move brings me some additional benefit. So each move (vertex) can be evaluated with some particular value. Thus sometimes we don&#8217;t have a function of and edge like F(A, B), but function of the vertices, like F(A) and F(B).</p>
<p>In breadth-first search and depth-first search we just pick up a vertex and we consecutively walk through all its successors that haven’t been visited yet.</p>
<figure id="attachment_3357" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/1.-Unweithed-Graph-Walkthrough.png"><img src="/wp-content/uploads/2012/09/1.-Unweithed-Graph-Walkthrough.png" alt="Walk Through an Unweithed Graph" title="Unweithed Graph Walkthrough" width="620" height="399" class="size-full wp-image-3357" srcset="/wp-content/uploads/2012/09/1.-Unweithed-Graph-Walkthrough.png 620w, /wp-content/uploads/2012/09/1.-Unweithed-Graph-Walkthrough-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In order to walk through an unweithed graph using DFS, we chose consecutively each successor of node i!</figcaption></figure>
<p>So in DFS in particular we started from left to right in the array above. So the first node that has to be explored is vertex “1”.</p>
<pre lang="PHP">
0: [0, 1, 0, 0, 1, 1]
</pre>
<p>However sometimes, as I said above, we have weighted graphs, so the question is – is there any problem, regarding to the algorithm speed, if we go consecutively through all successors. The answer in general is yes, so we must modify a bit our code in order to continue not with the first but with the best matching successor. By best-matching we mean that the successor should match some criteria like – minimal or maximal value.<span id="more-3347"></span></p>
<h2>Overview</h2>
<p>In the following example we see that some of the successors of vertex 0 are very far from it, while others are closer. Thus 4 has the value of 5, while node 1’s value is 2 and 5 is 1.</p>
<figure id="attachment_3359" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/2.-BFS-and-Weighted-Graph.png"><img src="/wp-content/uploads/2012/09/2.-BFS-and-Weighted-Graph.png" alt="DFS and Weighted Graph" title="DFS and Weighted Graph" width="620" height="399" class="size-full wp-image-3359" srcset="/wp-content/uploads/2012/09/2.-BFS-and-Weighted-Graph.png 620w, /wp-content/uploads/2012/09/2.-BFS-and-Weighted-Graph-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Weithed graph brings us more information about the successors of a given vertex. Thus we have to chose carefully which one to get first in our path exploration!</figcaption></figure>
<pre lang="PHP">
0: [0, 2, 0, 0, 5, 1]
</pre>
<p>In this case if we’re searching for the shortest path between 1 and 3, although 1 and 4 are the first two successors in the adjacency matrix of the &#8220;start&#8221; vertex, we don&#8217;t choose them since there’s a better solution – going through node 5.</p>
<figure id="attachment_3360" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/3.-Best-First-Search.png"><img src="/wp-content/uploads/2012/09/3.-Best-First-Search.png" alt="Best-First Search" title="Best-First Search" width="620" height="399" class="size-full wp-image-3360" srcset="/wp-content/uploads/2012/09/3.-Best-First-Search.png 620w, /wp-content/uploads/2012/09/3.-Best-First-Search-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In best-first search we continue the path to the target through the best-matching successor!</figcaption></figure>
<h3>Problems</h3>
<p>The question is – are we sure that by choosing node 5, we’ll find the best path? Even more! Is there a path through node 5? As we see on the image below both cases are possible.</p>
<figure id="attachment_3361" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/4.-BFS-problems.png"><img src="/wp-content/uploads/2012/09/4.-BFS-problems.png" alt="BFS problems" title="BFS problems" width="620" height="399" class="size-full wp-image-3361" srcset="/wp-content/uploads/2012/09/4.-BFS-problems.png 620w, /wp-content/uploads/2012/09/4.-BFS-problems-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Somtimes best-first search doesn&#8217;t find the &#8220;best&#8221; (shortest/longest/cheapest) path to the target!</figcaption></figure>
<p>Practically best-first search is identical with depth-first search, with the main difference that we choose the best-matching successor instead of choosing the first matching successor. So we’re sure that we’re going through all the successors but in some particular order, different from DFS. Thus we know that if there’s a path we’ll find it.</p>
<p>However even if we find the path between A and B, we can’t be sure that there is not a better path. We only know that this path is the best so far. </p>
<p>Another question is – how can we find the best matching successor effectively. Well if we’re looking for the minimal or maximal value one possible solution is to sort the array of successors.</p>
<figure id="attachment_3363" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/5.-Using-Priority-Queues.png"><img src="/wp-content/uploads/2012/09/5.-Using-Priority-Queues.png" alt="Using Priority Queues" title="Using Priority Queues" width="620" height="412" class="size-full wp-image-3363" srcset="/wp-content/uploads/2012/09/5.-Using-Priority-Queues.png 620w, /wp-content/uploads/2012/09/5.-Using-Priority-Queues-300x199.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The difference between depth-first and best-first is that we change the order of chosing the next successor!</figcaption></figure>
<pre lang="PHP">
0: [0 => 0, 1 => 2, 2 => 0, 3 => 0, 4 => 5, 5 => 1]
// sorted by value
0: [5 => 1, 1 => 2, 4 => 5, 0 => 0, 2 => 0, 3 => 1]
</pre>
<p>Another good approach will be to use priority queues or heaps.</p>
<p>Thus on every step we’ll get the best matching successor.</p>
<h2>Code</h2>
<p>In general best-first search uses the ground of depth-first search, so its implementation isn&#8217;t more difficult! The following PHP code snippet shows the very small difference between these two algorithms.</p>
<pre lang="PHP">
class Graph 
{
    protected $_len = 0;
    protected $_g = array();
    protected $_visited = array();
    
    public function __construct()
    {
        $this->_g = array(
            array(0, 2, 0, 0, 5, 1),
            array(1, 0, 3, 0, 0, 0),
            array(0, 2, 0, 8, 0, 0),
            array(0, 0, 3, 0, 5, 0),
            array(1, 0, 0, 8, 0, 1),
            array(1, 0, 0, 0, 5, 0),
        );
        
        $this->_len = count($this->_g);
        
        $this->_initVisited();
    }
    
    protected function _initVisited()
    {
        for ($i = 0; $i < $this->_len; $i++) {
            $this->_visited[$i] = 0;
        }
    }
    
    public function bestFirst($vertex)
    {
        $this->_visited[$vertex] = 1;
    
        echo $vertex . "\n";
        
        asort($this->_g[$vertex]);
        
        foreach ($this->_g[$vertex] as $key => $v) {
            if ($v > 0 && !$this->_visited[$key]) {
                $this->bestFirst($key);
            }
        }
    }
}

$g = new Graph();
// 2 1 0 5 4 3
$g->bestFirst(2);
</pre>
<h2>Application</h2>
<p>Best-first search is a typical greedy algorithm. In its principles lies the main greedy approach of chosing the best possible solution so far. It is important to note that depth-first search and breadth-first search are the very basic graph walk through approaches, but they can be also widely extended in order to solve more complex problems.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Depth-First Search">Computer Algorithms: Graph Depth-First Search </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/09/24/computer-algorithms-graph-best-first-search/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A JavaScript Trick You Should Know</title>
		<link>/2011/07/12/a-javascript-trick-you-should-know/</link>
		<comments>/2011/07/12/a-javascript-trick-you-should-know/#comments</comments>
		<pubDate>Tue, 12 Jul 2011 14:49:46 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Brace notation]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Concatenation]]></category>
		<category><![CDATA[Data types]]></category>
		<category><![CDATA[Formal languages]]></category>
		<category><![CDATA[heredoc]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[JavaScript syntax]]></category>
		<category><![CDATA[js solution]]></category>
		<category><![CDATA[possible solution]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">/?p=2333</guid>
		<description><![CDATA[JavaScript Strings You should know that in JavaScript you cannot simply write a multilined code chunk, i.e. something like this: var str = 'hello world'; This will result in an error, which can be a problem when you deal with large strings. Imagine a string containing some HTML that should be injected via innerHTML. Now &#8230; <a href="/2011/07/12/a-javascript-trick-you-should-know/" class="more-link">Continue reading <span class="screen-reader-text">A JavaScript Trick You Should Know</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
<li><a href="/2010/08/26/javascript-flexibility-regex-match/" rel="bookmark" title="JavaScript Flexibility &#8211; Regex match()">JavaScript Flexibility &#8211; Regex match() </a></li>
<li><a href="/2010/08/24/flexible-javascript-splitting-strings/" rel="bookmark" title="Flexible JavaScript &#8211; Splitting Strings">Flexible JavaScript &#8211; Splitting Strings </a></li>
<li><a href="/2010/08/25/flexible-javascript-replace-in-a-string/" rel="bookmark" title="Flexible JavaScript &#8211; Replace in a String">Flexible JavaScript &#8211; Replace in a String </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>JavaScript Strings</h2>
<p>You should know that in JavaScript you cannot simply write a multilined code chunk, i.e. something like this:</p>
<pre lang="javascript">
var str = 'hello
world';
</pre>
<p>This will result in an error, which can be a problem when you deal with large strings. Imagine a string containing some HTML that should be injected via innerHTML. Now one possible solution is to concatenate two or more strings, by splitting the initial string.</p>
<pre lang="javascript">
var str = 'hello'
        + 'world';
</pre>
<p>Howerver this solution result in some additional operations like concatenation. It can be very nice if there was something like the PHP multiline string format.</p>
<h2>The PHP Example</h2>
<p>In PHP you have the same use case with strings. You can have a string concatenated over multiple lines, but you cannot split lines like so:</p>
<pre lang="php">
// the following line is wrong
$str = 'hello
world'; 

// a possible solution to the line above is
$str = 'hello'
     . 'world';
// which is very similar to the js solution in the second example

// ... but in PHP there is the so called HEREDOC
$str = <<<EOD
hello
world
EOD;
</pre>
<p>The heredoc gives us the power to write multiline strings. </p>
<h2>The JavaScript Trick</h2>
<p>Actually in JavaScript there is something that's exactly what Heredoc is meant to be for PHP. Take a look at the last example:</p>
<pre lang="javascript">
var text = <>
this <br />
is
my
multi-line
text
</>.toString();

document.body.innerHTML = text;
</pre>
<p>Thus you can write multiline strings in the JavaScript code.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
<li><a href="/2010/08/26/javascript-flexibility-regex-match/" rel="bookmark" title="JavaScript Flexibility &#8211; Regex match()">JavaScript Flexibility &#8211; Regex match() </a></li>
<li><a href="/2010/08/24/flexible-javascript-splitting-strings/" rel="bookmark" title="Flexible JavaScript &#8211; Splitting Strings">Flexible JavaScript &#8211; Splitting Strings </a></li>
<li><a href="/2010/08/25/flexible-javascript-replace-in-a-string/" rel="bookmark" title="Flexible JavaScript &#8211; Replace in a String">Flexible JavaScript &#8211; Replace in a String </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/07/12/a-javascript-trick-you-should-know/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>jQuery.unbind()</title>
		<link>/2011/04/05/jquery-unbind/</link>
		<comments>/2011/04/05/jquery-unbind/#comments</comments>
		<pubDate>Tue, 05 Apr 2011 08:51:08 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Button]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Event]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[HTTP cookie]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery method]]></category>
		<category><![CDATA[Microsoft Binder]]></category>
		<category><![CDATA[obvious solution]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[possible solution]]></category>
		<category><![CDATA[RME]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[unbind]]></category>
		<category><![CDATA[User interface]]></category>
		<category><![CDATA[Widgets]]></category>

		<guid isPermaLink="false">/?p=2240</guid>
		<description><![CDATA[Binding Problems Typically in jQuery when you bind an HTML element with some event this event is fired every time the user (client) triggers it. Thus when you&#8217;ve a click event attached on a button you can click it as many times as you want. In some rare cases this can be tricky. Let&#8217;s imagine &#8230; <a href="/2011/04/05/jquery-unbind/" class="more-link">Continue reading <span class="screen-reader-text">jQuery.unbind()</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2009/12/30/jquery-live-vs-bind-performance/" rel="bookmark" title="jQuery live() vs bind() performance">jQuery live() vs bind() performance </a></li>
<li><a href="/2009/05/25/remove-dom-element-with-jquery/" rel="bookmark" title="Remove DOM Element with JQuery">Remove DOM Element with JQuery </a></li>
<li><a href="/2009/10/21/event-driven-programming-with-jquery-part-2-events-in-jquery/" rel="bookmark" title="Event driven programming with jQuery &#8211; (part 2). Events in jQuery.">Event driven programming with jQuery &#8211; (part 2). Events in jQuery. </a></li>
<li><a href="/2009/10/22/event-driven-programming-with-jquery-part-3-what-is-a-module/" rel="bookmark" title="Event driven programming with jQuery &#8211; (part 3). What is a module?">Event driven programming with jQuery &#8211; (part 3). What is a module? </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Binding Problems</h2>
<figure id="attachment_2254" style="width: 460px" class="wp-caption aligncenter"><a href="http://jquery.com/" target="_blank"><img class="size-full wp-image-2254" title="jquery applications" src="/wp-content/uploads/2011/04/jquery_applications.jpg" alt="jQuery JavaScript Library" width="460" height="240" srcset="/wp-content/uploads/2011/04/jquery_applications.jpg 460w, /wp-content/uploads/2011/04/jquery_applications-300x156.jpg 300w" sizes="(max-width: 460px) 100vw, 460px" /></a><figcaption class="wp-caption-text">jQuery JavaScript Library</figcaption></figure>
<p>Typically in <a title="jQuery on stoimen.com/blog" href="/tag/jquery/">jQuery</a> when you bind an <a title="HTML on stoimen.com/blog" href="/tag/html/">HTML</a> element with some event this event is fired every time the user (client) triggers it. Thus when you&#8217;ve a click event attached on a button you can click it as many times as you want. In some rare cases this can be tricky. Let&#8217;s imagine the following scenario.</p>
<ol>
<li>The user clicks on a &#8220;vote&#8221; button.</li>
<li>Some AJAX calls are performed.</li>
<li>After a successful AJAX call you setup a cookie to deny further votes from this machine.</li>
</ol>
<p>This seems to be pretty well known scenario, but as the click event is attached to the button there is enough time to click several times on the &#8220;vote&#8221; button and to vote several times. In this case before the cookie is set the user can vote more than once.<span id="more-2240"></span></p>
<h3>Demo</h3>
<p><iframe frameborder="0" scrolling="no" src="http://stoimen.com/projects/jquery.unbind/example1.php" style="border:1px solid #ccc;width:500px"></iframe></p>
<p>So one possible solution is to unbind the click event. In jQuery terms this is done by &#8230;</p>
<h2>$.unbind()</h2>
<p>With this method you can simply unbind the &#8220;click&#8221; event or whatever event there is attached on the desired HTML element. So now in the first case we had:</p>
<pre lang="javascript">
$(document).ready(function() {
    $('input').click(function() {
        $.ajax({ url : 'http://stoimen.com/projects/jquery.unbind/example1.php'
               , success : function() {
                    $('p').append('You\'ve voted successfully!<br />');
               }    
        }); 
    }); 
});
</pre>
<p>Now you can replace the code above with:</p>
<pre lang="javascript">
$(document).ready(function() {
    $('input').click(function() {
        $('input').unbind();
        $.ajax({ url : 'http://stoimen.com/projects/jquery.unbind/example1.php'
               , success : function() {
                    $('p').append('You\'ve voted successfully!<br />');
               }    
        }); 
    }); 
});
</pre>
<p>As you can see on the demo here now the button cannot be clicked more than once.</p>
<h3>Demo</h3>
<p><iframe frameborder="0" scrolling="no" src="http://stoimen.com/projects/jquery.unbind/example2.php" style="border:1px solid #ccc;width:500px"></iframe></p>
<h2>Cookies + unbind()</h2>
<p>There is a problem however. After reloading the page the event is attached again, so the user can click on the button once more. The obvious solution is to combine both the cookie and the unbind() as shown in the following pseudo code.</p>
<pre lang="javascript">
$(document).ready(function() {
    if (cookie is not set) { 
        $('input').click(function() {
            $('input').unbind();
            $.ajax({ url : 'http://stoimen.com/projects/jquery.unbind/example1.php'
                   , success : function() {
                        $('p').append('You\'ve voted successfully!<br />');
                        set cookie
                   }    
            }); 
        });
    } 
});
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2009/12/30/jquery-live-vs-bind-performance/" rel="bookmark" title="jQuery live() vs bind() performance">jQuery live() vs bind() performance </a></li>
<li><a href="/2009/05/25/remove-dom-element-with-jquery/" rel="bookmark" title="Remove DOM Element with JQuery">Remove DOM Element with JQuery </a></li>
<li><a href="/2009/10/21/event-driven-programming-with-jquery-part-2-events-in-jquery/" rel="bookmark" title="Event driven programming with jQuery &#8211; (part 2). Events in jQuery.">Event driven programming with jQuery &#8211; (part 2). Events in jQuery. </a></li>
<li><a href="/2009/10/22/event-driven-programming-with-jquery-part-3-what-is-a-module/" rel="bookmark" title="Event driven programming with jQuery &#8211; (part 3). What is a module?">Event driven programming with jQuery &#8211; (part 3). What is a module? </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/04/05/jquery-unbind/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Download Images with PHP</title>
		<link>/2011/01/18/download-images-with-php/</link>
		<comments>/2011/01/18/download-images-with-php/#comments</comments>
		<pubDate>Tue, 18 Jan 2011 13:48:38 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[CURL]]></category>
		<category><![CDATA[Hypertext Transfer Protocol]]></category>
		<category><![CDATA[PHP programming language]]></category>
		<category><![CDATA[possible solution]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">/?p=2131</guid>
		<description><![CDATA[As it seems one possible solution while trying to download images with PHP is to write a &#8220;client&#8221; to do so. Will it be with cURL, Zend Framework or some other tool &#8211; it doesn&#8217;t matter. However one of the most used approaches is simply with file_get_contents and file_put_contents. I&#8217;m not sure whether I wrote &#8230; <a href="/2011/01/18/download-images-with-php/" class="more-link">Continue reading <span class="screen-reader-text">Download Images with PHP</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/09/10/automatically-upload-images-with-php-directly-from-the-uri/" rel="bookmark" title="Automatically Upload Images with PHP Directly from the URI">Automatically Upload Images with PHP Directly from the URI </a></li>
<li><a href="/2010/05/25/download-files-with-zend-framework/" rel="bookmark" title="Download Files with Zend Framework">Download Files with Zend Framework </a></li>
<li><a href="/2011/02/25/how-to-collect-the-images-and-meta-tags-from-a-webpage-with-php/" rel="bookmark" title="How to Collect the Images and Meta Tags from a Webpage with PHP">How to Collect the Images and Meta Tags from a Webpage with PHP </a></li>
<li><a href="/2011/04/07/use-fopen-to-check-file-availability/" rel="bookmark" title="Use fopen() to Check File Availability?">Use fopen() to Check File Availability? </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>As it seems one possible solution while trying to download images with PHP is to write a &#8220;client&#8221; to do so. Will it be with <a href="http://php.net/manual/en/book.curl.php" target="_blank">cURL</a>, <a href="http://zendframework.com/" target="_blank">Zend Framework</a> or some other tool &#8211; it doesn&#8217;t matter.</p>
<p>However one of the most used approaches is simply with <a href="http://php.net/manual/en/function.file-get-contents.php">file_get_contents</a> and <a href="http://www.php.net/manual/en/function.file-put-contents.php">file_put_contents</a>. I&#8217;m not sure whether I wrote already about this or not, but this solution simply looks something like this.</p>
<pre lang="php">

file_put_contents('/path/to/file', 
                  file_get_contents('http://www.example.com/source.image');

</pre>
<p>In fact a client will give you more control over the process, to handle errors, etc. So maybe this is a better solution.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/09/10/automatically-upload-images-with-php-directly-from-the-uri/" rel="bookmark" title="Automatically Upload Images with PHP Directly from the URI">Automatically Upload Images with PHP Directly from the URI </a></li>
<li><a href="/2010/05/25/download-files-with-zend-framework/" rel="bookmark" title="Download Files with Zend Framework">Download Files with Zend Framework </a></li>
<li><a href="/2011/02/25/how-to-collect-the-images-and-meta-tags-from-a-webpage-with-php/" rel="bookmark" title="How to Collect the Images and Meta Tags from a Webpage with PHP">How to Collect the Images and Meta Tags from a Webpage with PHP </a></li>
<li><a href="/2011/04/07/use-fopen-to-check-file-availability/" rel="bookmark" title="Use fopen() to Check File Availability?">Use fopen() to Check File Availability? </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/01/18/download-images-with-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>More on CSS Optimization</title>
		<link>/2011/01/07/more-on-css-optimization/</link>
		<comments>/2011/01/07/more-on-css-optimization/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 14:40:14 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[css]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[Cascading Style Sheets]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Minification]]></category>
		<category><![CDATA[possible solution]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[Style sheet]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[Web application]]></category>
		<category><![CDATA[web applications]]></category>
		<category><![CDATA[Web design]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[web programming]]></category>

		<guid isPermaLink="false">/?p=2101</guid>
		<description><![CDATA[As CSS files are first downloaded to the client and then executed, the main optimization is to make those files smaller. But that doesn&#8217;t mean only minifing! The Minification Process While with minification you can strip all the symbols that only take space, but are useless when the browser parses the file, there are some &#8230; <a href="/2011/01/07/more-on-css-optimization/" class="more-link">Continue reading <span class="screen-reader-text">More on CSS Optimization</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/01/30/optimizing-css-five-simple-steps/" rel="bookmark" title="Optimizing CSS. Five simple steps!">Optimizing CSS. Five simple steps! </a></li>
<li><a href="/2010/02/05/css-sprites-go-beyond-the-limits-with-base64/" rel="bookmark" title="CSS sprites. Go beyond the limits with base64!">CSS sprites. Go beyond the limits with base64! </a></li>
<li><a href="/2010/02/10/manage-javascript-and-css-includes-within-zend-framework-application/" rel="bookmark" title="Manage JavaScript and CSS includes within Zend Framework application">Manage JavaScript and CSS includes within Zend Framework application </a></li>
<li><a href="/2010/01/18/what-if-your-site-doesnt-use-all-of-the-css-selectors/" rel="bookmark" title="What if your site doesn&#8217;t use all of the CSS selectors?">What if your site doesn&#8217;t use all of the CSS selectors? </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>As CSS files are first downloaded to the client and then executed, the main optimization is to make those files smaller. But that doesn&#8217;t mean only minifing!</p>
<p><a href="/wp-content/uploads/2011/01/css.jpg"><img class="alignleft size-full wp-image-2122" title="css" src="/wp-content/uploads/2011/01/css.jpg" alt="CSS" width="400" height="300" srcset="/wp-content/uploads/2011/01/css.jpg 400w, /wp-content/uploads/2011/01/css-300x225.jpg 300w" sizes="(max-width: 400px) 100vw, 400px" /></a><br />
<br clear="all" /></p>
<h2>The Minification Process</h2>
<p>While with minification you can strip all the symbols that only take space, but are useless when the browser parses the file, there are some other techniques, which in fact aren&#8217;t so simple, to speed up the loading process. By minification you get rid of the white spaces, tabs, new lines, etc., but the file may remain too large.</p>
<h2>Useless Rules</h2>
<p>Yes, sadly the browser doesn&#8217;t need all those white spaces, actually web developers need them. Just because this makes the file more readable, or readable at all. However most of the web applications have one large CSS file, typically named layout.css, main.css or whatever, that contains all the rules for the entire application. In many of the cases one page of a site doesn&#8217;t need all the rules for the site, so a possible solution is to remove all of the rules that aren&#8217;t used.</p>
<p>There are tools that may help you do the job. Such a tool, that I&#8217;m using is the Firefox add-on &#8211; <a title="Dust-Me Selectors" href="https://addons.mozilla.org/en-US/firefox/addon/5392/" target="_blank">Dust-Me Selectors</a>. Of course there are a lot other tools doing the same job, so it&#8217;s up to you to pick up one.</p>
<p>After removing all those useless rules you&#8217;ll see that the size of the file can be something like 20% of the size of the source file. This is interesting to note, because most of the time the minification cannot give you such performance benefit. In fact this comes with some issues.</p>
<h2>One Request or What?</h2>
<p>This is the dilemma of the web programming, isn&#8217;t it? However thus you can split the main CSS file to few smaller files, but they are named differently so you cannot expect the browser to cache them when the user visits the site for the first time.</p>
<p>The case must be, of course, tested against various situations, so you can decide what suits you. However the typical scenario is to optimize only few of the pages, as they might be the most visited &#8211; as for example the homepage. If two of the pages are mainly visited, than you can make custom, small, CSS files for them with only the necessary rules, and let the other pages with the main CSS file. If you&#8217;ve a lot of returning visitors, you can be sure the custom files will be cached (if the client cache is turned on) and the second time somebody visits the &#8220;homepage&#8221; for example the page will load faster.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/01/30/optimizing-css-five-simple-steps/" rel="bookmark" title="Optimizing CSS. Five simple steps!">Optimizing CSS. Five simple steps! </a></li>
<li><a href="/2010/02/05/css-sprites-go-beyond-the-limits-with-base64/" rel="bookmark" title="CSS sprites. Go beyond the limits with base64!">CSS sprites. Go beyond the limits with base64! </a></li>
<li><a href="/2010/02/10/manage-javascript-and-css-includes-within-zend-framework-application/" rel="bookmark" title="Manage JavaScript and CSS includes within Zend Framework application">Manage JavaScript and CSS includes within Zend Framework application </a></li>
<li><a href="/2010/01/18/what-if-your-site-doesnt-use-all-of-the-css-selectors/" rel="bookmark" title="What if your site doesn&#8217;t use all of the CSS selectors?">What if your site doesn&#8217;t use all of the CSS selectors? </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/01/07/more-on-css-optimization/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>5 PHP String Functions You Need to Know</title>
		<link>/2010/09/17/5-php-string-functions-you-need-to-know/</link>
		<comments>/2010/09/17/5-php-string-functions-you-need-to-know/#comments</comments>
		<pubDate>Fri, 17 Sep 2010 11:19:43 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Case Asset Management AB]]></category>
		<category><![CDATA[Foo bar]]></category>
		<category><![CDATA[Foobar]]></category>
		<category><![CDATA[php string functions]]></category>
		<category><![CDATA[php tutorial]]></category>
		<category><![CDATA[php upper cased strings]]></category>
		<category><![CDATA[possible solution]]></category>
		<category><![CDATA[speaker]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[string functions]]></category>
		<category><![CDATA[United States]]></category>

		<guid isPermaLink="false">/?p=1984</guid>
		<description><![CDATA[The Task First of all what we&#8217;d like to achieve? The task is to convert a string, most of the cases single word, by capitalize the first letter. In my case I&#8217;ve the world countries names all lower cased, while I need them with first letter capitalized. In example &#8220;united states&#8221; must become &#8220;United States&#8221;, &#8230; <a href="/2010/09/17/5-php-string-functions-you-need-to-know/" class="more-link">Continue reading <span class="screen-reader-text">5 PHP String Functions You Need to Know</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
<li><a href="/2012/03/16/you-think-you-know-php-quiz-results/" rel="bookmark" title="You think you know PHP. Quiz Results!">You think you know PHP. Quiz Results! </a></li>
<li><a href="/2009/10/11/strict-types-in-zend-framework-and-in-php/" rel="bookmark" title="Strict types in Zend Framework and in PHP">Strict types in Zend Framework and in PHP </a></li>
<li><a href="/2011/08/17/php-fetch-get-as-string-with-http_build_query/" rel="bookmark" title="PHP: Fetch $_GET as String with http_build_query()">PHP: Fetch $_GET as String with http_build_query() </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p><a href="/wp-content/uploads/2010/09/string.jpg"><img class="aligncenter size-full wp-image-1991" title="strings in PHP" src="/wp-content/uploads/2010/09/string.jpg" alt="Strings in PHP" width="430" height="184" srcset="/wp-content/uploads/2010/09/string.jpg 430w, /wp-content/uploads/2010/09/string-300x128.jpg 300w" sizes="(max-width: 430px) 100vw, 430px" /></a></p>
<h2>The Task</h2>
<p>First of all what we&#8217;d like to achieve? The task is to convert a string, most of the cases single word, by capitalize the first letter. In my case I&#8217;ve the world countries names all lower cased, while I need them with first letter capitalized. In example &#8220;united states&#8221; must become &#8220;United States&#8221;, but not &#8220;United states&#8221; or &#8220;UNITED STATES&#8221;. So here began the journey into PHP string functions, especially those for capitalization!</p>
<h2>1. ucwords</h2>
<p>The first thing you find in the <a title="PHP Manual" href="http://www.php.net/manual/en/index.php" target="_blank">PHP Manual</a> is the <a title="ucwords" href="http://php.net/manual/en/function.ucwords.php" target="_blank">ucwords</a> function. It changes the first letter to a capital letter, but it does not do the job. Why? Well let me show you an example.</p>
<pre lang="php">$str1 = 'foo bar';
$str2 = 'Foo bar';
$str3 = 'FOO BAR';
$str4 = 'фуу бар';

echo ucwords($str1); // Foo Bar
echo ucwords($str2); // Foo Bar
echo ucwords($str3); // FOO BAR
echo ucwords($str4); // фуу бар
</pre>
<p>Here we have four strings. A lower cased, an upper cased, a mixed cased and &#8230; a lower cased Cyrillic string. First of all the main reason why ucwords doesn&#8217;t fit here is because of the Cyrillic string. Whatever non-Latin string you have you can forget about capitalization. However the other strings conversions are also interesting. Take a look at the third string! Here the string remains &#8220;FOO BAR&#8221; instead of going &#8220;Foo Bar&#8221;, which simply means that this function only looks, and hopefully changes, the first letter.</p>
<p>So here we have two questions. How can we overcome the Cyrillic problem and how to &#8220;normalize&#8221; the UPPER CASE string?</p>
<h2>2. ucfirst</h2>
<p>This is another useful function in PHP. <a title="ucfirst" href="http://www.php.net/manual/en/function.ucfirst.php" target="_blank">ucfirst</a> as you may guess from its name converts a string by only changing its first letter. So &#8220;Foo bar&#8221; will remain &#8220;Foo bar&#8221;, while with ucwords it has become &#8220;Foo Bar&#8221;. Let&#8217;s see what this function does:</p>
<pre lang="php">$str1 = 'foo bar';
$str2 = 'Foo bar';
$str3 = 'FOO BAR';
$str4 = 'фуу бар';

echo ucfirst($str1); // Foo bar
echo ucfirst($str2); // Foo bar
echo ucfirst($str3); // FOO BAR
echo ucfirst($str4); // фуу бар
</pre>
<p>Here even the first string has only one capital letter &#8211; &#8220;foo bar&#8221; became &#8220;Foo bar&#8221;, and yet again we&#8217;ve the Cyrillic string unchanged. It simply doesn&#8217;t help us here!</p>
<h2>3. mb_convert_case</h2>
<p>As a PHP developer you know what the &#8220;mb_&#8221; prefix means &#8211; multibyte. This is quite useful. You can convert the string whatever the encoding is, so perhaps we can overcome the Cyrillic problem. But before proceeding to tests, let&#8217;s take a look at the parameters of this function.</p>
<p>The first thing to note here is that <a title="mb_convert_case" href="http://www.php.net/manual/en/function.mb-convert-case.php" target="_blank">mb_convert_case</a> doesn&#8217;t contain the case in its name &#8211; upper or lower. There&#8217;s a second parameter, after the first which is the string itself, who setups that. Note that here you don&#8217;t have the typical camel case or capitals parameter name, but MB_CASE_TITLE (as you know in English the title is always capitalized):</p>
<pre lang="php">echo mb_convert_case($str, MB_CASE_TITLE, ...
</pre>
<p>And a third one which specifies the encoding:</p>
<pre lang="php">echo mb_convert_case($str, MB_CASE_TITLE, 'utf-8')
</pre>
<p>Now let&#8217;s see what we can achieve with it:</p>
<pre lang="php">$str1 = 'foo bar';
$str2 = 'Foo bar';
$str3 = 'FOO BAR';
$str4 = 'фуу бар';

echo mb_convert_case($str1, MB_CASE_TITLE, 'utf-8'); // Foo Bar
echo mb_convert_case($str2, MB_CASE_TITLE, 'utf-8'); // Foo Bar
echo mb_convert_case($str3, MB_CASE_TITLE, 'utf-8'); // Foo Bar
echo mb_convert_case($str4, MB_CASE_TITLE, 'utf-8'); // Фуу Бар
</pre>
<p>As you can see now the Cyrillic problem doesn&#8217;t exists and mb_convert_case is intelligent enough to change &#8220;FOO BAR&#8221; into &#8220;Foo Bar&#8221; &#8211; as I said this is the English style titling. That is by no means the solution when you deal with capitalization with different encoding.</p>
<p>However there is another approach to overcome the all UPPER CASE conversion problem. A possible solution is to convert the string first to a lower case string.</p>
<h2>4. strtolower</h2>
<p><a title="strtolower" href="http://php.net/manual/en/function.strtolower.php" target="_blank">strtolower</a> is very useful PHP string function and perhaps any PHP developer has used it at least once. But yet again &#8211; it does not do the job. Again because of the encoding problem.</p>
<pre lang="php">echo strtolower('ФУУ БАР'); // #*&amp;$(#*%#
</pre>
<p>As you can see the Cyrillic string cannot be lower cased! Let&#8217;s search again into the &#8220;mb_&#8221; universe.</p>
<h2>5. mb_strtolower</h2>
<p>This is the function. Again you&#8217;ve to specify the encoding:</p>
<pre lang="php">
echo mb_strtolower('ФУУ БАР', 'utf-8')
</pre>
<h2>Conclusion</h2>
<p>It doesn&#8217;t matter whether you&#8217;re native English speaker or not. Most of the web sites are multilingual and you cannot be sure what happens when you convert strings in Alphabets different from the Latin. Thus be careful even when everything seems to be OK with Latin string tests.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
<li><a href="/2012/03/16/you-think-you-know-php-quiz-results/" rel="bookmark" title="You think you know PHP. Quiz Results!">You think you know PHP. Quiz Results! </a></li>
<li><a href="/2009/10/11/strict-types-in-zend-framework-and-in-php/" rel="bookmark" title="Strict types in Zend Framework and in PHP">Strict types in Zend Framework and in PHP </a></li>
<li><a href="/2011/08/17/php-fetch-get-as-string-with-http_build_query/" rel="bookmark" title="PHP: Fetch $_GET as String with http_build_query()">PHP: Fetch $_GET as String with http_build_query() </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/09/17/5-php-string-functions-you-need-to-know/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Secure Forms with Zend Framework</title>
		<link>/2010/04/09/secure-forms-with-zend-framework/</link>
		<comments>/2010/04/09/secure-forms-with-zend-framework/#comments</comments>
		<pubDate>Fri, 09 Apr 2010 07:16:17 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[zend framework]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Cryptographic hash function]]></category>
		<category><![CDATA[Hash function]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[MD5]]></category>
		<category><![CDATA[PHP programming language]]></category>
		<category><![CDATA[possible solution]]></category>
		<category><![CDATA[Session]]></category>
		<category><![CDATA[web server]]></category>

		<guid isPermaLink="false">/?p=1421</guid>
		<description><![CDATA[Maybe the correct title is not &#8220;with Zend Framework&#8221;, but &#8220;with PHP&#8221;, because the general approach I used is purely PHP and no Zend Framework dependency is used. However let me mention that ZF allows you to build forms with Zend_Form, which gives you an abstraction over the HTML forms with many goodies like validation, &#8230; <a href="/2010/04/09/secure-forms-with-zend-framework/" class="more-link">Continue reading <span class="screen-reader-text">Secure Forms with Zend Framework</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/06/10/json-and-zend-framework-zend_json/" rel="bookmark" title="JSON and Zend Framework? &#8211; Zend_Json">JSON and Zend Framework? &#8211; Zend_Json </a></li>
<li><a href="/2010/04/28/zend_datesetoptions-and-format_type-in-zend-framework-1-10-3/" rel="bookmark" title="Zend_Date::setOptions and format_type in Zend Framework 1.10.3">Zend_Date::setOptions and format_type in Zend Framework 1.10.3 </a></li>
<li><a href="/2010/07/19/zend-framework-cache-database-table-schemes/" rel="bookmark" title="Zend Framework: Cache Database Table Schemes">Zend Framework: Cache Database Table Schemes </a></li>
<li><a href="/2010/07/21/setting-up-global-cache-in-zend-framework/" rel="bookmark" title="Setting Up Global Cache in Zend Framework">Setting Up Global Cache in Zend Framework </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Maybe the correct title is not &#8220;with Zend Framework&#8221;, but &#8220;with PHP&#8221;, because the general approach I used is purely PHP and no <a title="Zend Framework" href="http://framework.zend.com/" target="_blank">Zend Framework</a> dependency is used. However let me mention that ZF allows you to build forms with Zend_Form, which gives you an abstraction over the HTML forms with many goodies like validation, filtering and protection.</p>
<h2>Zend_Form and Zend_Form_Element_Hash</h2>
<p>Although the technique I&#8217;m using is doing the same thing, note that in ZF there&#8217;s a <a title="Zend_Form_Element_Hash" href="http://framework.zend.com/apidoc/core/Zend_Form/Element/Zend_Form_Element_Hash.html" target="_blank">Zend_Form_Element_Hash</a> which generates and validates the form, thus protecting you from CSRF attacks. The thing is that I didn&#8217;t use it because the form I&#8217;m protecting is not generated with <a title="Zend_Form" href="http://framework.zend.com/manual/en/zend.form.html" target="_blank">Zend_Form</a>, and I cannot benefit from everything ZF is giving to me. However you can easily reproduce the basic strategy with every form and every framework till it&#8217;s written in PHP.</p>
<h2>What&#8217;s the solution?</h2>
<p>It&#8217;s pretty simple and it&#8217;s described many many times around the web, simply generate a random hash, a possible solution is to use uniqid in combination with mt_rand and md5, thus you&#8217;d get quite strong hash.</p>
<p>Step two is to pass this generated hash, also stored in the session in a hidden value of the form. Of course now the most asked question is: but that&#8217;s visible to the source and thus everybody will have a valid hash.</p>
<p>There&#8217;s the trick. OK everybody will have a valid hash, but on submit the hash is validated against the SESSION variable, and as you know the session is specified between the browser (client) and the web server. Although the attacker may have a valid hash he must execute the attacking script from the same domain, possibly with the same browser, which makes the task rather difficult.</p>
<h2>An Example</h2>
<p>Let me show a breve example, it may help make things clearer.</p>
<p>1. First step &#8211; start the session</p>
<pre lang="php" escaped="true">
&lt;?php
session_start();
?&gt;
</pre>
<p>2. Second step &#8211; validate the form against the $_SESSION and generate a valid token</p>
<pre lang="php" escaped="true">
&lt;?php
if (isset($_POST['name']) &amp;&amp; $_POST['token'] == $_SESSION['token'])
    echo $_POST['name'];
else
    echo 'dont hack';

$_SESSION['token'] = md5(uniqid('test', true));
?&gt;
</pre>
<p>3. Third step &#8211; make a form</p>
<pre lang="html4strict" escaped="true">
&lt;form method="POST" action=""&gt;
&lt;input type="hidden" value="&lt;?php echo $_SESSION['token'] ?&gt;" name="token" /&gt;
&lt;input type="text" name="name" value="stoimen" /&gt;
&lt;input type="submit" name="submit" /&gt;
&lt;/form&gt;
</pre>
<p><a href="http://www.stoimen.com/projects/php.secure.forms/">Demo here</a>.</p>
<p>For more to test this you may try to make the same form somewhere else on the web and to point the action to http://www.stoimen.com/projects/php.secure.forms/! Without the session validation it&#8217;s absolutely sure you can post on the attacked server. </p>
<p>P.S. Now I&#8217;ve to admit that this have nothing to do with Zend Framework, however it&#8217;s good practice and thus may be used with every framework.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/06/10/json-and-zend-framework-zend_json/" rel="bookmark" title="JSON and Zend Framework? &#8211; Zend_Json">JSON and Zend Framework? &#8211; Zend_Json </a></li>
<li><a href="/2010/04/28/zend_datesetoptions-and-format_type-in-zend-framework-1-10-3/" rel="bookmark" title="Zend_Date::setOptions and format_type in Zend Framework 1.10.3">Zend_Date::setOptions and format_type in Zend Framework 1.10.3 </a></li>
<li><a href="/2010/07/19/zend-framework-cache-database-table-schemes/" rel="bookmark" title="Zend Framework: Cache Database Table Schemes">Zend Framework: Cache Database Table Schemes </a></li>
<li><a href="/2010/07/21/setting-up-global-cache-in-zend-framework/" rel="bookmark" title="Setting Up Global Cache in Zend Framework">Setting Up Global Cache in Zend Framework </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/04/09/secure-forms-with-zend-framework/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
