php – nivas,b:=log() https://www.nivas.hr/blog This is a blog from the Nivas.hr crew to the galaxy of unknown. Wed, 02 Aug 2017 13:11:24 +0000 en-US hourly 1 https://wordpress.org/?v=5.8.2 Recursions and PHP https://www.nivas.hr/blog/2017/08/02/recursions-and-php/ https://www.nivas.hr/blog/2017/08/02/recursions-and-php/#respond Wed, 02 Aug 2017 11:31:01 +0000 https://www.nivas.hr/blog/?p=2713 Introduction

Recursion occurs when something uses a similar version of itself. Recursive procedure is one where at least one of its’ steps calls for a new instance of that very same procedure (broadly speaking we say that function calls itself). It is similar to iteration, with one major difference – iteration requires predefined number of repetitions, and with recursion one doesn’t need to know in advance how many repetitions there will be. In order to limit the number of repetitions and to avoid or stack overflow there must be a terminating scenario defined, so that the procedure can complete.

PHP limits the number of recursive calls and but it’s possible to expand this limit in php.ini file options.

http://php.net/manual/en/pcre.configuration.php

All recursive algorithms must have the following:

1. Base Case – end condition which is the solution to the “simplest” possible problem

2. Work toward Base Case – making the problem simpler

3. Recursive Call – using the same algorithm to solve a simpler instance of the problem

In order to show on a simple example how recursion works we will use the factorials. In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example: 5! = 5 * 4 * 3 * 2 * 1 = 120. Let’s write two simple algorithms to calculate the factorial value of given integer.

The first example will use iterative approach:

$number = 5;
function iterativeFactorial($number)
{
 if ($number < 0) {
 return -1; //initial condition, if number is negative exit the program
 }
 else if ($number === 0) {
 return 1; //factorial of 0 is 1
 }

 $factorial = 1;

 if ($number <= 1) return $factorial;
 while ($number > 1) {
 $factorial *= $number;
 $number--;
 }
 return $factorial;

}

The second example will use recursive approach:

$number = 5;

function recursiveFactorial($number)
{
 if($number < 0) {
 return -1; //initial condition, if number is negative exit the program
 }
 else if($number === 0) {
 return 1; //base case to exit the recursion
 } else {
 return $number * recursiveFactorial($number-1); // recursive call
 }
}

How It works

Phase One – creating new instances and saving them on stack

This phase is characterized by creating new instances of function calls and storing them on stack together with their addresses. In the first call the variable equals to 5 ($number = 5). It goes through initial condition – number must be positive in order to continue down the function. Then the base condition in which if number equals to zero the function will exit recursion. If this doesn’t happen ($number > 0), the function will call itself recursively to derive new instance of itself – 5 * recursiveFactorial( 5 – 1 ). The first instance of the function will wait on stack while the new instance repeats the process, this time $number variable will be equal to 5 – 1, which is 4 and it will compute 4 * recursiveFactorial (3). The process will continue until the $number variable is zero, in which case the function will return 1 and won’t call for the new instance of itself (base condition). At this point all created instances are waiting on stack, together with their return addresses.

Phase Two – Computing and deleting created instances from stack

The returning of 1 wakes up the last created instance of the function on stack (the one that called It – $number = 1), which accepts the return value of 1 and uses it to compute 1 * recursiveFactorial(1-1). This returns 1, the called instance is being deleted from stack and the next instance on stack is being called ($number = 2). After computing 2 * recursiveFactorial(2-1), 2 is returned, the called instance is being deleted from stack and next instance on stack is being called. The process continues until the “oldest” instance of function (the first one to be stored on stack, $number = 5) is computed and the final value of 120 returned.

Simple test

Both functions were ran as php files from command line, using Ubuntu on my laptop. The $number variable was set to 150 and each function was ran 3 times.  The results showed that on average recursive approach needed approximately 3.7 times more time than iterative.

Conclusion

The main disadvantage of recursive approach is that the algorithm may require large amounts of memory if the recursion goes very deep. This is because when the function is called, a new instance is created in memory.  Also, it will most likely consume more time than iterative. Both disadvantages can be minimized with tail optimization which is not supported in PHP.

However there are pros to using recursive approach. It is more elegant and makes code more readable. Because of that it can reduce time needed to write and debug code. This approach is more suitable for solving specific problems, when problem can be broken down into smaller pieces (such as sorting algorithms).

The ultimate goal should always be to get as close as possible to achieving ‘low memory consumption and short execution time’. It’s up to a programmer to decide which approach works better for a specific problem in a specific development environment.

]]>
https://www.nivas.hr/blog/2017/08/02/recursions-and-php/feed/ 0
ZgPHP meetup conference 2013 https://www.nivas.hr/blog/2013/09/10/zgphp-meetup-conference-2013/ https://www.nivas.hr/blog/2013/09/10/zgphp-meetup-conference-2013/#respond Tue, 10 Sep 2013 10:23:41 +0000 https://www.nivas.hr/blog/?p=2380 On 14th of September (this Saturday) our friends from ZgPHP user group will held a second anniversary jubilee ZgPHP Meetup and a full blown one-day PHP conference. The conference will be held in Croatian chamber of commerce offices (HGK), Nova cesta 3-7 on the second floor (entrance is located on south side of the building, same entrance as Lidl). For further details check out the conference web site.

See you there!

logo

]]>
https://www.nivas.hr/blog/2013/09/10/zgphp-meetup-conference-2013/feed/ 0
rim – PHP Remote Image Library https://www.nivas.hr/blog/2012/01/16/rim-php-remote-image-library/ https://www.nivas.hr/blog/2012/01/16/rim-php-remote-image-library/#comments Mon, 16 Jan 2012 13:35:47 +0000 https://www.nivas.hr/blog/?p=2174 Working on recent home project I found there is no library in PHP to get dimensions of remote images.
So I made rim php library to get type and size of remote images in optimized way.

Fork it on github

The easiest way of getting a image dimension is by using getimagesize PHP function.
It has one great fault when working with remote images, whole image must be downloaded in order for getimagesize to read it’s dimensions.
So if you want to find out dimensions of jpeg 2MB in size getimagesize will first download it. There goes bandwidth!

Rim downloads only few byes need to determine image type and dimensions.
Also if you need to get dimensions of lot’s of pictures rim will thread fetch request for further speed increase.

Take a look at this benchmark, fetching image types and sizes of all images on Hot New Releases in Books at amazon.com:

Have fun!

P.S.
Bug reports would be appreciated ;)

]]>
https://www.nivas.hr/blog/2012/01/16/rim-php-remote-image-library/feed/ 3
Payment processing in the region and PayPal integration woes https://www.nivas.hr/blog/2011/04/21/payment-processing-in-the-region-and-paypal-integration-woes/ https://www.nivas.hr/blog/2011/04/21/payment-processing-in-the-region-and-paypal-integration-woes/#respond Thu, 21 Apr 2011 09:36:44 +0000 https://www.nivas.hr/blog/?p=1960 From mid March, companies in Croatia can finally receive electronic money transfers via PayPal (read background story in my article published in Nacional).

Payment processing isn’t something new in Croatia, but PayPal is. On-line stores were able for years to process user credit cards via some of our local popular credit card processing services like T-Com Pay Way or Webteh – WebPay (or directly through connections with each bank – less popular method). But only recently (a year ago), with arrival of Kolektiva and similar sites oriented to wider online consumer public, online payments started to become more popular, widely accepted and less frightened to a regular Joe.

In our e-commerce web development work so far, we had chance to work in close with following regional internet payment service providers:

And just recently – the PayPal.

No matter PayPal is mature product, integration was not walk in the park. From developers standpoint, I would definitely commend T-Com Pay Way, Webteh and qVoucher services for ease of integration and support they have. In contrast to PayPal’s undocumented features (or lack of documentation and examples) or EMS’s infinite redirects to 3rd party pages (enforced by other parties) in payment process.

PayPal
After some headache & time spent at the PayPal sandbox (self-contained environment within which you can prototype and test PayPal features and APIs) we finally managed to get it working.

We used widely used HTML way to integrate Website Payments Standard with our shopping cart (please see “Third-Party Shopping Carts – The Cart Upload Command”) since integration via API has been proven to be more complex and undocumented than Facebook’s SDK.

For security we used Encrypted Website Payments (please see “Protecting Payment Buttons by Using Encrypted Website Payments”.

Encrypted Website Payments relies on public-key cryptography using OpenSSL which is available both as external program that can be executed from PHP and as php extension. Prepare to enter world of pain with this one, since most of examples use executable file to do actual encoding.

Using OpenSSL as extension with PayPal is not straightforward, best example can be found at PayPal SDK in php toolkit.

We implemented support for both IPN and PDT notifications:

  • PDT (Payment Data Transfer) – is secure method to retrieve details about PayPal transaction after (and if) user chooses to return to our site after paying on the PayPal. It should be used only to display information to the user. Our system is not depending on it since there is no guarantee that this action will be executed.
  • IPN(Instant Payment Notification) – is direct PayPal to our system communication. In order to verify authenticity of IPN data received from PayPal should be checked and then sent back to PayPal in exact order it was received. PayPal should respond with “VERIFIED”.

Please note that although PayPal send newline as CR+LF (%0D%0A), PHP returns these new lines as LF (%0A) – so, newlines transformed by PHP into LF must be replaced with CR+LF before data is sent back to PayPal. This bug can easily be reproduced if you enter both Address line 1 and Address line 2 during payment, because those two lines PayPal combines into one field separated with CR+LF.

You can try all all this, or you can just contact us for consulting and/or implementation services. :)

]]>
https://www.nivas.hr/blog/2011/04/21/payment-processing-in-the-region-and-paypal-integration-woes/feed/ 0
Will Internet Explorer 6 finally die on August 31, 2009? https://www.nivas.hr/blog/2009/06/04/will-internet-explorer-6-finally-die-on-august-31-2009/ https://www.nivas.hr/blog/2009/06/04/will-internet-explorer-6-finally-die-on-august-31-2009/#comments Thu, 04 Jun 2009 13:50:28 +0000 https://www.nivas.hr/blog/?p=1208 We have been using very strange setups here at the office to test sites on Internet Explorer 6. Lot’s of us still use Windows XP, and some of us still had default Internet Explorer 6 on our computers. When IE8 was released, we didn’t upgrade immidiately so we could still test sites in default IE6 installations (lots of different fake/multi IE setups throw most bizzare errors, so testing under default IE installation was a must).

But couple of days ago we finally give in to the dark forces of Windows Auto update, and we upgraded to Internet Explorer 8.

The only correct way now for site testing under different Internet Explorer versions is by using virtual machine of some sort. Vmware is option, but you have to build your own virtual setup which can be a pain. However, Microsoft has been good enough to finally provide developers with Internet Explorer Application Compatibility VPC Images for their Virtual PC. You can download completely free, perfectly legal and working images of followign operating systems packed with IE’s:

  • Windows XP SP3 with IE6,
  • Windows XP SP3 with IE7,
  • Windows XP SP3 with IE8,
  • Vista with IE7 and
  • Vista with IE8.

All XP images will expire on August 31, 2009, which is the end-of-life for good old Windows XP, and hopefully end-of-life of Internet Explorer 6. Hello Windows Seven! :) (Btw, I’ve tried RC1 of Windows Seven and it ROCKS, not only because of the name).

]]>
https://www.nivas.hr/blog/2009/06/04/will-internet-explorer-6-finally-die-on-august-31-2009/feed/ 3
View source crashes Firefox v3.0.9 https://www.nivas.hr/blog/2009/04/24/view-source-crashes-firefox-v309/ https://www.nivas.hr/blog/2009/04/24/view-source-crashes-firefox-v309/#comments Fri, 24 Apr 2009 14:50:05 +0000 https://www.nivas.hr/blog/?p=1069 Since I updated FF to 3.0.9 (on Win XP), view source doesn’t work. Even “firefox -safe-mode” crashes browser every time. Thank you Mozilla Html Validator plugin! Hope 10.000 error reports I sent will help you.

update 27-04-2009: Yes, my friends were right. Html Validator plugin was causing this. After updating to v0.8.5.6 problem gone. And note to FireFox plugin developers – please DON’T put this in install.rdf without being completely sure that your plugin won’t break anything (maybe 10% of plugins can do this):
<em:maxVersion>3.0.*</em:maxVersion>

fferror

]]>
https://www.nivas.hr/blog/2009/04/24/view-source-crashes-firefox-v309/feed/ 3
goto https://www.nivas.hr/blog/2009/04/22/goto/ https://www.nivas.hr/blog/2009/04/22/goto/#comments Wed, 22 Apr 2009 20:04:12 +0000 https://www.nivas.hr/blog/?p=1061 Ha! I completely missed new function implemented in php 5.3 – old’skool “goto“! :) I am not particularly happy. Not happy at all.
[ftf w=”490″ h=”150”][/ftf]Outputs: Bar

]]>
https://www.nivas.hr/blog/2009/04/22/goto/feed/ 1
Online tickets for U2 concert in Zagreb = fail https://www.nivas.hr/blog/2009/03/27/online-tickets-for-u2-concert-in-zagreb-fail/ https://www.nivas.hr/blog/2009/03/27/online-tickets-for-u2-concert-in-zagreb-fail/#comments Thu, 26 Mar 2009 23:34:59 +0000 https://www.nivas.hr/blog/?p=948 U2 is (aside from Lepa Brena) – the most anticipated concert of the year in Croatia. Marketing campaign was pretty strong (so I guess organizers invested some money) and commercials strongly advertised online ticket sale which started just couple of minutes ago (at 00:01AM).

u2concert

Unfortunately for U2 fans, online ticket sales maybe did start, but they sure did end pretty fast. But not because web shop run out of tickets, but because web shop and organizers of the concert ran out of professionalism.

Look guys, if you decided to run so strong advertising campaign across couple of countries which loudly and clearly says: “Ticket sales start online on Friday at 00:01”, I suppose one who does all that, would also build a website which can sustain such number of customers?

Well, I guess not.

Exactly the same thing happened some time ago when Croatian Football Association launched online reservation of world cup tickets (if I can recall correctly). I am not big sports fan but many of my friends are and they were very pissed.

Servers are so dirty cheap, and downtime costs a lot of money (nerves, reputation…), Especially if downtime happens a minute you launch your service. My personal preference/advice regarding server configuration in time of special events or service launch is – tend to over engineer your network! EC2, EBS, S3 (Amazon Web services) and other cloud computing solutions do their job pretty good in situations like this.

Otherwise you get this beauty…
serviceunavailable

]]>
https://www.nivas.hr/blog/2009/03/27/online-tickets-for-u2-concert-in-zagreb-fail/feed/ 1
Letter Đ mistery – Ð!=Đ and ð != đ https://www.nivas.hr/blog/2008/10/27/letter-d-mistery-%c3%b0d-and-%c3%b0-d/ https://www.nivas.hr/blog/2008/10/27/letter-d-mistery-%c3%b0d-and-%c3%b0-d/#comments Mon, 27 Oct 2008 14:14:09 +0000 https://www.nivas.hr/blog/?p=652 We spent couple of hours trying to figure out this one, so we decided to share it with our fellow readers and hopefully, save some time and unnecessary stress for them. UTF-8 is defacto standard encoding for multilanguage websites. PHP5 doesn’t have native support for it, but you can integrate it. MYSQL supports utf8, but not utf8_croatian_collation. But you can also hack your way around that for sorting. If you are not dealing with Croatian letters and UTF-8, you probably won’t encounter this problem. However, if you ARE using UTF-8 read on!

We are redesigning one large website and naturally, some content from old website has to be migrated to new site. Since we don’t have access to their database, we have to manually copy content from old website’s HTML source. Client’s old site is in UTF-8. Imagine following entry in old HTML source:
[ftf w=”480″ h=”105″][/ftf]
This is a select tag with list of cities in Croatia, the city in example is Đakovo. So as I said, we are copy-ing large amounts of data from old HTML’s, and we do not care why old site displays this city as “&#208;akovo” and not as “Đakovo”. After we pasted “Ðakovo” into our engine, we momentarily started to get all sorts of different errors. The most bizare one was comming from our utf8_strtolower function which had to return string “đakovo”. Instead it was returning string “ðakovo”. Wicked!

After some digging, we found out that there was nothing wrong with our utf8 php methods nor our mysql database. We found out that the letter Ð (hex d0 00) we pasted from HTML was just not the letter Đ (hex 10 01) we needed. Somebody (or something) very brilliant, used letter Eth instead of standard Croatian letter D with stroke.

Eth (Ð, ð; also spelled edh or eð) is a letter used in Old English, Icelandic, Faroese (in which it is called edd). In the Unicode universal character encoding standard, upper and lower case eth are represented by U+00D0 and U+00F0. These code points are inherited from the older ISO 8859-1 standard. In HTML, eth is represented by the Latin character entities Ð and ð.

Đ (lowercase đ) is a letter of the Latin alphabet, formed from D with the addition of a bar or stroke through the letter. This is the same modification that was used to create eth (ð), but eth is based on an insular variant of d while đ is based on its usual upright shape. In Unicode the letter is represented as U+0110 LATIN CAPITAL LETTER D WITH STROKE and U+0111 LATIN SMALL LETTER D WITH STROKE.

So there you have it. No matter the letters look the same, beware what you copy/paste. :)

]]>
https://www.nivas.hr/blog/2008/10/27/letter-d-mistery-%c3%b0d-and-%c3%b0-d/feed/ 3
We got Super Mario https://www.nivas.hr/blog/2008/06/27/we-got-super-mario/ https://www.nivas.hr/blog/2008/06/27/we-got-super-mario/#comments Fri, 27 Jun 2008 14:54:44 +0000 https://www.nivas.hr/blog/?p=334 So anyways, it is bleedin’ hot outside, therefore, logical conclusion is that I should make Super Mario out of Post-It papers on the wall. Check it:

Super Mario

It really looks awesome in our chill out … sorry, I mean, in our conference room.
Super Mario

So how are you spending your hot hot hot summer days?



]]>
https://www.nivas.hr/blog/2008/06/27/we-got-super-mario/feed/ 5
How HRT failed in their intention to become Croatian BBC https://www.nivas.hr/blog/2008/05/17/how-hrt-failed-in-their-intention-to-become-croatian-bbc/ https://www.nivas.hr/blog/2008/05/17/how-hrt-failed-in-their-intention-to-become-croatian-bbc/#comments Sat, 17 May 2008 10:08:06 +0000 https://www.nivas.hr/blog/?p=303 This one goes to all our foreign readers which would otherwise probably be left out from knowing news of the week in Croatia – Croatian National Television (HRT.hr) bluntly copied British Broadcasting Corporation (BBC.co.uk) website!

The shit hit the fan few days ago and whole Croatian web community got pretty pissed off. HRT spokesman said (in defence to accusations of stealing BBC’s design) that HRT wishes to be Croatian BBC, and ok – I absolutely respect that. I also respect their understanding for the need to redesign the site. The old HRT.hr website was 8-10 years old and not something to look at.

But lets get one thing straight – I totally and absolutely disrespect the method of execution of their intentions. Whoever did the production of this monstrosity lacks the proper knowledge and experience… 10 years of experience in web development field at least.

Client is always right, but clients are not web designers (no matter how bad they would want it to be), and our sole professional and moral obligation is to notify client of possible breach in copyright laws, breach in functionality or any kind of possible side-effect that some of their ideas could do to harm the project, harm them self or harm web developers reputation.

Not once, but every time, we ask client – which websites do they like, who are their competitors, who is their role model in business… And based on our previous experience, knowledge, research, strategic planning and comprehensive user tests – we produce results. Results which are specially suited for our client. Not fake copy of website they wish to have.

As our friend Maratz nicely wrote, and I couldn’t agree with him more: “This is the embarrassment of the decade for the Croatian web community.”.

Compare and cry ™:

More voices:

Updated 20.05. – Big up to our comrades in arms at BBC. And thanks to Alan Connor (co-editor of BBC Internet Blog) who linked to my article, and hey I really don’t know how I missed this beauty – http://www.rtl.hu/. It seems that BBC was true inspiration for many “web designers”. But, RTL.hu is light AGES ahead of HRT.hr. Whoever did the job, they did it well. There is just a small we-copied-bbc-design fact… but hey. :)

]]>
https://www.nivas.hr/blog/2008/05/17/how-hrt-failed-in-their-intention-to-become-croatian-bbc/feed/ 13
mysql utf8 latin2 utf8 weirdness https://www.nivas.hr/blog/2007/09/10/mysql-utf8-latin2-utf8-weirdness/ https://www.nivas.hr/blog/2007/09/10/mysql-utf8-latin2-utf8-weirdness/#comments Mon, 10 Sep 2007 18:44:58 +0000 https://www.nivas.hr/blog/2007/09/10/mysql-utf8-latin2-utf8-weirdness/ This one is a keeper, have to write it down somewhere in case I forget it by tomorrow morning. :) Today I was doing routine deploy of one of our new websites to production server. Everything went smoothly, except the fact I couldn’t see any of Croatian letters on the site texts (which were stored in mysql)!! We did migration to UTF8 some time ago, and this was highly unexpected. So I started to dig into the dump. :)

Looking at the mysqldump of a database I was a bit surprised to see Croatian letters screwed up beyond recognition. For example letter “š” was represented as “ÄąÄO„” (4 bytes), “č” was “čO” (two bytes)… etc. OMG! All our tables are “CHARSET=utf8”, we force “AddDefaultCharset utf-8” in Apache and all of our markup uses “charset=utf-8” for content type encoding. BUT, we unintentionally left one very bad call in our config file which got triggered if site was running on development server – “SET NAMES ‘latin2’ COLLATE ‘latin2_croatian_ci”. The production config had SET NAMES utf8, but development didn’t. Oh boy.

Ok so now I had a real mess – utf8 tables with utf8 data in them stored as re-encoded latin2 but in utf8!? I tried converting the dump from ISO8859-2 to UTF8 but that just made things worse, some of characters now used 6 bytes which isn’t good. The solution was pretty straight forward. I converted the dump from UTF8 to ISO-8859-2 and I got real UTF8 again. I imported the converted dump and changed for good config files to “SET NAMES ‘utf8’ COLLATE ‘utf8_general_ci”.
iconv to the rescue:

[ftf w=”400″ h=”150″]
mysqldump -u root -p db > weirdo-dump.sql
iconv -f UTF-8 -t ISO_8859-2//TRANSLIT weirdo-dump.sql > dump-latin2-aka-realUTF8.sql
mysql -u root -p db < dump-latin2-aka-realUTF8.sql[/ftf]

]]>
https://www.nivas.hr/blog/2007/09/10/mysql-utf8-latin2-utf8-weirdness/feed/ 3
PHP4 must die! https://www.nivas.hr/blog/2007/09/10/php4-must-die/ https://www.nivas.hr/blog/2007/09/10/php4-must-die/#respond Mon, 10 Sep 2007 02:28:45 +0000 https://www.nivas.hr/blog/2007/09/10/php4-must-die/ Harsh as it may sound, lately the web is full of headlines like that. Why, why!? Mass panic mode activated! What does it all mean?? The end of PHP as we know it?

The PHP development team finally announced end of life for PHP4. After 2007-12-31 there will be no more releases of PHP 4, and critical security fixes will be available until 2008-08-08. After that, you are running php4 on your own risk, and we all know how risky the business Internet is. Do you still have Windows NT 4.0 or RedHat 7.1 on your servers? Are they developed or supported? No!

It was about a damn time they let go php4. PHP5 has been available for 3 years, and hosting companies have had plenty of time to make the switch. From developer standpoint I have absolutely no sympathy for those who have left it until the last minute, and even then needed to be pushed. I understand the problem they have – they didn’t realize the importance of php5. And now gazillion of php3/4 sites (which make a large majority of php users) have to be “upgraded”. What will happen to them? PHP dev. team could avoid this hassle, by just plotting the php’s development road map better, and being more direct with timelines. They are still doing it wrong, since they are killing php4, and not giving enough info on forthcoming PHP6.

Our migration was also being dictated by hosting company. We asked our provider for php5 in the beginning of 2006, and begged, and cursed and then asked polite again and some time in January this year, we just couldn’t take any more of that bullshit and switched to php5. How hard was to migrate lots of messy code from php4 to php5? We did migration surprisingly fast and painless for many of our old projects. If you had error_reporting set to E_ALL durring development in php4, haven’t used register_globals or magic quotes, you should be just fine. And we introduced new PHP5 OOP stuff to our new projects immediately. All in all, PHP5.2 is now what php4 had to be back then, and I am keeping my hopes high for PHP6.

]]>
https://www.nivas.hr/blog/2007/09/10/php4-must-die/feed/ 0
Some geeky statistics https://www.nivas.hr/blog/2007/09/06/some-geeky-statistics/ https://www.nivas.hr/blog/2007/09/06/some-geeky-statistics/#respond Thu, 06 Sep 2007 00:59:16 +0000 https://www.nivas.hr/blog/2007/09/06/some-geeky-statistics/ If you don’t have a life anymore (like me), you will probably find these statistics/penetration reports interesting. :) Flash 9 is kicking, together with php5 and Apache. That’s all I wanted to hear. Read on!

Php5 finally gained some points, probably because Zend announced php4’s end of life. That should happen years ago. :) Too bad Php6 release date isn’t scheduled yet.

Netcraft’s last report says that Windows IIS takes 34.2% and Apache 48.4% of market share. Microsoft’s recent gains raise the prospect that Windows may soon challenge Apache’s leadership position. Apache has been the leading web server software since the March 1996 Netcraft Web Server Survey. In November 2005, Apache was found on 71 percent of web sites. It’s worth noting that Apache has lost market share to another open source server, lighttpd (1.2% of all sites), and Google (4.4%) as well as Windows. But if Microsoft continues to gain share at its current pace, it could close the gap on Apache sometime in 2008.

]]>
https://www.nivas.hr/blog/2007/09/06/some-geeky-statistics/feed/ 0
mysql + google https://www.nivas.hr/blog/2007/04/25/mysql-google/ https://www.nivas.hr/blog/2007/04/25/mysql-google/#comments Wed, 25 Apr 2007 16:40:57 +0000 https://www.nivas.hr/blog/2007/04/25/mysql-google/ A recent post on the Google Developer Blog announces some enhancements Google’s made to MySQL, in hopes that they will be adopted in the next release, and to allow everyone to begin using them. At the moment, patches are available for mysql v4.x only. DO-h!

]]>
https://www.nivas.hr/blog/2007/04/25/mysql-google/feed/ 1
PHP Optimization Tips – The Balkan way! https://www.nivas.hr/blog/2007/03/31/php-optimization-tips-the-balkan-way/ https://www.nivas.hr/blog/2007/03/31/php-optimization-tips-the-balkan-way/#respond Sat, 31 Mar 2007 15:06:38 +0000 https://www.nivas.hr/blog/2007/03/31/php-optimization-tips-the-balkan-way/ Lately I became obsessed with a speed and optimization of PHP web applications. Namely, we are currently working heavily on a new release of voodoo [vudu] (a content engine we built using our in-house developed framework which utilizes few common PHP design patterns). I guess that ActionScript optimization got under my skin and now it’s kicking in into PHP front. :) We are reinventing the wheel, but hey – what else would we do? Play Quake all day long? :)

Soooo, I did some benchmarking, I did some reading, and this is what I’ve came up so far:

  1. If a method can be static, declare it static. Speed improvement is by a factor of 4
  2. Avoid magic like __get, __set, __autoload
  3. require_once() is expensive
  4. Use full paths in includes and requires, less time spent on resolving the OS paths
  5. See if you can use strncasecmp, strpbrk and stripos instead of regex
  6. preg_replace is faster than str_replace, but strtr is faster than preg_replace by a factor of 4
  7. Error suppression with @ is very slow
  8. $row[’id’] is 7 times faster than $row[id]
  9. Single quotes are faster than double quotes
  10. (42 == $foo) is faster then if ($foo == 42)
  11. ++$i is faster than $i++
  12. true is faster than TRUE, And 1 is even faster than true
  13. Calling isset() happens to be faster then strlen()
  14. While is faster than do while:
    while (--$i) { //do nothing }

    as opposed to

    do { //do nothing } while (--$i);

    And this performs even better:
    for ($i=0; $i++<$count; ) { ... }

  15. Using persistant over non-persistant DB connections in mysql can increase number of requests per second by 41%
  16. You can save yet another 40% of time spent for parsing and compiling by using an opcode cache like APC
  17. References do not provide any performance benefits for strings, integers and other basic data types. In contrast, functions that accept array and object parameters have a performance advantage when references are used. This is because arrays and objects do not use reference counting, so multiple copies of an array or object are created if "pass by value" is used. So the following code:
    function ObjRef(&$o) { $a =$o->name; }
    is faster than:
    function ObjRef($o) { $a = $o->name; }
  18. In PHP 5, all objects are passed by reference automatically, without the need of an explicit & in the parameter list. PHP 5 object performance should be significantly faster.
  19. Fastest PHP Input filtering comes as a filter extension built in PHP 5.2 and is available for 5.1 as a separate download. There is a good tutorial on zend devzone
  20. The ctype extension offers a series of function wrappers around C's is*() function that check whether a particular character is within a certain range. Unlike the C function that can only work a character at a time, PHP function can operate on entire strings and are far faster then equivalent regular expressions.
    preg_match("![0-9]+!", $foo);
    vs
    ctype_digit($foo);
  21. Internally arrays are stored inside hash tables when they array element (key) is the key of the hashtables used to find the data and result is the value associated with that key. Since hashtable lookups are quite fast, you can simplify array searching by making the data you intend to search through the key of the array, then searching for the data is as simple as $value = isset($foo[$bar])) ? $foo[$bar] : NULL;. This searching mechanism is way faster then manual array iteration, even though having string keys maybe more memory intensive then using simple numeric keys. Second example is is roughly 3 times faster.

    $keys = array("apples", "oranges", "mangoes", "tomatoes", "pickles");
    if (in_array('mangoes', $keys)) { ... }

    vs

    $keys = array("apples" => 1, "oranges" => 1, "mangoes" => 1, "tomatoes" => 1, "pickles" => 1);
    if (isset($keys['mangoes'])) { ... }

Some tips may be completely out dated or completely wrong due to different hardware/software configurations on systems used for benchmarking.

And for over-obsessed characters - I've found interesting articles about how stuff is handled differently in php5.1 and 5.2 opcode - compiled variables and strings.

Sources: moskalyuk.com, whenpenguinattacks,
iBlog, phpLens, wikimedia, phpbench, php.net, php.net - migration,

]]>
https://www.nivas.hr/blog/2007/03/31/php-optimization-tips-the-balkan-way/feed/ 0
Hiring Hobos To Wait in Line for PS3 https://www.nivas.hr/blog/2006/11/17/hiring-hobos-to-wait-in-line-for-ps3/ https://www.nivas.hr/blog/2006/11/17/hiring-hobos-to-wait-in-line-for-ps3/#respond Fri, 17 Nov 2006 01:20:53 +0000 https://www.nivas.hr/blog/2006/11/17/hiring-hobos-to-wait-in-line-for-ps3/ PS3 release in the States is delayed again, and mob is getting crazy! Some wait in lines, some pay homeless to wait for them, and some get killed in drive by waiting for PS3, including reporter. I never EVER had console, so I thought, it’s time to get one. I will wait to see how Wii and PS3 will compare in the end.

]]>
https://www.nivas.hr/blog/2006/11/17/hiring-hobos-to-wait-in-line-for-ps3/feed/ 0
some notes on php design https://www.nivas.hr/blog/2006/10/28/76/ https://www.nivas.hr/blog/2006/10/28/76/#comments Sat, 28 Oct 2006 10:17:16 +0000 https://www.nivas.hr/blog/2006/10/29/76/ Today, I have read on metapundit.net some thoughts on how to improve php coding. Don’t see the real point in this, except the faster coding. Readability and maintenance is degraded slightly.

Update – 18.11.2006. – After taking some time to think about this, I have to agree with MetaPundit. Putting var names into array, and looping trough them makes code more maintainable. But I still have some issues with this, regarding more complex stuff.

Example 1:
class foo{
function foo($duration, $height, $width, $quality){
$this->_duration = $duration;
$this->_height = $height;
$this->_width = $width;
$this->_quality = $quality;
}
/* Useful code goes here*/
...
class foo{
function foo($duration, $height, $width, $quality){
foreach(array('duration', 'height', 'width', 'quality') as $arg)
{
$this->{"_$arg"} = $$arg;
}
}
Example 2:

$row = $db->query('select * from foo');
$template->setVariable('fname',$row['fname']);
$template->setVariable('lname',$row['lname']);
$template->setVariable('zip',$row['zip']);
$template->setVariable('city',$row['city']);
$template->setVariable('state',$row['state']);
$template->setVariable('street',$row['street']);
$template->setVariable('county',$row['county']);

...
$row = $db->query('select * from foo');
foreach(array('fname','lname','zip','city','state','street','zip','county') as $field)
$template->setVariable($field,$row[$field]);
...
]]> https://www.nivas.hr/blog/2006/10/28/76/feed/ 5 Filesystem corruption with PHP https://www.nivas.hr/blog/2006/10/20/filesystem-corruption-with-php/ https://www.nivas.hr/blog/2006/10/20/filesystem-corruption-with-php/#respond Fri, 20 Oct 2006 01:04:40 +0000 https://www.nivas.hr/blog/2006/10/20/filesystem-corruption-with-php/ Writing to a file is easy with PHP. But what will happen if 2 processes try to write to a file at once? Exactly, your data might easily become corrupted and useless. You don’t want that to happen, of course. That’s why you need to implement file locking. flock() is your friend. For writing to a file, you want to obtain an exclusive lock on the file. There must never be concurrent writes to a file, after all. Here’s an example.

For reading from a file, you want to obtain a shared lock. Here’s an example on how to do this.

Keep in mind that flock() will not work on NFS mounted filesystems or FAT filesystems.

]]>
https://www.nivas.hr/blog/2006/10/20/filesystem-corruption-with-php/feed/ 0
PHP Security – Never trust user input https://www.nivas.hr/blog/2006/06/20/php-security-never-trust-user-input/ https://www.nivas.hr/blog/2006/06/20/php-security-never-trust-user-input/#respond Tue, 20 Jun 2006 08:48:15 +0000 https://www.nivas.hr/blog/2006/06/20/php-security-never-trust-user-input/ No mater if you are beginner or experienced PHP programmer, you should definitely check out PHP Security Guide by Rob Miller. SQL Injection, Spoofed Form Input, Cross-Site Request Forgery, File Uploads, Including Files, Register Globals, Magic Quotes… He is trying to keep it up to date, so please support him if you can.

UPDATED 2.7.2006. – Here are some examples (PHP Security by Example).

]]>
https://www.nivas.hr/blog/2006/06/20/php-security-never-trust-user-input/feed/ 0