Friday, 11 January 2019

PHP: PHP Code optimization techniques

If a method can be static, declare it static. 
Speed improvement is by a factor of 4

1. echo is better than print
echo( 'CHECKMATE: PLAY with PROBLEMS' );
// is better than
print( 'CHECKMATE: PLAY with PROBLEMS' );

2. Use echo' s multiple parameters instead of string concatenation
echo 'PLAY', 'WITH', 'PROBLEMS';
// is better than
echo 'PLAY' . 'WITH' . 'PROBLEMS';

3. Surrounding your string by ' instead of " will make things interpret a little faster since PHP looks 
for variables inside "..." but not inside '…'.
Of course you can only do this when you don’t need to have variables in the string.

echo 'a string ' . $name;
// is better than
echo "a string $name";

4. Use functions outside of loop. Otherwise function gets called each time.
$max = count( $array );
for( $i = 0; $i < $max; $i++ ){
// do something
}
// is better than
for( $i = 0; $i < count( $array ); $i++ ){
// do something
}

5. Unset your variables to free memory, especially large arrays.
6. Avoid magic functions like __get, __set, __autoload
7. require_once() is expensive
8. Use full paths in includes and requires, less time spent on resolving the OS paths.
include( '/var/www/html/your_app/test.php' );
//is better than
include( 'test.php' );

9. If you need to find out the time when the script started executing, $_SERVER['REQUEST_TIME'] is preferred to time()
10. See if you can use strncasecmp, strpbrk and stripos instead of regex
11. str_replace is better than preg_replace, but strtr is better than str_replace by a factor of 4
12. If the function, such as string replacement function, accepts both arrays and single characters as arguments, 
and if your argument list is not too long, consider writing a fewredundant replacement statements, 
passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
13. It’s better to use switch statements than multi if, else if statements.
switch( $name ){
case 'saiful':
// do something
break;
case 'ekram':
// do something
break;
case 'arif':
// do something
break;
default:
// do something
break;
}
// is better than
if( $name == 'saiful' ){
// do something
}
else if( $name == 'ekram' ){
// do something
}
else if( $name == 'arif' ){
// do something
}else{
// do something
}
14. Error suppression with @ is very slow.
$name = isset( $id ) : 'saiful' : NULL;
//is better than
$name = @'saiful';
15. $row['id'] is 7 times faster than $row[id]
16. Error messages are expensive
17. Close your database connections when you're done with them
18. Incrementing a local variable in a method is the fastest. Nearly the 
same as calling a local variable in a function.
19. Incrementing a global variable is 2 times slower than a local variable.
20. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
21. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
22. Just declaring a global variable without using it in a function also 
slows things down(by about the same amount as incrementing a local var). 
PHP probably does a check to see if the global exists.
23. Methods in derived classes run faster than ones defined in thebase class.
24. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. 
A similar method call is of course about 15 $localvar++ operations.
25. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. 
Try to use more static HTML pages and fewer scripts.
26. Your PHP scripts are recompiled every time unless the scripts are cached. 
Install a PHP caching product to typically increase performance by 25-100% by removing compile times. 
OP code caches are useful so that your script does not have to be compiled on every request
27. When working with strings and you need to check that the string is either of a certain 
length you'd understandably would want to use the strlen() function. 
This function is pretty quick since it’s operation does not perform any calculation 
but merely return the already known length of a string available in the 
zval structure (internal C struct used to store variables in PHP). 
However because strlen() is a function it is still somewhat slow because the function call 
requires several operations such as lowercase & hashtable lookup followed by the execution of said function. 
In some instance you can improve the speed of your code by using an isset() trick.

if( strlen( $name ) < 5 ){
echo "Name is too short";
}
// is better than
if( !isset( $name{5} ) ){
echo "Name is too short";
28. When incrementing or decrementing the value of the variable$i++ happens to be a tad slower then ++$i. 
This is something PHP specific and does not apply to other languages, 
so don’t go modifying your C or Java code thinking it’ll suddenly become faster, it won’t. 
++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. 
Post incrementation actually causes in the creation of a temporary var that is then incremented. 
While pre-incrementation increases the original value directly. This is one of the optimization 
that opcode optimized like Zend’s PHP optimizer. It is a still a good idea to keep in mind since 
not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running 
without an opcode optimizer.

29. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
30. Do not implement every data structure as a class, arraysare useful, too
31. Don’t split methods too much, think, which code you will really re-use
32. Make use of the countless predefined functions
33. If you have very time consuming functions in your code, consider writing them as C extensions
34. Profile your code. A profiler shows you, which parts of your code consumes how many time.
35. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%
36. Use ; tags when declaring PHP as all other styles are depreciated, including short tags.
37. Never trust variables coming from users (such as from $_POST) use mysql_real_escape_string when using MySQL, and htmlspecialchars when outputting as HTML
//a safe query
$_user      = mysql_real_escape_string( $user );
$_password  = mysql_real_escape_string( md5( $password ) );
$query      = sprintf( "SELECT * FROM user_info WHERE user='%s' AND password='%s'", $_user, $_password ); 
//safe output 
echo htmlspecialchars( "<a href='test'>Test</a>", ENT_QUOTES );
//output: <a href='test'>Test</a>
38. Avoid using plain text when storing and evaluating passwords. Instead use a hash, such as an md5 hash.
$user_input = 'myPassword';
if( md5( $user_input ) == $md5_password_from_database ){
//login here...
}
39. Avoid the PHP mail() function header injection issue.
40. Unset your database variables (the password at a minimum), you shouldn’t need it after you make the database connection.
41. Use sprintf instead of variables contained in double quotes, it’s about 10x faster.

Tuesday, 8 January 2019

PHP: Xajax and PHP: JavaScript without the pain Automatic for the people

While it shares LAMP honors with Perl and Python, though, PHP has become the most commonly used server-side platforms for Ajax and, of all the Ajax frameworks for PHP, Xajax is the most commonly used. If you are not familiar with JavaScript, which forms the basis of Ajax, but still would like to use Ajax with PHP, Xajax is the obvious choice because Xajax generates the required JavaScript for you.
In this Hands On, I’ll demonstrate a simple way to use Ajax and PHP within Xajax, with an Oracle database, while sidestepping the need for the problematic XMLHttpRequest.

Xajax backrounder

Xajax is an open source, object oriented, PHP class library that can be used with PHP scripts for server-side processing. Xajax is used to communicate asynchronously between a client- and a server-side application comprised of PHP scripts, and generates JavaScript wrapper functions so that PHP functions on the server can be accessed from a client application.
When a client application invokes the wrapper functions, a XMLHttpRequest object is initiated and a XMLHttpRequest object is sent to the server. On the server, the Xajax object receives the XMLHttpRequest and invokes the PHP functions corresponding to the JavaScript wrapper functions.
The default request type of PHP functions registered through Xajax is POST. The PHP functions return an XML response that is returned to the client application by the Xajax object. Based on the instructions in the XML response, the Xajax’s JavaScript message pump updates the content of the client input page. Xajax has a feature that, data is updated only if data has been modified.

Download and go

As Xajax is a PHP class library, first download and install PHP 5 and Apache2 HTTP server as explained in an earlier. The example application shall store and fetch data from Oracle database 10g. Therefore, enable the Oracle database extension in the php.iniconfiguration file.
extension=php_oci8.dll
Create an example database table in OE schema with a PHP script, Table.php, which is available in resources zip. Download Xajax0.2.4/0.2.5. Extract xajax_0.2.4.zip file to the C:/Program Files/Apache Group/Apache2/htdocs directory.

Monday, 7 January 2019

GIT: Dry Run Before Adding to Git Repository

When something goes wrong it is important to test things before you do them so you can avoid things going wrong!
One way to do that in Git is to use the --dry-run flag with git-add.
Let’s say I have a bunch of changes and I just want to check what will happen when I run git-add to stage them for commit. Unstaging a staged change isn’t a big deal but I like to avoid problems (and fixing them!) if I can.
git add . --dry-run

Using this command I’m adding all changed files (the . means everything) but I’m only doing a simulation. When this happens I’ll get a list of files that will be included in the add and staged for the next commit.
A handy tip for the next time you want to see what happens before you do it.

GIT: How to Create Git Aliases

An alias, otherwise known as a shortcut, allows to place a simple command in front of a longer or less memorable command.
For example, we could type:
git commit -m "some change"
Or we could type even less and do:
git c -m "some change"
We’re only saving a few letters but considering how many times you commit in a day or week, it’s a bit easier on your fingers. Less tapping of the keyboard and more working on the fun code.
To create a Git alias, we need to open up our .gitconfig file and edit it. Because we want to have these aliases available to us in every project, we are going to edit the .gitconfig file in our user directory.
If you don’t already have the file in your user directory, that’s okay. We can have Git handle that for us.
We’ll create an alias first using the git-config command, to which we pass the type of config file (in our case it’ll be global in our user home directory) and then define the alias.
git config --global alias.c commit
This will add the following line to our ~/.gitconfig file. Let’s take a look to see if it was saved.
git config --list
This lists out all of our config items and you should see the alias:
c = commit
listed as output.
Now we have access to that alias within Git. We can type:
git c -m "something"
and it will work just as if we typed out the full command.
Let’s open up the config file and take a look. We’ll open ours in Vim, but you can use any editor you want.
vim ~/.gitconfig
You should see something like this:
[alias]
    c = commit
Let’s add another alias by hand without using the git-config command. It’s just a text file so we can edit it and type out our alias by hand.
Let’s add an alias to make it quicker to get the status of our working directory. Under the existing alias for commit, let’s add this:
st = status
We’ll save our .gitignore file and then try it out.
git st
And we should get some output from Git (assuming we’re inside a Git project) as if we ran the full command.
We can add another for git-log, too.
l = log
And how retrieving the basic log is two letters faster than before!
Okay, let’s do one more to quickly archive the entire repository.
Git provides a command called git-archive that allows us to export the entire repository as either a zip for tar archive file.
git archive --format=zip -o latest.zip HEAD 
This command will output the current repository at HEAD to the a zip file named latest.zip. It will save the file right where you are in the repository.
This can come in handy if you have to quickly share your work with someone who is not in the Git repository or if you need to throw the files up on a server somewhere.
To alias this we add this to our .gitconfig file:
zip = git archive --format=zip -o latest.zip HEAD
Now when we run:
git zip
in a valid Git project directory, git-archive will zip up the entire project and place it in the project root.

One Bit of Advice

You don’t have to have a fully decked out .gitconfig file right from the get-go. Add aliases to your config file as it makes sense and as you need them. They can be tough to remember if you add too many at once!

GIT: Understanding Git Log

Git logs allow you to review and read a history of everything that happens to a repository. The history is built using git-log, a simple tool with a ton of options for displaying commit history.

What’s in Log?

A Git log is a running record of commits. A full log has the following pieces:
  • A commit hash (SHA1 40 character checksum of the commits contents). Because it is generated based on the commit contents it is unique.
  • Commit Author metadata: The name and email address of the author of the commit.
  • Commit Date metadata: A date timestamp for the time of the commit
  • Commit title/message: The overview of the commit as written in the commit message.

A Typical Log

Git logs can be whatever you want them to be. Git-log offers dozens and dozens of options but let’s start with the simplest.
git log 
This outputs the most basic log:
commit 98aa8d722bdecc4e56156cfe1a793a4d16848eb8
Author: Ryan Irelan 
Date:   Sat Jan 10 23:26:40 2015 -0600
 
Adding in new homepage
 
Includes the assets needed for Foundation
 
commit dd8d6f587fa24327d5f5afd6fa8c3e604189c8d4
Author: Ryan Irelan 
Date:   Tue Jan 6 20:07:17 2015 -0600
 
added origination declaration at bottom of RSS feed
This is a snippet of the log, showing two commits. We have a commit SHA1 hash, the author, the date, and the commit message, explaining what happened in the commit. This layout is the default look of the log.
Git has something called Commit Limiting to make it easier to narrow down hundreds or thousands of commits to the ones you want to review.

Directory Restricted Log

The default log is great for grabbing a quick look at what just happened in the repository. But it takes up a lot space and you can only see a handful of commits at once.
When I’m developing a project, I sometimes only want to know what happened in a specific directory. Let’s say I’m working on some CSS or Sass and only want to know about changes in my Sass directory. I can get much more specific with git-log and restrict it only to a specific directory.
git log scss
This will only return commits that had changes in the scss directory.

Log by branch

We can use a similar syntax as directory restriction and build a log for just one branch. We only need to specify the branch we want to see.
git log develop
We can clean that up a little by removing any merge commits (which can bulk up the log if there are a lot of merges, like there would be a develop branch.
git log develop --no-merges

Wednesday, 2 January 2019

PHP: Important Points to PHP

  1. If a method can be static, declare it static. Speed improvement is by a factor of 4
  2. echo is better than print

    echo( 'CHECKMATE: PLAY with PROBLEMS' );

    // is better than

    print( 'CHECKMATE: PLAY with PROBLEMS' );
  3. Use echo’s multiple parameters instead of string concatenation

    echo 'PLAY', 'WITH', 'PROBLEMS';

    // is better than

    echo 'PLAY' . 'WITH' . 'PROBLEMS';
  4. Surrounding your string by  instead of  will make things interpret a little faster since PHPlooks for variables inside “…” but not inside ‘…’. Of course you can only do this when you don’t need to have variables in the string.

    echo 'a string ' . $name;

    // is better than

    echo "a string $name";
  5. Use functions outside of loop. Otherwise function gets called each time.
    1$max = count( $array );
    02for( $i = 0; $i < $max; $i++ )
    03{
    04    // do something
    05}
    06
    07// is better than
    08
    09for( $i = 0; $i < count( $array ); $i++ )
    10{
    11    // do something
    12}
  6. Unset your variables to free memory, especially large arrays.
  7. Avoid magic functions like __get, __set, __autoload
  8. require_once() is expensive
  9. Use full paths in includes and requires, less time spent on resolving the OS paths.
    1include( '/var/www/html/your_app/test.php' );
    2//is better than
    3include( 'test.php' );
  10. If you need to find out the time when the script started executing, $_SERVER['REQUEST_TIME'] is preferred to time()
  11. See if you can use strncasecmp, strpbrk and stripos instead of regex
  12. str_replace is better than preg_replace, but strtr is better than str_replace by a factor of 4
  13. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a fewredundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
  14. It’s better to use select statements than multi if, else if statements.
                   switch( $name ){
    case 'saiful':
// do something
    break;
    case 'ekram':
// do something
    break;
    
case 'arif':
// do something
break;

    default:
// do something
    break;
}
// is better than
if( $name == 'saiful' ){
// do something
}else if( $name == 'ekram' ){
// do something
}else if( $name == 'arif' )
{
// do something
}else{
// do something
}
  1. Error suppression with @ is very slow.
    1$name = isset( $id ) : 'saiful' : NULL;
    2//is better than
    3$name = @'saiful';
  2. $row['id'] is 7 times faster than $row[id]
  3. Error messages are expensive
  4. Close your database connections when you’re done with them
  5. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
  6. Incrementing a global variable is 2 times slower than a local variable.
  7. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
  8. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
  9. Just declaring a global variable without using it in a function also slows things down(by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
  10. Methods in derived classes run faster than ones defined in thebase class.
  11. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.
  12. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
  13. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times. OP code caches are useful so that your script does not have to be compiled on every request
  14. When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function. This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.
    01if( strlen( $name ) < 5 )
    02{
    03    echo "Name is too short";
    04}
    05
    06// is better than
    07
    08if( !isset( $name{5} ) )
    09{
    10    echo "Name is too short";
    11}
  15. When incrementing or decrementing the value of the variable$i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don’t go modifying your C or Java code thinking it’ll suddenly become faster, it won’t. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend’s PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
  16. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
  17. Do not implement every data structure as a class, arraysare useful, too
  18. Don’t split methods too much, think, which code you will really re-use
  19. Make use of the countless predefined functions
  20. If you have very time consuming functions in your code, consider writing them as C extensions
  21. Profile your code. A profiler shows you, which parts of your code consumes how many time.
  22. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%
  23. Use ; tags when declaring PHP as all other styles are depreciated, including short tags.
  24. Never trust variables coming from users (such as from $_POST) use mysql_real_escape_string when using MySQL, and htmlspecialchars when outputting as HTML

    //a safe query

    $_user      = mysql_real_escape_string( $user );

    $_password  = mysql_real_escape_string( md5( $password ) );


    $query      = sprintf( "SELECT * FROM user_info WHERE user='%s' AND password='%s'", $_user, $_password ); //safe output echo htmlspecialchars( "<a href='test'>Test</a>", ENT_QUOTES );


    //output: <a href='test'>Test</a>
  25. Avoid using plain text when storing and evaluating passwords. Instead use a hash, such as an md5 hash.
    1$user_input = 'myPassword';
    2if( md5( $user_input ) == $md5_password_from_database )
    3{
    4    //login here...
    5}
  26. Avoid the PHP mail() function header injection issue.
  27. Unset your database variables (the password at a minimum), you shouldn’t need it after you make the database connection.
  28. Use sprintf instead of variables contained in double quotes, it’s about 10x faster.