tag:blogger.com,1999:blog-37721936222683260562018-05-08T10:38:54.239+01:00thephpcodethephpcode is where your PHP resources flow and you can find tips and tricks of PHP coding. Code snippets and examples are also provided. Best of PHP are included in thephpcode. Remember, if you have questions, do post a comment on the relevant post.Sam Yongnoreply@blogger.comBlogger65125tag:blogger.com,1999:blog-3772193622268326056.post-79441910744130680432009-12-31T03:43:00.001+00:002009-12-31T06:53:02.051+00:00fontreplace - PHP/jQuery Font Replacement (FLIR)Lately I was quite into web design and interface so much that I started exploring sIFR and FLIR. Yesterday I decided to develop a FLIR for PHP and jQuery.<br /><br />You can download the fontreplace package at: <a href="http://www.mediafire.com/?0o511knwywm">http://www.mediafire.com/?0o511knwywm</a> (122 kB, zip format).<br /><br />Features:<ul><li>PHP 4.4.2 and above compatible</li><li>Uses jQuery Javascript Framework</li><li>Transparent background for CSS background support</li><li>Lightweight</li><li>Reads font color, font size, and font dynamically.</li><li>Detects whether user has font before loading from server</li><li>100% SEO Friendly and minimal code changes</li><li>Supports font color RGBA with alpha.</li><li>Tested working on IE7, IE8, FF 2.0, 3.0, 3.5, Safari (Win) 4.0 and Chrome 3.0, 4.0</li></ul><br />The demo and example is inside the zip file. Place the content of the zip file on a PHP-enabled server and run it on the browser.Sam Yongnoreply@blogger.com7tag:blogger.com,1999:blog-3772193622268326056.post-91653584713859658022009-12-27T15:14:00.001+00:002009-12-31T06:52:31.012+00:00The Art of Password Protection in PHPWhile I was working on some algorithm on PHP earlier on, I began to thought about the methods of password protection when I was still a novice in PHP, till now where I stand. Here's a little bit on how I went through the stages of password protection.<br /><br /><a href="http://img64.imageshack.us/img64/3589/artofpasswordprotection.jpg" target="_blank"><img border="0" src="http://img64.imageshack.us/img64/3589/artofpasswordprotection.jpg" alt="The Art of Password Protection, MD5, SHA1, Salting, php code" /></a><br /><br />Of course my website wasn't hack and I wasn't that bad NOT to hash the password at all. When I started off building my first website, betaPod, I actually used MD5 for password to be hashed. Afterwhich, I learnt about how MD5 passwords can be rainbow-tabled and cracked, and came to know about what is called salting.<br /><br />Then when I thought that if salting is not enough, I came up with positions of the salt based on the password entered, which makes the hash very unique and secured.<br /><br />You can definitely use the code in the image.Sam Yongnoreply@blogger.com0tag:blogger.com,1999:blog-3772193622268326056.post-25333702873758561512009-11-25T08:29:00.000+00:002009-11-25T08:29:24.275+00:00Issues with multiple requests on PHPAgain today I was answering questions on <a href="http://stackoverflow.com/questions/1795372/multiple-requests-on-php">StackOverflow</a> when I came across the question about not being able to load pages when downloading/loading large files.<br /><br />If you are using session, I suggest you use <code>session_write_close()</code> before you output the file to the browser.<br /><br />This is because when the session is opened on one page, you cannot load another page until the session has been written and released. <code>session_write_close()</code> is called automatically when your script ends, but because your outputting process takes time before your script end, your session file is locked and thus other pages cannot be viewed.<br /><br />However, if you are using different browser and/or system, it will be ok because the session file locked is unique to each SESSION ID.<br /><br />Look at: <a href="http://php.net/manual/en/function.session-write-close.php">http://php.net/manual/en/function.session-write-close.php</a><br /><br />However do take note that after <code>session_write_close()</code>, you cannot call <code>session_start()</code> or there will be a warning. Also if you make changes to <code>$_SESSION</code>, it will not take effect.Sam Yongnoreply@blogger.com0tag:blogger.com,1999:blog-3772193622268326056.post-83601058234266418972009-11-02T02:02:00.000+00:002009-11-02T02:02:20.924+00:00Getting value from an object (or instance of a class) in PHP 5Just earlier on I was working on the String class in the Samstyle PHP Framework. I was glad that I read the PHP manual and found this magical method in PHP5 OOP called __toString().<br /><br />Using __toString(), you can actually return a value for the object/instance of a class.<br /><br />See the example below:<br /><br /><pre><code>class MyClass{<br /><br /> function __construct(){<br /> // constructor<br /> }<br /><br /> function __toString(){<br /> // to String<br /> return 5;<br /> }<br /><br />}<br /><br />$inst = new MyClass();<br /><br />echo $inst; // echos 5</code></pre><br />How powerful!Sam Yongnoreply@blogger.com4tag:blogger.com,1999:blog-3772193622268326056.post-16090773323523318592009-10-30T16:14:00.001+00:002009-11-10T23:34:15.417+00:00jQuery-like chaining in PHP's Object Oriented ProgrammingIt's interesting to see how object methods in PHP can be chained just like jQuery's chaining. <br /><br />jQuery's chaining:<br /><br /><code>$("div").children(".firstbtn").hide().fadeIn();</code><br /><br />In PHP, it is also possible to chain similarly. <br /><br />Using the <a href="http://code.google.com/p/samstyle-php-framework/source/browse/trunk/class/string.class.php">string class</a> from Samstyle PHP Framework, we can do chaining in PHP like this:<br /><br /><code>echo $str->trim()->replace('a', 'b')->value();</code><br /><br />To do chaining in PHP, simply add a return statement at the end your methods where appropriate.<br /><br /><code>return $this;</code><br /><br />Advisable to only do this kind of chaining for Action methods, meaning to say that these methods are only doing actions which are not supposed to return value.<br /><br />Hope this helps!Sam Yongnoreply@blogger.com0tag:blogger.com,1999:blog-3772193622268326056.post-56665076384062829422009-10-12T03:37:00.002+01:002009-10-12T03:50:37.907+01:00file_get_contents() vs fread() - Speed Test and BenchmarkingFile access is commonly found in any PHP application. Be it caching, or reading data from a file or what. Lately I've been wondering, whether the use of file_get_contents() over fread() is a good practice (i always prefer file_get_contents()).<br /><br />So this morning I ran a test between this 2 methods of reading a file. The script I used to run is at <a href="http://thephpcode.pastebin.com/f2e84fab1">http://thephpcode.pastebin.com/f2e84fab1</a><br /><br />So here's the result from the tests of 5 runs:<table style="width:100%;"><tr><td>&nbsp;</td><th>fread() (seconds)</th><th>file_get_contents() (seconds)</th></tr><tr><th>Mean</th><td>0.03674</td><td>0.01322</td></tr><tr><th>Min</th><td>0.030710935592651</td><td>0.0098111629486084</td></tr><tr><th>Max</th><td>0.04555082321167</td><td>0.016166925430298</td></tr></table><br /><br />So here it's clear that file_get_contents() is much faster than fread(), mainly because fread() consists of an overhead additional loop and several functions.Sam Yongnoreply@blogger.com2tag:blogger.com,1999:blog-3772193622268326056.post-21874741330993121682009-10-10T09:45:00.003+01:002009-10-10T10:25:53.812+01:00Using Bit Shifting to Divide / MultiplyTo think of it, I rarely use bitwise operators in my coding - especially with all the convenience of other operators (can you imagine calculating bits whole day?).<br /><br />But seriously when I was reading on Bitwise operators, I realised that <code>($n / 2) == ($n >> 1)</code>. So i tested out and...<br /><br />By shifting bits, we can actually do multiplication and division. But however, this is only true when ($n / $x) is still a integer.<br /><br /><code><br />$n = 1600;<br /><br />var_dump(($n / 2) == ($n >> 1));<br />var_dump(($n / 4) == ($n >> 2));<br />var_dump(($n / 8) == ($n >> 3));<br />var_dump(($n / 16) == ($n >> 4));<br /><br />var_dump(($n * 2) == ($n << 1));<br />var_dump(($n * 4) == ($n << 2));<br />var_dump(($n * 8) == ($n << 3));<br />var_dump(($n * 16) == ($n << 4));<br /></code><br /><br />I ran some tests on which one is faster, and found that bitshifting is actually much faster.<br /><br />Here are the results:<table style="width:100%;"><tr><td>&nbsp;</td><th>Normal (seconds)</th><th>Bitshift (seconds)</th></tr><tr><th>Mean</th><td>0.12407</td><td>0.10461</td></tr><tr><th>Min</th><td>0.122979164124</td><td>0.104335069656</td></tr><tr><th>Max</th><td>0.126028060913</td><td>0.105180025101</td></tr></table>Post to the testing script: <a href="http://thephpcode.pastebin.com/f1f6ec979">http://thephpcode.pastebin.com/f1f6ec979</a><br /><br />So when you do some simple math in programming, you know ways to speed things up.Sam Yongnoreply@blogger.com3tag:blogger.com,1999:blog-3772193622268326056.post-82759199967674372122009-10-10T08:20:00.005+01:002009-10-10T10:14:36.836+01:00Pre vs Post Increment in PHPEarlier on I was browsing Google Code, and I chanced upon <a href="http://code.google.com/p/jspeed/">JSpeed</a> - a javascript optimizer. I saw that they actually change post increments to pre-increments. I wondered why and thought I could <a href="http://stackoverflow.com/questions/1546981/post-increment-vs-pre-increment-javascript-optimization">ask this on Stack Overflow</a>.<br /><br />One theory came up to be "preincrement (++i) adds one to the value of i, then returns i; in contrast, i++ returns i then adds one to it, which in theory results in the creation of a temporary variable storing the value of i before the increment operation was applied". -- <a href="http://physical-thought.blogspot.com/2008/11/pre-vs-post-increment-speed-test.html">http://physical-thought.blogspot.com/2008/11/pre-vs-post-increment-speed-test.html</a><br /><br />So I thought, what about PHP? <br /><br />I went on to test it on PHP with a FOR loop and I have the following code:<br /><code>&lt;?php<br /><br />$time_start = microtime_float();<br /><br />for($i = 0; $i<10000000;$i++){<br /><br />}<br /><br />$time_end = microtime_float();<br />$loadedin = (float)($time_end - $time_start);<br />echo $loadedin.' s<br/>';<br /><br />$time_start = microtime_float();<br /><br />for($i = 0; $i<10000000;++$i){<br /><br />}<br /><br />$time_end = microtime_float();<br />$loadedin = (float)($time_end - $time_start);<br />echo $loadedin.' s<br/>';<br /><br />function microtime_float(){<br /> list($usec, $sec) = explode(" ", microtime());<br /> return ((float)$usec + (float)$sec);<br />}<br /><br /><br />?&gt;</code><br /><br />Amazingly, pre-increment is much faster than post-increment in PHP. Look at the results:<table style="width:100%;"><tr><td>&nbsp;</td><th>Pre-inc (seconds)</th><th>Post-inc (seconds)</th></tr><tr><th>Mean</th><td>0.68695</td><td>0.74147</td></tr><tr><th>Min</th><td>0.685925960541</td><td>0.740597963333</td></tr><tr><th>Max</th><td>0.68816781044</td><td>0.743010044098</td></tr></table><br /><br />Thus I conclude that pre-increment is useful in for loops than post-increment. It is much faster through the iterations.Sam Yongnoreply@blogger.com1tag:blogger.com,1999:blog-3772193622268326056.post-89157890324439131372009-09-23T03:23:00.005+01:002009-09-23T03:37:46.329+01:00Session Denial: session id contains illegal charactersThis morning I woke up, went over to <a href="http://stackoverflow.com/">StackOverflow</a> (Yes I admit lately I've been quite active answering questions on SO) and I saw this question: <a href="http://stackoverflow.com/questions/1463175/session-hijacking-or-attack">Session hijacking or attack?</a><br /><br />The asker, <a href="http://stackoverflow.com/users/125075/toto">Toto</a>, saw these in his error logs:<br /><pre>[22-Sep-2009 21:13:52] PHP Warning: session_start() [function.session-start]: The session id contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,' in /var/my_files/class.session.php on line 67 <br />[22-Sep-2009 21:13:52] PHP Warning: Unknown: The session id contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,' in Unknown on line 0 <br />[22-Sep-2009 21:13:52] PHP Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct () in Unknown on line 0</pre><br /><br />The first thing I thought before answering question was that obviously the user had tampered with the PHP session cookie (The cookie name is "PHPSESSID" by default). <br /><br />So what we can do to prevent these errors is to simply reset the ID whenever the session fails to start:<br /><br />&lt;?php<br /><br />$ok = @session_start();<br />if(!$ok){<br /> session_regenerate_id(true); // replace the Session ID<br /> session_start(); // restart the session (since previous start failed)<br />}<br /><br />?&gt;</code><br /><br />Note that users tampering/changing the PHPSESSID to generate this error does not affect your server or read/write files on your server. It may be an attempt to generate great amount of log entries into your error logging file and so on. Thus with this solution, you can prevent such things from happening, yet allowing smooth load for normal users.<br /><br />this piece of security protection has been added to <a href="http://code.google.com/p/samstyle-php-framework">Samstyle PHP Framework</a> (after v1.2.11).Sam Yongnoreply@blogger.com3tag:blogger.com,1999:blog-3772193622268326056.post-45545516366194466532009-09-04T15:47:00.003+01:002009-09-15T13:45:32.147+01:00PHP speed up: Quote your stringsI've wanted to post this earlier, but i've been busy lately. So yeah, here's a tip off on how to speed things up for new or beginner php developers.<br /><br />You might have noticed, PHP error level by default is set to E_ALL & ~E_NOTICE, which means all errors except notices are reported. <br /><br />Take a look at the following snippet:<br /><code>&lt;?php<br /><br />$test = cool;<br />echo $test;<br /><br />?&gt;</code><br /><br />You might have noticed that it works fine. The output is still "cool". <br /><br />But when you set the error level to E_ALL, you get to see an additional line like this one:<br />Notice: Use of undefined constant cool - assumed 'cool' in /public_html/quotestring.php on line 3<br /><br />This means what when the line "$test = cool;" is parsed, PHP actually look up whether a constant "cool" exists. If not, it will assume that it is the string "cool". This means that extra time is taken to find the constant.<br /><br />We ran a test to compare between quotes and no-quotes for a string, and also compared between <a href="http://thephpcode.blogspot.com/2009/07/using-single-instead-of-double-quotes.html">double quotes and single quotes</a>. the result was amazing (the output on browser):<br /><br />Notice: Use of undefined constant cool - assumed 'cool' in /public_html/quotestring.php on line 4<br />cool<br />0.000458002090454 s<br />cool<br />9.05990600586E-6 s<br />cool<br />8.10623168945E-6 s<br /><br />The first one is without quotes (look up constants then decide that it is a string). The 2nd one is using double quotes (look if there are variables or control characters to parse then output) and the last one is using single quotes (just output).<br /><br />The full PHP code for the test results can be found on Pastebin at the following link:<br /><a href="http://thephpcode.pastebin.com/f7bb6a1f9">http://thephpcode.pastebin.com/f7bb6a1f9</a><br /><br />So remember to quote your strings with single quotes and occasionally use double quotes to speed things up. I am Sam Yong, signing off.Sam Yongnoreply@blogger.com1tag:blogger.com,1999:blog-3772193622268326056.post-54716277599173954492009-08-31T15:42:00.004+01:002009-08-31T15:57:43.558+01:00PHP GD: allow PHP to decide image typeIt is at times quite troublesome having the need to detect what image type is the file, then decide which function (imagecreatefromjpeg, imagecreatefrompng or imagecreatefromgif) to use for the image. Well, here's a simple solution.<br /><br /><code>&lt;?php<br /><br />$src = "http://example.com/image.jpg";<br />$image = imagecreatefile($src);<br /><br />function imagecreatefile($f){<br />$content = file_get_contents($f);<br />return imagecreatefromstring($content);<br />}<br /><br />?&gt;</code><br /><br />That's a great and easy way. However, the bad thing is that there will be an overhead of a function and a large variable $content. Having the variable $content in the function scope allows the variable to be disposed at the end of the function, saving memory.<br /><br />To fix the large variable, you can do this instead:<br /><code>&lt;?php<br /><br />$src = "http://example.com/image.jpg";<br />$image = imagecreatefile($src);<br /><br />function imagecreatefile($f){<br />return imagecreatefromstring(file_get_contents($f));<br />}<br /><br />?&gt;</code><br /><br />Hope it helps!Sam Yongnoreply@blogger.com1tag:blogger.com,1999:blog-3772193622268326056.post-57981991891783437642009-08-27T16:40:00.002+01:002009-08-27T16:48:24.769+01:00PHP new development site/manualI was browsing the web earlier on, and I chanced upon one of the PHP website development server at <a href="http://pb11.php.net/">http://pb11.php.net/</a><br /><br />Some comments:<br />the interface (UI) is definitely much better and everything's clearer.<br />however, the layout and contents are much about the same from the current one.<br /><br />So you can try it out at <a href="http://pb11.php.net/">http://pb11.php.net/</a><br /><br />Take note that the mirror is unofficial and is not updated to the latest.Sam Yongnoreply@blogger.com0tag:blogger.com,1999:blog-3772193622268326056.post-39523543424476661372009-08-24T01:22:00.004+01:002009-08-24T01:28:51.967+01:00Optimize your code: Keep functions out of statements!It's always said that we should think out of the box. In any programming language, we should write functions out of certain statements statements.<br /><br />Consider this:<br /><code>&lt;?php<br /><br />$arr = array(/* 10000 elements */);<br />for($i = 0; $i < count($arr); $i++){<br /> // ...<br />}<br /><br />?&gt;</code><br /><br />If you work this out slowly using a debugger or what, you would have noticed that count($arr) will be called for each iteration of the for loop! Each time you call count($arr), count() actually works out your array size and if your array is huge, the script will be stuck at this loop for a few seconds. <br /><br />So what about doing something like this?<br /><code>&lt;?php<br /><br />$arr = array(/* 10000 elements */);<br />$l = count($arr);<br />for($i = 0; $i < $l; $i++){<br /> // ...<br />}<br /><br />?&gt;</code><br />Isn't this logically cleaner and faster in execution?<br /><br />This also applies to while loop.Sam Yongnoreply@blogger.com0tag:blogger.com,1999:blog-3772193622268326056.post-83154541733354283302009-08-24T00:34:00.003+01:002009-08-24T00:58:15.456+01:00PHP Arrays - End vs IndicesI've looked through the PHP Arrays function list lately while working on some php scripts that requires lots of interaction with Arrays. It came to me that the following 2 are the identical:<br /><br />$value = end($array);<br />$value2 = $array[count($array)-1];<br /><br />But which is more efficient?<br /><br />In a test, I tested both with a 1000 elements array. A total of 5 tests were ran and an average of 0.00040926s for using end() and 0.00041699s for using $arr[count($arr)-1].<br /><br />That was only a single dimension array. Which means that all the elements are non-arrays. The moment i ran on a 2 dimensional array, the test results differ! Again I ran 5 tests, and an average of 0.00070285s for using end() and 0.00040769s for $arr[count($arr)-1].<br /><br />Why? end() has to move the internal pointer of the array all the way to the end of the array. However, end() is still useful for arrays whose keys are not numeric.<br /><br />The codes for the test can be found on pastebin at <a href="http://thephpcode.pastebin.com/f7fa7d00c">http://thephpcode.pastebin.com/f7fa7d00c</a>Sam Yongnoreply@blogger.com0tag:blogger.com,1999:blog-3772193622268326056.post-92148574981255581592009-08-14T01:43:00.002+01:002009-08-14T01:50:23.669+01:00MySQL transaction (rollback+commit) - better with PHPLately I've been working on a project that has MySQL tables with relationship to each other. I have several functions that accesses the Database, and one function to call all these functions. However, I need to know that if one of the function that accesses the database fails, I need to do a rollback. <br /><br />Here's how we can do it:<br /><br /><code>&lt;?php<br />function addShop($shop){<br /><br />$ok = true;<br />$ok = $ok && mysql_query('START TRANSACTION');<br /><br />$ok = $ok && shops_AddShop($shop);<br />$ok = $ok && ($shop['id'] = mysql_insert_id());<br />$ok = $ok && shops_UpdateCategories($shop);<br /><br />if($ok){<br />mysql_query('COMMIT');<br />}else{<br />mysql_query('ROLLBACK');<br />}<br /><br />return $ok;<br />}<br /><br />?&gt;</code><br /><br />If one of the MySQL queries failed, I can do a rollback and reverse the appropriate changes. It's much better taking advantage of the <a href="http://thephpcode.blogspot.com/2009/08/improving-and-speed-up-conditional.html">short circuit evaluation</a> as talked about earlier on. <br /><br />In that case you will have a more stable application.Sam Yongnoreply@blogger.com0tag:blogger.com,1999:blog-3772193622268326056.post-51347230783041530972009-08-14T01:06:00.004+01:002009-08-20T02:06:07.552+01:00Getting function name in a functionI came to this time when I was doing recursive functions. I thought that if I change the function name, I will have to change the name again in the codes within the function. Consider the function below.<br /><br /><code>&lt;?php<br /><br />function a($v){<br />$ret = array();<br /> if(is_array($v))<br /> {<br /> foreach($v as $k){<br /> $ret[] = a($k);<br /> }<br /> }else{<br /> $ret = $v;<br /> }<br /> return $ret;<br />}<br /><br />?&gt;</code><br /><br />If i were to change the function name, and I forgot to change the one within the code, I will cause myself an error and debug intensively.<br /><br />However using backtrace, I am able to get the function name when inside a function. The function below enables you to get the function name when called. <br /><br /><code>&lt;?php<br /><br />function func_name(){<br />$bt = debug_backtrace();<br />$ret = '';<br />if(isset($bt[1]) && isset($bt[1]['function'])){<br />$ret = $bt[1]['function'];<br />}<br />return $ret;<br />}<br /><br />?&gt;</code><br /><br />So to get the first function working even after changing function name:<br /><br /><code>&lt;?php<br /><br />function a($v){<br />$ret = array();<br /> if(is_array($v))<br /> {<br /> $f = func_name();<br /> foreach($v as $k){<br /> $ret[] = $f($k);<br /> }<br /> }else{<br /> $ret = $v;<br /> }<br /> return $ret;<br />}<br /><br />?&gt;</code><br /><br />And there you have it!<br /><br />This function was extracted from the php class (/class/php.class.php) of the fast and lightweight PHP framework - Samstyle PHP Framework 1.2.9 AlphaSam Yongnoreply@blogger.com0tag:blogger.com,1999:blog-3772193622268326056.post-1426354120051526812009-08-09T12:22:00.000+01:002009-08-09T13:37:31.544+01:00Happy Birthday Singapore!<span style="font-weight:bold;font-size:140%;">We, the citizens of Singapore, pledge ourselves as one united people, regardless of race, language or religion, to build a democratic society, based on justice and equality, so as to achieve happiness, prosperity and progress for our nation.</span><br /><br />Happy Birthday Singapore!Sam Yongnoreply@blogger.com0tag:blogger.com,1999:blog-3772193622268326056.post-40473781797403381902009-08-07T00:22:00.003+01:002009-08-07T00:32:20.387+01:00Calculating Age using Birthday in PHPHere's some food for the thoughts: calculating age using birthday in PHP. <br /><br /><code>&lt;?php<br /><br />function getAge($birthday){<br /> $dt = strtotime($birthday);<br /> // convert the birthday to a standard format (UNIX epoch)<br /> $a = gmdate('Y') - gmdate('Y',$dt);<br /> // find the difference of years<br /> return $a; // return the age.<br />}<br /><br />?&gt;</code><br /><br />And here we have, a simple Age calculating function which is useful when displaying age on User profiles or calculating age restriction and so on. <br /><br />For example, you can put this against a movie age rating checker:<br /><code>&lt;?php<br /><br />$bday = '1993-04-05';<br />$age = getAge($bday);<br /><br />$movies = getPGMovies();<br /><br />if($age >= 21){<br /> // R21 and below can be watched<br /> $movies= array_merge($movies,getR21Movies());<br />}<br />if($age >= 18){<br /> // M18 and below can be watched<br /> $movies= array_merge($movies,getM18Movies());<br />}<br />if($age >= 16){<br /> // NC16 and below can be watched<br /> $movies= array_merge($movies,getNC16Movies());<br />}<br />// display $movies<br />?&gt;</code>Sam Yongnoreply@blogger.com1tag:blogger.com,1999:blog-3772193622268326056.post-32798325233796802832009-08-05T12:04:00.004+01:002009-08-14T01:42:55.680+01:00Improving and Speed up Conditional ExpressionsThis is something cool and you can implement in your PHP scripts, and also you should make this a habit for most of your programming languages - and that is <a href="http://en.wikipedia.org/wiki/Short-circuit_evaluation">Short Circuit Evaluation</a>.<br /><br />Consider the following code:<br /><br /><code>&lt;?php<br /><br />function a(){<br />echo 'a';<br />return true;<br />}<br /><br />function b(){<br />echo 'b';<br />return false;<br />}<br /><br />if(b() && a()){<br />echo 'c';<br />}<br /><br />?&gt;</code><br /><br />When run, the output is only 'b'. Reason being that when the if statement is run, the checks from bracket then left to right. If the first expression evaluates into false, the second will not be run. <br /><br />Now take a look at the OR comparison operator.<br /><br /><code>&lt;?php<br /><br />function a(){<br />echo 'a';<br />return false;<br />}<br /><br />function b(){<br />echo 'b';<br />return true;<br />}<br /><br />if(b() || a()){<br />echo 'c';<br />}<br /><br />?&gt;</code><br /><br />This time, the output is 'bc'. Reason being that the expression in IF will be evaluated to the first true. if the first true is found, the rest will not be executed.<br /><br />This allows you to speed up your application. Think about the following code:<br /><br /><code>&lt;?php<br /><br />$url = htmlentities($_POST['url']);<br /><br />if($url == '' || validate::url($url)){<br />echo 'URL is not valid.';<br />}else{<br />echo 'Valid URL provided';<br />}<br /><br />?&gt;</code><br /><br />It'll help to save time if the string is empty - since Short Circuit Evaluation parses that $url is empty, so it's a true and it won't bother to execute the rest of the expression.Sam Yongnoreply@blogger.com0tag:blogger.com,1999:blog-3772193622268326056.post-20446886921245644582009-07-30T06:37:00.004+01:002009-08-01T05:50:24.884+01:00Calling PHP functions from Javascript using/via AJAXThis has been quite a topic for some time - the ability for PHP functions to be called from Javascript. Well, yesterday I did it by implementing this feature into Samstyle PHP Framework. <br /><br />This is similar to ASP.NET AJAX Extension's Webservice, where you can directly call Methods in classes of your ASP.NET website.<br /><br />Download and experiment with this new feature at <a href="http://code.google.com/p/samstyle-php-framework/">http://code.google.com/p/samstyle-php-framework/</a>. Only available in the framework after version 1.2.6 BETA.<br /><br />But again remember, PHP is a server-side script, which shouldn't have access from a client-side script like javascript. here we're doing AJAX calls back to the server to call the function.Sam Yongnoreply@blogger.com0tag:blogger.com,1999:blog-3772193622268326056.post-63668772036633975442009-07-26T04:37:00.004+01:002009-07-26T04:45:01.930+01:00PHP: Generate random color codeHello! today I was surfing the net again reading up articles when I came across this website which has a few codes on several uses. but their snippets were quite full of flaws and vulnerability.<br /><br />well, I am going to talk about one of their code snippets: <a href="http://phpsnips.com/snippet.php?id=34">http://phpsnips.com/snippet.php?id=34</a> - Generating random color code.<br /><br />Here's mine, a function that generates CSS-compatible colour code in hexadecimal:<br /><code>&lt;?php<br /><br />function rand_colorCode(){<br />$r = dechex(mt_rand(0,255)); // generate the red component<br />$g = dechex(mt_rand(0,255)); // generate the green component<br />$b = dechex(mt_rand(0,255)); // generate the blue component<br />$rgb = $r.$g.$b;<br />if($r == $g && $g == $b){<br />$rgb = substr($rgb,0,3); // shorter version<br />}<br />return '#'.$rgb;<br />}<br /><br />$code = rand_colorCode();<br />echo '<span style="color:'.$code.'">This code is '.$code.'</span>';<br /><br />?&gt;</code><br /><br />Isn't this much better than the one posted at phpsnips.com? Note that this function doesn't utilize the functions in GD, but you can use the RGB in GD.Sam Yongnoreply@blogger.com1tag:blogger.com,1999:blog-3772193622268326056.post-63989250735304126892009-07-23T15:49:00.003+01:002009-07-23T15:54:20.838+01:00Using single instead of double quotes in PHPToday I was reading up on some articles on the web when I suddenly gave thought about the codes I have always been doing.<br /><br />The other day I was talking to my friend about using single or double quotes, and I persisted on using single quotes instead of double quotes while writing string in PHP. My friend asked why: and here's why we use single quote (') instead of double (").<br /><br />When writing double (") quotes, PHP parses for variables and control characters (e.g. \n, \r, \t, ...) inside the string:<br /><br /><code>&lt;?php<br /><br />$str = "testing";<br />echo "my string: $str";<br />// outputs string(18) "my string: testing"<br /><br />?&gt;</code><br /><br />Where possible, use single quotes (') to write strings:<br /><br /><code>&lt;?php<br /><br />$str = 'testing';<br />echo 'my string: '.$str;<br />// outputs string(18) "my string: testing"<br /><br />?&gt;</code><br /><br />In conclusion: Single quotes speeds things up.Sam Yongnoreply@blogger.com0tag:blogger.com,1999:blog-3772193622268326056.post-87815396867661618442009-07-20T16:46:00.003+01:002009-07-20T16:50:41.434+01:00Samstyle PHP Framework v1.2.0 released<span style="font-weight:bold;">Finally Samstyle PHP Framework v1.2.0 is released!</span> As promised, most features listed on the project home page are implemented in the v1.2.0 release.<br /><br />You can download a copy of the framework and start using it by visiting the project home page at <a href="http://code.google.com/p/samstyle-php-framework/">http://code.google.com/p/samstyle-php-framework/</a>.<br /><br />it is the stable version and you can use it. <br /><br />Upcoming 1.2.1 will include a Form Javascript validator which you can create using the validator class.<br /><br />Should you need any help with framework, you can write a comment here, or on the Google code side, or email me.Sam Yongnoreply@blogger.com0tag:blogger.com,1999:blog-3772193622268326056.post-47547479261536505452009-07-19T14:43:00.003+01:002009-07-20T00:04:03.546+01:00PHP Code crashes ApacheToday i was reading up DoS and DDoS on Wikipedia when i came across this thing about Forkbomb (a kind of wabbit). So I tried it out on my own localhost server. <br /><br />This was what i wrote in the file:<br /><code>&lt;?php<br /><br />while(include(basename($_SERVER['PHP_SELF'])));<br /><br />?&gt;</code><br /><br />Then I run the script on my browser. as expected, "apache.exe" crashes right after the script ran. The script will keep running and including itself, which in turns run more loops.<br /><br />However, the amazing thing is that, apache recovered itself and my localhost is able to run again. If you have noticed, apache actually runs on 2 processes, both "apache.exe". When the main process crashes, the secondary process detects this crash and then load the server again, thus preventing downtime.Sam Yongnoreply@blogger.com3tag:blogger.com,1999:blog-3772193622268326056.post-5409660460818300632009-07-14T08:57:00.004+01:002009-07-25T03:34:26.396+01:00PHP GD: Creating a security captcha in PHPI was working on an application yesterday when I had to write a captcha security check on the form. So I came up with the following script to generate an image with random code. The script will also rotate the code a little in the image and randomize the position of the code on the image. a random background will also be selected (random background image should be 100px by 30px).<br /><br /><code>&lt;?php<br />session_start();<br /><br />// note that $_GET['k'] is a static key that you can enter when getting the image.<br />// generate the key and store into session<br />$_SESSION['captchasecurity'] = md5(mt_rand().time().$session_hash).$session_hash.md5($_GET['k'].mt_rand());<br />// create a shorter key for display<br />$key = dechex(crc32($_SESSION['captchasecurity']));<br /><br />// disable the client side caching<br />header('Content-type: image/png');<br />header('Cache-Control: max-age=0');<br />header('Expires: '.gmdate('r',time()-3600*24*365));<br />header('Pragma:');<br /><br />// randomize the background image<br />$r = mt_rand(0,3);<br />$captcha = imagecreatefrompng('img/captcha'.$r.'.png');<br /><br />$cl = mt_rand(0,50);<br />$c = imagecolorallocate($captcha, $cl, $cl, $cl);<br />$line = imagecolorallocate($captcha,233,239,239);<br /><br />$txtx = imagefontwidth(5) * strlen($key) +10;<br />$txty = imagefontheight(5);<br /><br />$timg1 = imagecreate($txtx,$txtx);<br />$ba = imagecolorallocatealpha($timg1,0, 0, 0,127);<br />imagefilledrectangle($timg1, 0, 0, $txtx, $txtx, $ba);<br />imagesavealpha($timg1, true);<br /><br />$tc = imagecolorallocate($timg1, $cl, $cl, $cl);<br />imagestring($timg1, 5, 0, $txtx/2 - $txty/2, $key, $tc);<br /><br />$tca = imagecolorallocatealpha($timg1, 255, 255, 255,127);<br />$timg = imagerotate($timg1, mt_rand(-5,5), $tca);<br />imagesavealpha($timg, true);<br />imagecopy($captcha, $timg, mt_rand(2,22), mt_rand(3,6), 0, $txtx/2 - $txty/2, $txtx, $txtx);<br /><br />// output the captcha image<br />imagepng($captcha);<br /><br />// free up memory<br />imagedestroy($timg);imagedestroy($timg1);<br />imagedestroy($captcha);<br />?&gt;</code><br /><br />To check whether the code entered by the user against the one generated, simply do the following:<br /><code>&lt;?php<br /><br />// case sensitive check. CRC32 hash is in low case. <br />if($_POST['captchacode'] != dechex(crc32($_SESSION['captchasecurity']))){<br />// the code is wrong<br />}else{<br />// code is correct.<br />}<br /><br />?&gt;</code><br /><br />Get the full code on Pastebin: <a href="http://thephpcode.pastebin.com/f21c1ed80">http://thephpcode.pastebin.com/f21c1ed80</a><br /><br />Note that this captcha script has been tested to be successful on my localhost. I cannot guarantee 100% bot proof. You are advised to step up the security in your own application.Sam Yongnoreply@blogger.com4