个人以为文章部分观点有一定偏差,但是依然能让人清晰的看到PHP和ASP.NET各自的优劣。
![Sean Hull](http://www.oracle.com/technology/pub/columns/images/shull.jpg)
PHP and ASP.NET Go Head-to-Head
By Sean Hull
One developer's view of the pros and cons of the two most popular means of building web applications
When it comes to Web development these days, you have a lot of options. Many of these methods involve preprocessing—that is, embedding code into HTML pages with special tags that signal to a preprocessor that they contain code, and that it should do something with it. Much like a CGI, this code is then run on the server, and it returns some content, which then assumes part of the shape of the resulting HTML page sent back to the browser. Both the open source scripting language PHP and languages within Microsoft's ASP.NET framework fall into this category; JavaServer Pages (JSP) and Perl/Mason operate this way as well.
In this article I'll focus on PHP, the technology Oracle has chosen to incorporate into its products, and ASP.NET. I'll overview the various strengths and weaknesses of each, discussing in particular those areas that will help you make your decision on which to go with for your development project. There are a lot of factors to consider, and different projects may appeal to a different technology. In conclusion you'll find a point-by-point comparison in terms of price, speed and efficiency, security, cross-platform support, and the advantages of an open source solution.
What is ASP.NET?
The latest incarnation of ASP, ASP.NET, is not completely backward-compatible with previous versions of ASP, as it is a complete rewrite of the software. Previous ASP technology actually has a lot more in common with PHP than with ASP.NET, which is a complete framework for building Web applications. One of the principal features of this model is the flexibility to choose your programming language. ASP.NET works with scripted languages such as VBScript, JScript, Perlscript, and Python, as well as compiled languages such as VB, C#, C, Cobol, Smalltalk, and Lisp. The new framework uses the common language runtime (CLR); your language source is compiled into Microsoft Intermediate Language code, which the CLR then executes.
The framework also provides for true object-oriented programming (OOP), and true inheritance, polymorphism, and encapsulation are supported. The .NET class library is organized into inheritable classes based around particular tasks, such as working with XML or image manipulation.
Besides the programming language and the methodology, database access is a significant concern. When you program in ASP.NET, integration with databases can be accomplished through ODBC, which provides a consistent set of calling functions to access your target database.
Strengths and Weaknesses
ASP.NET's strength lies clearly in its clean design and implementation. It is an object-oriented programmer's dream, with language flexibility, and with sophisticated object-oriented features supported. In that sense, it is truly interoperable with your programmers' existing skills.
Another strength of ASP.NET is the development environment. For instance, developers can use WebMatrix, a community-supported tool, Visual Studio .NET, or various Borland tools such as Delphi and C++ Builder. Visual Studio, for instance, allows setting of breakpoints, tracing sections of code, and reviewing the call stack. All in all, it's a sophisticated debugging environment. Plenty of other third-party IDE solutions for ASP.NET are certain to surface as well.
But what you gain in robustness, you pay for in efficiency. ASP.NET is expensive with respect to memory usage and execution time, which is due in large part to a longer code path. For Web-based applications, these limitations can be a serious problem, because on the Web, your application is likely to scale to thousands and thousands of users per second. Memory usage can also become an issue on your Web server.
What is PHP?
PHP is a scripting language based on the model of preprocessing HTML pages. When the PHP preprocessor in your Web server notices a PHP language tag like the following, the PHP engine is invoked to execute that code:
<?php some code here ?>
PHP will be familiar to any programmers who have worked with imperative programming languages; you'll notice syntactical similarities with Perl, C, and Java. Strictly speaking, Java is an imperative programming language, but it also makes use of object-oriented constructs and concepts. PHP borrows from this structure when it is convenient, but it is not a pure OOP language.
In the discussion of ASP.NET above, I mentioned the ODBC driver, and how applications can be built with database abstraction in mind. In PHP, you can also use ODBC to talk to databases, so you already have a whole list of supported databases to choose from. There are also native drivers for MySQL, Oracle, and Postgres. Furthermore, if you are connecting to Oracle, a special OCI8 library provides more feature-rich access to Oracle, allowing you to use such features as LOB, BLOB, CLOB, and BFILE.
You might ask, at this point, "Why are database-dependent libraries being touted as features of PHP?" Database abstraction, or independence, is a feature if you seek to build an application that works with multiple databases in one application or that can easily be ported to another database—when moving from development to production, for instance. And these are indeed valid concerns and considerations.
But, as Tom Kyte points out in his latest book, Effective Oracle by Design (Oracle Press), database dependence should be your real goal because you maximize your investment in that technology. If you make generic access to Oracle, whether through ODBC or Perl's DBI library, you'll miss out on features other databases don't have. What's more, optimizing queries is different in each database.
Zend Technologies, a commercial software company that contributes significantly to PHP, has created a commercial-development environment called Zend Studio that includes a sophisticated debugger, a profiler, and other features. It has also built the free Zend Optimizer, which, in combination with the Zend Encoder, compiles PHP code to speed performance. Additional commercial products also exist, such as the Zend Performance Suite, which can cache precompiled PHP pages, further speeding overall performance tremendously.
Strengths and Weaknesses
As of beta version 4, PHP 5 still has a few shortcomings, including its lack of exceptions, event-based error-handling instances that interrupt the normal flow of a program, jumping your code to a special error-handling section. Java also provides exceptions for error handling, while C++ provides exception handling via the try, catch, and throw syntax. You can, of course, still manage errors in PHP, but the structure is not standardized, so programmers are left to their own devices on how to implement error handling, leading to less consistency and a tendency to reinvent the wheel.
Another weakness is that PHP's function names are case insensitive. Some programmers might find this feature annoying, though this isn't a serious drawback.
I do have misgivings about PHP's object model, however. PHP wasn't designed to be an object-oriented language. Some of those features were added later, although care was made to keep backward compatibility with PHP 3, so you're left with a bit of both models. In fact, many of these weaknesses are addressed in PHP 5. Keep your ears to the ground.
What PHP lacks in a few areas, it makes up for by leaps and bounds in areas in which it excels. The price is right, so you don't have to worry about licensing issues. It's open source, too, so an entire community will keep a close eye on development, identifying bugs and making sure they get fixed. And if there's a feature you don't like, you can dabble with the code. What's more, PHP works native with Apache: It can be compiled as a module or directly into the Apache binary.
But running on Apache means that, with PHP, you can take advantage of whatever server investments you've already made, because Apache runs on Windows, Linux, Solaris, and various other Unix platforms. Also, going with a web server with Apache's track record means security remains a top priority. And, finally, PHP has a smaller code path, meaning there's less server-side code executed to parse and execute your PHP page, which results in more efficient memory and usage and faster execution.
What's New in PHP 5?
The fourth beta release of PHP 5 came out at the end of December 2003, and the change log makes it obvious that many bugs are being identified and ironed out. Although it's still in beta, it's definitely worth taking a look at for all the new features and advances.
PHP 5's major new achievements come in the area of its exception handling and a new object that introduces features that bring true OOP to PHP. Exception handling was certainly one of the most noticeable missing features in PHP 4, and its addition to PHP 5 is certainly a sign of maturity. Exception handling means you have language defined and standardized ways of handling errors in your software. Just use the try, catch, and throw methods, and your PHP code becomes more robust and clean.
The new object model has a number of positive impacts on programs written in PHP. In PHP 4, when an object was passed to a function or method, it was passed by value, unless you explicitly told PHP otherwise. This procedure meant that a copy of that object, all the data structures in memory, would have to be copied. This step used memory and made access slow and clunky. In PHP 5, however, objects are always passed by reference.
The new object-oriented features in PHP 5, including constructors and destructors, are noteworthy. As with C++ and Java, they provide a standard way to create the object, allocate memory, and do any necessary setup via a constructor method and perform cleanup with a destructor method.
PHP 5 also introduces more subtle control of methods and variables in your classes. In PHP 4, everything was public: You could access variables from your classes outside the class or in derived classes. In PHP 5, you can still make variables or methods public, but you can also make them private, so they're used only within the class itself. A third option is to make them protected, which means that methods and variables can be viewed within the class or when subclassed.
Furthermore, PHP 5 introduces type hinting, or better type checking. When you pass an object into a routine, PHP can check that it is the right type and give a type-mismatch error if the check fails.
Additional features such as static methods and variables and abstract classes exist, so be sure to check the documentation for details.
Security Comparison
ASP.NET officially requires that you use IIS. Unfortunately, IIS has a long history of vulnerabilities, which makes many administrators reluctant to deploy it to handle their web site. Whether these weaknesses are because of Microsoft's ineptness or because IIS is a real red flag to hackers is irrelevant: Those systems have a history of being hacked and compromised. PHP runs on Apache, too, which is fast and open source and has a good security track record. Also, as I mentioned, Apache runs on many platforms.
If you are considering ASP.NET but you want to use Apache for your front-door to the Internet, you are fortunate to have a few options. First, you can use Apache to relay requests to IIS running internally on another machine. Apache then handles static content and passes aspx content on to the IIS server, which isn't exposed to the internet.
However, if you want to host ASP.NET with Apache, a couple of options are available that may or may not be supported by Microsoft. As a last alternative, there is Ximian's Project Mono, which is working to build an open-source module. Check www.go-mono.com for more information.
Database Coding Examples
Connecting to a database is one of the first things you'll consider doing in PHP or ASP.NET. With ASP.NET, however, it's a little more complicated, because you have the option of any of a number of languages to choose from. Of course, these code samples would have to be embedded into an HTML page, the classes instantiated, and so on. The following information, however, will give you an idea of the coding styles for each.
PHP 5 Connecting to Oracle
Here's a PHP 5 class that provides an Oracle connect-and-disconnect routine to show one way of connecting to Oracle with PHP 5 (other drivers, such as the ODBC driver, and generic database interfaces can be used as well):
ASP.NET Connecting to Oracle
If you're looking to connect to Oracle with VB.NET (Visual Basic is Microsoft's default .NET programming language), take a look at this sample from MSDN:
Making the Choice
Without assuming you've already decided to go with PHP, I'll conclude that its strengths far outweigh its weaknesses. (See the summary in Table 1.) It boils down to price, speed and efficiency, security, cross-platform applicability, and open-source opportunity. Its only weakness is its lack of a pure and perfect OOP implementation; however, this is a minor drawback. Though language constructs do help, ultimately, good coding is a matter of practice, execution, good habits, and discipline.
PHP 4 | PHP 5 | ASP.NET | |
Software price | free | free | free |
Platform price | free | free | $$ |
Speed | strong | strong | weak |
Efficiency | strong | strong | weak |
Security | strong | strong | strong |
Platform | strong | strong | weak (IIS only) |
Platform | any | any | win32 (IIS only) |
Source available | yes | yes | no |
Exceptions | no | yes | yes |
OOP | weak | strong | strong |
Price. Here, we must consider not simply the price tag of the initial investment, which, in the case of PHP, is obviously free, but also the implementation, maintenance, and debugging costs. In the case of PHP, you may invest in the Zend optimization engine. With ASP, however, you're investing from the very beginning, and you're spending for add-on technologies—libraries for doing graphics manipulations, for instance. But, in the long term, PHP isn't going to press you to upgrade and collect more licensing fees. Everyone who has dealt with complex licensing also knows that companies spend time and money just ensuring they are compliant. Furthermore, you have a difference in response when getting bugs fixed. This, of course, translates to time, which translates to cost for overall development.
Speed and efficiency. As I mentioned earlier, ASP.NET is a framework allowing you to use various programming languages. In addition, it is touted as having a great object-oriented model. All this is true, but it becomes a detriment as far as speed is concerned. For all that advantage, there is a lot more code to run through to execute the same ASP page than you have to execute in the PHP engine for an equivalent PHP page. PHP is the quick-and-dirty type of solution, the one to get the job done. And though a lot of robustness has been added to it since its 2.0 and 3.0 days, it still retains that core optimized high-speed approach.
Speed is not the only consideration. Memory usage is also important.
Security. ASP.NET runs on IIS, which has been compromised innumerable times, as evidenced by IT news reports every other week. It has become such a liability, in fact, that in spite of all the marketing dollars spent on it, many IT professionals refuse to have their networks exposed with an IIS Web server. PHP, however, works with Apache, which has a proven track record of speed, reliability, and hardened security. Check www.securityfocus.com for more information.
Cross-platform applicability. ASP.NET runs on IIS and is starting to run on Apache, which can run on a whole host of platforms. PHP has been designed to work with Apache from the beginning, so you have many proven and reliable server platforms to choose from.
Open source opportunity. Open source is not just some philosophical torch idealistic programmers, or companies wanting to save a few bucks on licensing costs, are carrying. When you're dealing with bugs in the software itself, open source can be a serious godsend.
In either case, with PHP or ASP.NET, you have a large user base using the software and possibly encountering bugs. With ASP.NET, those bugs have to go through a bureaucratic process to get acknowledged, fixed, tested, and rolled out in a new patch or release. PHP fixes, however, can get fixed quickly and rereleased. Anyone who has watched open-source development knows new releases and patches often come out in days rather than in weeks or months, as with commercial software. If that's not fast enough, you can always fix a problem yourself if you have to.
Next StepsRead Sean's follow-up to this column, PHP vs. ASP.NET Redux
Read The Hitchhiker's Guide to PHP (series)
Learn more about PHP at the Open Source Developer Center
Sean Hull is the senior consultant at his firm, iHeavy Inc., in New York City. He focuses on integrating open source technologies with commercial technologies such as Oracle, and has serviced many successful New York companies. The opinions expressed by this author are entirely his own and do not reflect the position of Oracle or any other corporation.