Posts

Showing posts from 2012

Top 10 articles 2012

Image
Article Published Views Using V8 Javascript engine as a PHP extension Jul 22 8458 Create PDF invoices with HTML5 and PhantomJS Dec 8 2006 How to write a really small and fast controller with PHP Jul 17 1320 MySQL or MySQLi or PDO Jul 21 957 PHP Framework Comparison Oct 19 916 Mass inserts, updates: SQLite vs MySQL Sep 13 585 How to implement really small and fast ORM with PHP Oct 16 524 PHP memory consumption with Arrays and Objects Jun 23 465 For or Foreach? PHP vs. Javascript, C++, Java, HipHop Jun 27 444 How to implement a real-time chat server in PHP using Server-Sent Events Oct 29 386 Views from 6/19/12 to 12/28/12: 23464 Top 5 Country Views United States 4680 Germany 4109 China 1268 United Kingdom 1224 Russia 982

Building PHP extensions with C++, the easy way (update: MySQL, threads)

Image
Here is an easy way to build a PHP extension with C++ and default PHP packages on a Ubuntu system. I use SWIG to wrap C++ code to the Zend API. When using loops and recursion intensively, porting a few functions to C++ can give you some extra power . First, install all required packages (tested with Ubuntu 12.10) : apt-get install php5-cli php5-dev swig g++ Second, write the code: // example.swig %{ #include <iostream> #include <vector> using namespace std; int HelloWorld(char *str) { cout << "Hello World: " << str << endl; // run some slow code vector<int> array; for (int i=0; i < 10000000; i++) array.push_back(i*2); for (int i=0; i < array.size(); i++) array[i]++; return 0; } %} %module example int HelloWorld(char *str); Third, compile the code and load the exension: swig -c++ -php5 example.swig g++ `php-config --includes` -O2 -march=native -mtune=native -std=c++11 -fPIC -c *.cpp g++ -shared *.o -o exa

Fixing ASP.NET application for IE10 compatibility

We've a stable MVC web application. However, recently there was a sprung in issues (mostly JavaScript) breaking many of the existing features. Recently, QA started to test application in IE10 browser after the analytic showing an increased traffic from it (Thanks to a lot of new Windows 8 devices). Where QA was quick enough to log defects one-after-the-another , we as a developer, were a bit panicked. This post is all about fixing your application for IE 10. I'm in progress of fixing my application and will keep posting any new gimmick. (I appreciate if you could share your experiences too) 1st Fix (Master Stroke) Issue: Application working in cookieless mode. I.e. Adding session to URL. For example: upon login (Forms Authentication), http://mysite.com/welcome.aspx, it shows http://mysite.com/welcome.aspx(A(ikRoEoqwOieH_FyADedeEbit-_uDNadHNudahUar-HaUsU99DiasIadsjKAsjJiaojdJaJadijAQBR0))/Welcome.aspx The first fix I did, was with minutest change but fixed more than 80% issues i

Create PDF invoices with HTML5 and PhantomJS

Image
Creating invoices in PDF is always a bit tricky: there are many libraries to create PDF documents with PHP, but most can't handle complex layouts and require a lot of memory and CPU time. Things like Unicode characters and line/page breaks are often difficult to program and the source of many bugs and memory problems. Using logos as vector graphics or embedding TrueType fonts is often required, but not possible with most libraries. The good thing is that all these features are included in HTML5. Since most companies offer their invoices also in HTML, it would be great to convert them directly to PDF. Tools like html2ps and ps2pdf can produce PDFs with 200+ pages without problems, but only support HTML4 and some very limited CSS. Also, the layout is never the same as in a web browser. So we need a real web browser to convert HTML pages to PDFs. From testing web applications, we know that PhantomJS is a headless WebKit browser that runs on the commandline and can automate things

Exporting events to google calendar Link HtmlHelper

Following is a ASP.NET MVC HtmlHelper to generate an anchor link for exporting an event to Google Calendar. public static MvcHtmlString ExportEventToGoogleLink(this HtmlHelper htmlHelper, string title, DateTime startDateTime, DateTime endDateTime, string description, string location, string linkText, IDictionary<string, object> htmlAttributes = null) { const string dateFormat = "yyyyMMddTHHmmssZ"; Uri url = System.Web.HttpContext.Current.Request.Url; StringBuilder sb = new StringBuilder(); sb.Append("http://www.google.com/calendar/event?action=TEMPLATE"); sb.Append("&text=" + title); sb.Append("&dates=" + startDateTime.ToUniversalTime().ToString(dateFormat)); sb.Append("/"); sb.Append(endDateTime.ToUniversalTime().ToString(dateFormat)); sb.Append("&details=" + description); sb.Appe

Shrink qcow2 file with Windows guest

Remove unnecessary file and empty the recycle bin in windows guest. De-fragment your disk in windows guest. You may do it several times for good compact status. Free unused disk space in windows guest. sdelete -c c: Convert the disk image itself. qemu-img convert -c -O qcow2 win.qcow2 win-shrinked.qcow2

The power of column stores

using column stores instead of row based stores can reduce access logs from 10 GB to 130 MB of disk space reading compressed log files is 4 times faster than reading uncompressed files from hard disk column stores can speed up analytical queries by a factor of 18-58 Normally, log files from a web server are stored in a single file. For archiving, log files get compressed with gzip. A typical line in a log file represents one request and looks like this: 173.15.3.XXX - - [30/May/2012:00:37:35 +0200] "GET /cms/ext/files/Sgs01Thumbs/sgs_pmwiki2.jpg HTTP/1.1" 200 14241 "http://www.simple-groupware.de/cms/ManualPrint" "Mozilla/5.0 (Windows NT 5.1; rv:12.0) Gecko/20100101 Firefox/12.0" Compression speeds up reading the log file: $start = microtime(true); $fp = gzopen("httpd.log.gz", "r"); while (!gzeof($fp)) gzread($fp, 8192); gzclose($fp); echo (microtime(true)-$start)."s\n"; // 26s $start = microtime(true); $fp = fopen("

Runtime vs. memory usage

Oftentimes, better runtime can result in higher memory usage. Here is an example to create some strings to test bulk inserts on Redis: $cmd = ""; $start = microtime(true); for ($i=0; $i<1000000; $i+=2) $cmd .= "SET entity:".$i.":key value_".($i+1)."\r\n"; echo number_format(microtime(true)-$start, 1)."s\n"; // 0.7s echo number_format(memory_get_usage(true)/1048576, 1)." MB\n"; // 17.5 MB echo number_format(memory_get_peak_usage(true)/1048576, 1)." MB\n"; // 17.5 MB $cmd = ""; $start = microtime(true); $cmd = vsprintf(str_repeat("SET entity:%d:key value_%d\r\n", 500000), range(0,1000000)); echo number_format(microtime(true)-$start, 1)."s\n"; // 0.4s echo number_format(memory_get_usage(true)/1048576, 1)." MB\n"; // 30.8 MB echo number_format(memory_get_peak_usage(true)/1048576, 1)." MB\n"; // 128.5 MB (PHP 5.4.5, 2.5 GHz, win64) We see that the same result can be c

Developers's time of permanency is 15 years?

Image
This article is not about performance of PHP, but more about performance of developers in general. A nice article from golem.de claims that the developers's time of permanency is - exactly - 15 years. The main facts of the article: developers have abrasion like professional athletes No: Developers don't require fast running, much muscle power or intensive training. Of course, getting older does not mean getting healthier, but health care improves every year and people are getting older and older. The key success factors are more talent and motivation than age. Also, older athletes produce more money with marketing than younger ones. developers at the age of 20 bring more money than older developers Yes, if the business is selling developers by hour/day and quality (number of bugs, wrong architecture decisions, usability, performance) does not matter. Young developers without a final degree and without working experience normally have lower salaries. No in all other case

A three-line guestbook in PHP

Below you can see a short script that causes to write somthing you enter a form to a file. Each entry is appended in new line. <form method=post><input name=a><input type=submit></form> <?php if($_POST['a'])file_put_contents('z.txt',$_POST['a']."\n",FILE_APPEND);

Error while enabling windows feature NetFx3

Image
Recently, I tried to install SQL 2012 express edition on a Windows 8 OS running inside VMware. Installation wizard is very much the same as SQL 2008, so I thought it's going to be pretty smooth. With several Next  clicks, my installation process started. BUT :( it got aborted with following error: The following error has occurred: Error while enabling windows feature : NetFx3, Error Code : -2146498298. Reason: ========================================================= Installation process requires .NET framework 3.5, which is generally not installed along with windows. However, it is available in Turn Windows Features On/Off option. Most likely this will be unchecked if you are getting NetFx3 installation error. You'd be tempted to quickly check and try install this component. It shows 2 options - Install from a disc or install from internet. If you try later option, it will fail (I don't know reason but you'd see a generic error message). Check following resolution for

Free php pdf tutorial

Image
People are searching for free php pdf tutorials because they want to learn php from home without having internet connection. This way is very efficient to develop one's skill in php. So that people's are looking for free php pdf tutorials in the internet but they don't able to find php pdf tutorials because most of the php pdf tutorials are not free. To give you some help in our php tutorial blog we provide you all php tutorials and resources without any costs. You can download our php pdf tutorials free from our website. We try to provide you php tutorials in pdf format and also in step by step manner. We divided our whole tutorials into three parts such as php pdf tutorials for beginners, advanced php pdf tutorials and object-oriented php pdf tutorials. Here we give you some brief about our all php pdf tutorials.  PHP PDF TUTORIALS FOR BEGINNERS In this section you can easily download our php beginning pdf tutorials . So let me show you the contents of our beginning l

PHP beginners pdf tutorials free download

In this PHP tutorial section we are trying to provide you All pdf php tutorial for that you can learn PHP from home. This php pdf tutorials are free for all. Just download our PHP tutorial from media-fire link. Sometimes you feel bored or you are not get in touch with internet at this time you can open our pdf php tutorials and easily learn php without having internet.  Free PHP pdf tutorial:  We devided our whole pdf tutorial into three parts. In this part we will provide you beginners php PDF tutorials with media-fire link. So lets start and download our PHP pdf beginners tutorial. Here is the list of our beginners php tutorials.  Starting with PHP web development.pdf PHP intallation.pdf ZAMPP installation.pdf Vertrigo server installation.pdf What is PHP.pdf Writing your first php script.pdf PHP variable.pdf PHP comments.pdf PHP operators index.pdf PHP arithmetic operator.pdf PHP assignment operator.pdf PHP comparison operator.pdf PHP increment and decrement operators.pdf PHP cont

PHP increment and decrement operators

In PHP the ++ and the -- sign are increment and decrement operators. Increment means increase and decrement means decrease that means increment operator increase the variable value and decrement operator decrease the variable value. The PHP increment operator increases it's variable value by one and the PHP decrement operator decreases it's variable value by one . Suppose that we have a variable $x. We want to increase it's value one. Consider the statement below  $x=10 but we want to increase it's value one so that the new form is  $x=$x+1 We can rewrite this by using PHP increment operator :  $x++; Similarly in PHP decrement operator we can write $x--;  Each PHP increment and decrement operators has two types:  (++$x) Pre-increment : It first increment $x value one and then return the value of $X. ($x++) Post-increment : It first return $x value and then increment the value of $x. (--$x) Pre-decrement : It first decrement $x value one and then return the value of $x

PHP comparison operators

PHP comparison operator means using PHP operators compare two things or two variable . Suppose that we have two variable $a=10 and $b=20. We have to know which variable is small or big. In that case we use comparison operators. Different types of PHP comparison operators are given below ( == ) Equal : It returns true if $a and $b is same.  ( != ) Not Equal : It returns true if $a and $b is not same.  ( === ) Identical : It returns true when $a and $b is same and same type.  ( !== ) Not Identical : It returns true when $a and $b is not same and same type. ( < ) Less than : Returns true if ($a<$b) $a is less than $b.  ( > ) Greater than : Returns true if ($a<$b) $a is greater than $b.   PHP comparison operators first check the condition then return true or false. If true then execute the program otherwise not execute the program. Now take a look at the example below <pre class=”brush: php;”> <? php $a = 10 ; $b = 20 ; $c = 10 ; echo ( $a == $c ); echo "<br

Applying Scrum to legacy code and maintenance tasks

There are some problems with Scrum that mainly occur when dealing with third party components or legacy systems: wrong estimations (time, impact, risk, complexity) bad requirements (inconsistent, incomplete, testable, conflicting, faulty) development involved in operations (bug analysis, data correction, deployment, hot-fixes) delays in development (bugs in legacy system, missing documentation) testing (quality/quantity of test cases, un-mockable interfaces, long running offline processes, performance issues, live and test system differ) General problems with Scrum: development (gold plating, rework, misunderstandings and bugs from collective code ownership) estimations (missing experience, excessive estimations for unpleasant stories) technical debt vs. velocity (architecture violations save deadlines) performance (stories are functional requirements, performance is normally no acceptance criteria, often only specified as "system should be fast and responsive") testing (t

PHP assignment operators

PHP assignment operators are used to assign value in a variable such that we can assign value 10 in a variable $a like that $a=10. Now the value of $a is 10 because we assign 10 in variable a. equal (=) sign is used to represent PHP assignment operator but in array we use => sign to assign value. Now take a look at an example of PHP assignment operators. <?php $a = 20; echo $a; ?> Save and run the above code. We can use PHP arithmetic operator in PHP assignment operator. Here is an example: <?php $a=10; $a+=10; echo $a; ?>

PHP arithmetic operators

When you were start your first math learning, I am sure you have used + sign, - sign, * and / sign. These sign are used in PHP as a arithmetic operator. Different kinds of PHP arithmetic operators are + operator, - operator, * multiply operator, / division operator, % modulus operator. Here we describe its clearly. (+) Addition Operator: Using this operator we can add two value such that $a + $b or 12+15=27. (-) Subtraction Operator: Using this operator we can subtract two value such that $a - $b. (*) Multiply Operator: We call * sign is multiply operator in PHP. Multiply operator is used for multiplication such that 12*2=24. (/) Division Operator: To find quotient we use PHP division operator. For an example, 12/2=6. (%) Modulus Operator: We find remainder from two variable we use PHP modulus operator. For an example, 12%2=0. PHP Arithmetic Operator Example:   Let's try an example where we have used all PHP arithmetic operators. <?php echo (2+8); // Addition echo "<

PHP Operators Index

PHP operators are used to compare two values. It is an expression that takes one or more values and produce another value such that $a+$b where + sign is an operator and a, b are two variable. PHP operators are two types:  Unary Operator and Binary Operator Unary Operator: Unary means one. PHP unary operator can take only one value, for an example ++,-- operator. We use ++ operator to increment value and -- operator to decrement value.  Binary Operator: Binary operator can take two value such that + operator, - operator etc. For an example, $a+$b. Some PHP operators are plus + operator, minus - operator, * multiply operator, / divide operator and so on. We can divide all PHP operators into different types. Before entering the dept of our PHP tutorial we need to understand each operator clearly. Here is the lists of all PHP operator. PHP Operators Index: Arithmetic Operators Assignment Operators Comparison Operators Bitwise Operators Incrementing Operators Decrementing Operators Log

How to implement a real-time chat server in PHP using Server-Sent Events (update: added C benchmark)

Lessons learned: A web server written in PHP can give more than 10000 req/s on small hardware A web server written in PHP is not slower than being written in Java (without threads) A web server written in PHP is 30 percent slower than being written in C (without threads) Realtime applications can be developed in PHP without problems PHP normally runs inside a web server like Apache or nginx. This keeps all requests separate from each other and does not allow sharing memory or connections. To implement a chat server, the browser has to poll the server regularly for new data. The data is stored in a database and looked up for each request. This is very slow, takes a lot of resources on the server and does not give messages in realtime. Newer browsers support data being pushed from the server to the client. There are two techniques used: WebSockets (full-duplex) and Server-Sent Events (push notifications) Using these techniques, one connection stays open for each client and the server

How to write JavaScript in MVC style

Image
Intent ============================================================================== This tutorial explains a way to implement MVC (Model View Controller) pattern in client script using pure JavaScript . Idea is to highlight basic fundamentals of implementing MVC in client code. If you grab these basics, you can easily create advance implementations with lesser code using various libraries like JQuery and Knockout etc. Quick brush up on MVC Instead of getting theoretical, I'll put it this way: View : These are the HTML elements in your UI - TextBoxes, HiddenBoxes, Images, Tables etc. For example, in Google home page, view elements includes Search TextBox, Search Button, Search result div container, Suggestions display div container etc. Model :  Model represents data which drives functionality of screen. It may or may not have 1:1 mapping with your view elements. For example, in Google search page, model may contain an array of autoSuggest words or an array of search results in J

How to write JavaScript functions in different styles

INTENT ================================================================= This article is to explore different ways to write JavaScript functions. All example below are in context of plain JavaScript and do not depend on any library like JQuery (which might come as a surprise to few :) Level: Beginners Original Basic implementation.. Declare a method and call at some point later function SayHello(msg) { alert(msg); } //call explicitly SayHello('my name is'); //alerts "my name is" Different style where function is assigned to a variable and then called later var SayHello = function(name) { alert(name); }; SayHello('Deepak'); NOTE: Check the ; at end of function (i.e. after }) . This was not required in previous example because we declared a method. However, now we are assigning a function to a variable just like we say var i = 10; If you miss this ';', function would still execute properly but many IDE's may complain th

Convert Debian amd64 to multi-arch

Do following steps... sudo dpkg --add-architecture i386 sudo sed -i 's/deb\ /deb\ [arch=amd64,i386]\ /g' /etc/apt/sources.list sudo apt-get clean; sudo apt-get autoclean; sudo apt-get update After that you can install the packages that only support i386 such like skype. Enjoy it!

PHP Framework Comparison (update: opcode caching)

Image
Reading about PHP frameworks, you'll get a lot about Symfony and Zend Framework. It is true that these frameworks have a lot of features and do great marketing. But what about performance and scalability? There are 2 kinds of frameworks: those written in C as an extension and those written in PHP Using a framework written in C will definitively give the best performance. But fixing (security) bugs and maintaining them requires C knowledge. If the documentation is not complete or incorrect, you might need to read the code to understand the functionality or wait for the maintainer to help you. So if you don't need super high performance, my recommendation is using a framework written in PHP. Here is a test from Laruence (PHP core developer): higher numbers are better, source Here is another test from Zeev Suraski (Zend/PHP core developer): higher numbers are better, source Here is another excellent test from Wang Rui: smaller numbers are better, source (with call graphs, respon