Tag-Archive for ◊ PHP ◊

Author:
Thursday, March 24th, 2011

Following is the code for sorting two dimensional array by given key.

<?php
$arr = array();
$arr[0]['id'] = 1;
$arr[0]['name'] = 'sathish';
$arr[0]['role'] = 1000;
$arr[1]['id'] = 2;
$arr[1]['name'] = 'siyam';
$arr[1]['role'] = 200;
$arr[2]['id'] = 3;
$arr[2]['name'] = 'prabhu';
$arr[2]['role'] = 1234;
$arr[3]['id'] = 4;
$arr[3]['name'] = 'hawai';
$arr[3]['role'] = 111;
$arr[4]['id'] = 5;
$arr[4]['name'] = 'dean';
$arr[4]['role'] = 999;
$result = sortTwoDimensionArrayByKey($arr,'name');
echo "<pre>";
print_r($result);
echo "</pre>";
function sortTwoDimensionArrayByKey($arr, $arrKey, $sortOrder=SORT_ASC){
foreach ($arr as $key => $row){
$key_arr[$key] = $row[$arrKey];
}
array_multisort($key_arr, $sortOrder, $arr);
return $arr;
}
?>

This will output:

Array
(
[0] => Array
(
[id] => 5
[name] => dean
[role] => 999
)
[1] => Array
(
[id] => 4
[name] => hawai
[role] => 111
)
[2] => Array
(
[id] => 3
[name] => prabhu
[role] => 1234
)
[3] => Array
(
[id] => 1
[name] => sathish
[role] => 1000
)
[4] => Array
(
[id] => 2
[name] => siyam
[role] => 200
)
)

Category: PHP | Tags: ,  | 2 Comments
Author:
Wednesday, February 24th, 2010

Hi Guys, I am expecting more comments from you (as a reader, as a PHP developer, or any other technology person). I have listed few misconceptions about PHP which I am aware of, you guys can add in more comments to this. I saw in many blogs, programmers are getting into arguement pointing out their technology is the best and other technologies are bad,which should not happen. If you know something which can’t be handled using PHP or which is handled properly in PHP, please post as a comment, we will discuss futher over that.

1. PHP is slow, since it is not a compiled language

PHP became a compiled language in the year 2000, when PHP 4 was released for the first time. Until version 3, PHP source code was parsed and executed right away by the PHP interpreter.

PHP 4 introduced the Zend engine. This engine splits the processing of PHP code into several phases. The first phase parses PHP source code and generates a binary representation of the PHP code known as Zend opcodes. Opcodes are sets of instructions similar to Java bytecodes. These opcodes are stored in memory. The second phase of Zend engine processing consists in executing the generated opcodes.

The Zend engine was built in such way that right after the first phase, the opcodes may be stored in the server shared memory space. This is done by special PHP extensions known as opcode caching extensions. There are several PHP caching extensions also known as PHP accelerator extensions.

Solution: Install a PHP accelerator which will skip the initial compilation step if a PHP script was previously compiled and stored in shared memory.

2. PHP is a Weakly typed language. Leads to more bugs and bad code.

Ya I do accept this. PHP has given this option for the ease of learning. But most of the times it leads to bad code.

Solution: As a Good PHP developer, while working in development environment just make error_reporting=E_ALL

E_ALL includes E_STRICT also, it will provide us run-time notices, suggest changes to your code which will ensure the best interoperability

3. PHP won’t support ORM

Many open source ORM’s are available for PHP and which are best too.

1. Doctrine

2. Propel

These ORM’s are inbuilt inside most of the MVC frameworks like Symfony, Zend, CakePHP, etc

Solution:

Use a proper ORM in your projects, it will reduce lot of complexity related to DB.

4. PHP always mingle with MySQL

Its not, since PHP & MySQL are open source technologies, most of the users are going for this combination

PHP supports various DBs (dBase, DB++, FrontBase, filePro, Firebird/InterBase, Informix, IBM DB2, Ingres, MaxDB, Mongo, mSQL, Mssql, MySQL, Mysqli, Mysqlnd, Oracle OCI8, Ovrimos SQL, Paradox, PostgreSQL, SQLite, SQLite3, Sybase, tokyo_ tyrant)

5. The mixture of PHP code with HTML markup tends to make code difficult to read

Ya its absolutely true. It again depends on developers. PHP allows you to write structured code as well as OOPS like C++. So its our responsibility to choose the best.

Solution:

Use a good MVC framework for your project which reduces developer’s burden as well. It reduces the cycle and recoding. Many MVC frameworks are available like Symfony, Zend, CakePHP, CodeIgnitor. Get a best framework which satisfy your purpose (http://www.phpframeworks.com/). Initially it will be difficult to move to MVC, but once you started it, you won’t move back to your traditional (structured) way of coding.

6. PHP won’t support Webservices

PHP gives full support to webservices. It has inbuilt support for webservices like SOAP, XML-RPC, OAuth, SCA.

7. PHP codes are not unit tested by developers

Ya, this is also true most of time but not always. Its because of developer and client. Most of the clients expect fast delivery, speed development while using PHP. So developers are not getting time to unit test, this is the major reason according to me. But PHP supports Unit test through PHPUnit.

8. Not matured applications are developed using PHP

Hmmmmm…. If we see in general, most of the companies are giving a second thought to jump into PHP for bigger applications. But PHP powers some of the most popular Web sites in the world, such as Yahoo!, Lufthansa, Wikipedia and Disney Online. Facebook is currently the busiest site in the world that is developed mostly in PHP.

Author:
Tuesday, February 23rd, 2010

Steps for setting up error reporting in Symfony

You can set up the Error Reporting Level, in myapp/config/settings.yml

prod:

.settings:

error_reporting:  257

dev:

.settings:

error_reporting:  4095

4095 is a shortcut for E_ALL | E_STRICT

257 stands for E_ERROR | E_USER_ERROR (the default value for every new environment)

Symfony can log a lot of custom events. You can find all the symfony logs under the myproject/log/ directory

There are eight levels of symfony log messages: emerg, alert, crit, err, warning, notice, info, and debug. You can configure the maximum level to be logged in each environment in the logging.yml

Default Logging Configuration, in myapp/config/logging.yml

prod:
  enabled: off
  level:   err
  rotate:  on
  purge:   off
 dev:
 test:
 #all:
#  enabled:  on
#  level:    debug
#  rotate:   off
#  period:   7
#  history:  10
#  purge:    on

You can manually add a message in the symfony log file from your code by using one of the techniques described below

// From an action
$this->logMessage($message, $level);
// From a template
<?php use_helper('Debug') ?>
<?php log_message($message, $level) ?>

For clearing the log use the below command.

symfony log-purge
Category: PHP, Symfony | Tags: , ,  | One Comment
Author:
Friday, January 29th, 2010

While working on symfony framework we faced some issues and in this blog I am going to discuss about the issues and fixes for that issues.

Problem 1 :

symfony 1.2 propel-build-model Bus error

(Crashes PHP CLI when we try to execute

symfony propel-build-model or

symfony propel-build-all

)
Solution :

Execute €˜symfony propel-build-model’ ends with ‘Bus error’

I found this is caused by one field type in db with default value:

I have a column called €˜created_at’of type: timestamp with default value ‘CURRENT_TIMESTAMP’, this is on MYSQL level.

Execute €˜propel-build-schema’ at symfony command line

you will get

created_at: { type: TIMESTAMP, required: true, defaultValue: CURRENT_TIMESTAMP } then, run ‘propel-build-model’, you would get ‘Bus error’

propel generator might not know ‘CURRENT_TIMESTAMP’. After removing this from scheme.yml, you can run that script smoothly.

Problem 2 :

When we tried to host the symfony project which we developed to Linux server, it displayed blank page.

Solution :

It’s because of the case sensitivity of filenames.

Ex: we have a file Test.php, in windows if we include test.php it will work but in Linux it will fail because of case sensitivity.

Author:
Monday, November 02nd, 2009

The usual security stuffs PHP developers handle are
1. Encryption / decryption
2. Validating the User with session Login

Since PHP is to develop web applications, the major secjurity issues with web applications are
1. Cross Site Scripting
2. SQL Injection
3. Trusting User Input
4. Check the referrer

These are the 4 major secutity issues we need to handle in our PHP scripts

1. Cross Site Scripting Prevention

Most of the developers won’t validate the incoming data like querystring and post data.As a result this leads to stealing of cookie or redirecting to different site, etc€¦ For eg, A user will post comment in a blog with a code €œNice Post <img src=€http://site.com/images/myimage.gif€ onload=€window.location=’http://mysite.com/’€ />

This results in redirection of site to €œhttp://mysite.com/€, whenever a user visits the blog.

To prevent from XSS attacks in PHP
Check and validate properly all user inputted data that you plan on using and dont allow html or javascript

code to be inserted from form.

you can Use htmlspecialchars() to convert HTML characters into HTML entities

you can use strip_tags() to only allow some tags

2. SQL Injection Prevention
For eg:

<?php

$firstname = €œJulien’); DELETE FROM mytable; INSERT INTO mytable (firstname) VALUES (’hacked€;

$sql = €œINSERT INTO mytable (firstname) VALUES (’$firstname’)€;

//€¦running the $sql query

?>

To Prevent in PHP

i. Use the addslashes() function which will escape both single and double quotes, by adding backslashes before them, to prevent multiple queries from being executed.

ii. Validate the data with the length of the input field. For eg:

<?php

//escape trouble characters
$firstname = addslashes(firstname);

//make sure not longer than expected length
$firstname = substr($firstname, 0, 32);

$sql = €œINSERT INTO mytable (firstname) VALUES (’$firstname’)€;

//€¦run the $sql query

?>

3. Check the referer: Check to make sure that the information being sent to your script is from your website and not from an outside source. While this information can be faked, it’s still a good idea to check.

For eg: If you have a Login form in your website with username and password textbox. There may be some other hacker who can create same type of form and can use form action to your website. To prevent this type of attack, we can get the referer using $_SERVER['HTTP_REFERER'] and validate before processing.

4. Don’t trust user input anytime. Don’t include, require, or otherwise open/delete a file with a filename based on user input, without thoroughly checking it first.

€œThe better way to reduce programming effort with better security is using a good framework to develop the project.

For eg: Symfony, CakePHP, Zend Framework, etc all these frameworks provides good solution for all the major security issues which we face and also you can maintain the standard in your code and deliverables.€

Author:
Thursday, October 01st, 2009

When we think of Open Source Software, the first software which comes into mind under web category is PHP. We have solution for most of the common issues like Contant Management, Customer relationship management, Project Management etc…

Many companies completely depend on PHP opensource tools. PHP make us to think why we need to €œreinvent the wheel€. I am listing out the list of open source softwares which are very useful.

These are some of the softwares which I know, still lot of open source projects available in PHP. Why can’t you guys get it and use it with less efforts?

Category: PHP | Tags: , , , , , ,  | 11 Comments
Author:
Tuesday, September 01st, 2009

I have developed a graphical solution for our prestigious client. Graphical solution includes generating Bar chart, Pie chart, line chart, Stacked bar chart, Multiple bar chart. I have done a simple search to get the list of open source applications which is available in market to provide the Chart solution.

I have got a list of opensource PHP Charts

1. JPGraph
2. GraPHPite
3. Open Flash Chart
etc…

We had chosen JPGraph since it has most of the chart types. But on the next day, I got to know its not completely open source, for commercial purpose we need to get license.

I started searching for some solution which is provided by PHP.

I got a fantastic PEAR package, “Image_Graph”.

PHP professionals knows what is PEAR (PHP Extension and Application Repository). Its is a framework and distribution system for reusable PHP components.

We can handle most of the charts using Image_Graph. Some of them are

Bar Chart, Pie Chart, Line Chart, Donut Chart, Step Chart, Logarithmic Charts, Area Chart, CandleStick Chart, rador Chart, Impulse Chart, Dot Chart, Band Chart and BoxWhisker charts with stacked and gradient effects. Its a cool package.

Click here to have a look at the list of graphs

Requirements need to check before starting with Image_Graph

1. Your PHP should support Graphics, for that you need to install and enable GD Library.

Click here to get more details about GD Library

2. Your PHP version on server should me more than 4.3.0, suggested to keep PHP 5

3. You need to have the following PEAR packages in your server.

i. Image_Canvas-0.3.1
[Linux Command to install : pear install Image_Canvas-0.3.1 ]

ii. Image_Color-1.0.3
[Linux Command to install: sudo pear install Image_Color-1.0.3]

If you have done with all the above stuffs, you are ready to install Image_Graph PEAR Package.

Linux Command: pear install Image_Graph-0.7.2

For Manual installation Download the Image_Graph and move it to the PEAR path.

Try Examples in Local:

1. Download Image_Graph Package
2. Unzip the package
3. Move the unzipped folder to the web root of your Apache [either www / htdocs].
4. You can access the examples using url : http://localhost/Image_Graph/docs/examples/

By exploring the examples, you will get to know the various way of implementation. Its very simple if you know the basics of PHP.

Issues Which I faced during production upload:

The problems which I faced are

1. Missing of Fonts:

I got a warning like “Warning: imagettfbbox(): Could not find/open font in /usr/share/php/Image/Canvas/GD.php on line 1245

Solution:
This occurs if you don’t have the correct (or any) fonts in your Fonts directory, found at php/Image/Canvas/Fonts/. Make sure that you have the corresponding .ttf file located in your Fonts directory

2. Issues with Legends for Pie/Donut charts

I got one more issue, that legends are not shown for Pie/Donut Charts. Refer: http://pear.veggerby.dk/samples/show/id/gradient_pie/

I searched for solutions. Finally the issue is with Image_Graph PEAR Package. They have included 2 lines which caused the problem. I didn’t analyse the functioanlity of the 2 lines. But the solution is simple, comment that two lines in the installed package.

Solution:

1. You need to find the PEAR package’s include path.

2. By checking the phpinfo using method [phpinfo( )], you can get the path “include_pathPHPinfo

3. In file /usr/share/php/Image/Graph/Plot/Pie.php, comment the following lines
Line 502: // $this->_clip(true);
Line 616: // $this->_clip(false);

I hope this will defenitely help peoples who is going for “Image_Graph” PEAR Package. Enjoy coding :)

Author:
Tuesday, July 14th, 2009

What is Enterprise Application?
Enterprise Applications are software which provides business logic support functionality for an enterprise, typically in commercial organizations, which aims to improve the enterprise’s productivity and efficiency.

Characteristics of enterprise software:
Characteristics of enterprise software are performance, scalability, and robustness. Enterprise software typically has interfaces to other enterprise software.

Services provided by enterprise software are typically business-oriented tools such as online shopping and online payment processing, interactive product catalogue, automated billing systems, security, content management, CRM, ERP, Business Intelligence, HR Management, Manufacturing, EAI etc.

What is Scalability?
There are a number of different aspects of scalability. It always starts with performance, code maintainability, fault tolerance, and the availability of programming staff.

Why people has negative impression that PHP is only for small scale web-sites?
PHP is a language for the rapid development of dynamic Websites. It also has many features that are friendly to beginning programmers, such as the fact that it doesn’t require variable declarations. However, many of these features can lead a programmer inadvertently to allow security holes to creep into a Web application. The popular security mailing lists teem with notes of flaws identified in PHP applications, but PHP can be as secure as any other language once you understand the basic types of flaws PHP applications tend to exhibit.

PHP is an open source programming language that is widely popular on the web. However because PHP so popular in shared hosting environments, many people have an impression that PHP is only for small scale web-sites. This is patently untrue, and PHP is in use in many large scale web sites such as Yahoo, wikipedia and Lufthansa Online Ticketing for the creation of large web applications such as IMP.

Enterprises want to have specific assurances about a web technology they use in the following areas:

  • performance and fast development
  • reliability and security
  • extensibility – able to use industry standards to communicate with other software systems.
  • scalability – able to add additional servers as the load increases.
  • load balancing – ability to distribute the load so no single server is overloaded
  • high availability – ability to survive failure of server components transparently.

Conclusion:
To achieve high performance and scalability – it not only depend on language, it also depend on the developers.

I will give my next article about How to make our PHP code excellent.