Comparison of PHP, Python, ruby--web scripting languages

Source: Internet
Author: User
Tags echo command php language php and mysql hosting shared hosting shared hosting provider ruby on rails tiobe index
Summary

In the last few years, scripting languages have become increasingly popular in Web application programming. This paper attempts to find the differences, advantages and disadvantages in today's three most popular languages: PHP, Python, and Ruby. Obviously, they have their own views and support, so it is a difficult task to state objective facts and to satisfy a scientific approach. These three languages will evaluate the history, evolution, prevalence, syntax, semantics, functionality, security, and performance of the Web application environment. Finally, a final conclusion will suggest the most promising language.

1. Introduction

The dynamic scripting language has reached a common programming language in the mainstream market. They have certain attributes to differentiate from classical static languages such as language C + +:
--They are dynamic types
--they pay attention to grammar
--they have an automatic memory management and garbage collection
--they are mostly explanatory (rather than compiled)

These properties are attractive for web application development because they support rapid prototyping, rapid code changes, and test routines. Depending on the specific language selected, there is also the value of a particular difference language. However, this article is not about comparing dynamic and static languages, but comparing three dynamic languages: PHP, Python, and Ruby. In this introduction I will give some details about the history and popular language. The main part of the paper is about comparative grammar and semantics, language features, security and performance. Eventually there will be a conclusion that lists all the discoveries and suggestions based on the needs of programmers and users.

This article describes a description of three languages, an overview of the features and possibilities, and a comparison of the properties associated with web development and decision guidance when evaluating an engineering language.

1.1 History

The history of Web application development is relatively short. At first it was all almost a link to some static files. Mehdi Jazayeri points out that this Web application project is similar to the software engineering history, but is much smaller in web application engineering [14]. He showed that in the early days there was no more structure and the generation scripts were written in Perl to produce web pages. Thus, the content in the embedded script and the HTML markup code have a larger problem, resulting in difficulty in managing the code. At this point, PHP enters the market in an opposite way: The script code is inserted into the HTML content.

PHP was started by Ram Lerdorf in 1994, which is an acronym for "Personal Home" (in 1997 with PHP replaced by: Hypertext preprocessor). The PHP language was developed by the PHP team and is now the actual standard [12], resulting from the absence of formal language specifications. [13] It is published under the Open Source License Terms and the development documentation is free online.

As Web application engineering matures, software engineers recognize that a separation of concerns is necessary to achieve large and complex projects. A well-known design pattern in web development has a new focus: Model-View-controller [17]. PHP does not support object-oriented programming from the start, but its functionality is constantly being added to the language to catch up with the need for model-view-controller design patterns.

At the same time, the Python programming language is a few years old. Python was developed by Guido van Rossum in 1991 for a short period of time when the World Wide Web was published for public use. It was a full-featured universal language from the outset and was not specifically used as a web scripting language like PHP. Its language is not formally regulated, but the de facto standard is made by the Python Software Foundation [20] (which implements reference CPython, because it was written in C). There are several other projects that provide a compatible Python implementation: For example, Jython was written in Java and used at the bottom of the Java platform. IronPython is written in C #, using the. NET Framework. A implementation named PyPy is written in Python itself. [10] Similar to Php,python has a strong open source background, as well as comprehensive online development documentation.

Another programming language was born in 1995:ruby, a scripting language developed by the time and the Yukihiro Matsumoto, which has a very similar philosophy compared to Python. Ruby is a fully object-oriented programming language that is strongly influenced by the Smalltalk of programming languages. Ruby has an implementation specification written in C and is open source (again similar to PHP and Python). The Ruby language development is done in collaboration with an open community, and there is no formal base or organization behind it. [9] Language specifications and development documentation are available online for free.

1.2 Popularity

The popularity of the language used is very important for the company to have a large enough pool of employees. Unpopular and unknown languages are a planned adventure for maintenance and development, as well as for writing software. Thus, what language should be used in decision-making projects depends on the prevalence of programming languages.

At this point I would like to mention the popular measurements very difficult. The results of any form cannot be regarded as true scientific evidence, as it is difficult to collect representative data.

One indicator of popularity is the Tiobe programming Community index [6]. It is ranked by skilled engineers, courses, third-party vendors, and search engine-rated programming languages. The website says, "The index can be used to check if your programming skills are still up-to-the-current or what programming language to use in making strategic decisions to start building a new software system." "May 2009 PHP is ranked fourth, sixth bit Python and Ruby on tenth.

Another way to measure such network media is to discuss IRC, newsgroups, and so on. Anton Ertl provides a data page that counts different languages for each company's application. As of March 2009, Python is ranked number one, Ruby is ranked fourth and PHP Nineth. Similar to the Tiobe index, there is a website about the popularity of programming languages, also based on IRC ratings and discussion properties such as Slashdot[5]. This normalized discussion site finally shows Python ranked third, Ruby in sixth place and PHP Nineth.

In the context of the Web programming language, we can also consider the existing software ecosystem. As mentioned earlier, all three languages are closely related and are free and open source software, so there are many web frameworks and content management systems to use. PHP is used by the most popular content management systems, such as MediaWiki, Drupal, Joomla, and WordPress, and only a few of them are listed here. Python's most popular web framework has a Zope application server and is used in content management systems like Plone, Django. Ruby provides a well-known web framework for Ruby on rails, but there is no popular content management system to use.
PHP provides a major advantage for SMBs and private customers: it can be used on almost every shared hosting provider and is now the easiest to build on a server.

In short, PHP, Python and Ruby are always among the top ten popular languages and are the world's most famous languages. PHP has an advantage in the search engine rating and is available on the hosting provider. Python has an advantage in discussing media ratings. PHP offers the most popular full-featured content management system, which allows no programming skills on site construction, while Python and Ruby illustrate the available web frameworks for greater flexibility, but also require more programming effort.

2. Syntax and semantic comparison

This chapter will focus on the discussion of code snippets and programming language constructs, which can be compared in three languages: PHP, Python, and Ruby.

2.1 PHP

As mentioned in the introduction, PHP invented the technique of embedding code directly in the contents of a document. A simple example is shown in Listing 1.1, when the incoming request, the script is triggered, the built-in PHP echo command is executed.

Listing 1.1. PHP code embedded in an HTML document


Listing 1.2. A simple PHP sample to check the login information

This is useful for small and static web pages, but as the development and application of the network becomes more complex, the embed code is transferred to the Templateles (template engine), which is responsible for the view, design, and appearance.

Business logic code separates other files, which improves clarity and maintainability. Here is a typical example of a PHP code snippet that shows the basic language structure in listing 1.2. This is the work on security from Armin Ronacher on Web applications [19].

As you can see, the PHP syntax comes from the syntax in the C language, which is the central element in the language. Today's version does not have a namespace (which will be introduced in future PHP 5.3), and all functions need to have unique names. Variables must precede the $ sign and do not require initialization, and can access global variables with a special keyword ("global"). PHP has a weak-type system that uses implicit type conversions, such as an integer and a string that can be compared in a Boolean expression. This often causes confusion and uncertainty?? The operator should use the case, but there are comparison tables and hints in the PHP documentation.

In the example above, MySQL database statements are directly integrated into the code, which is a disadvantage in PHP for a long time because the database system is tightly coupled with PHP functions. Until PHP 5.1 supports PDO (PHP Data Objects), this is a way to abstract the database layer using a construction-based feature.

The paradigm for object-oriented programming is relatively new for the PHP language, which was introduced in PHP 4 and enhanced in PHP 5. However, PHP's program code roots are evident in most of the current PHP Web frameworks and content management systems, but there is a migration process from the process-oriented to the object-oriented approach.

PHP has always been considered easy for beginners to learn. Sample code is available in many places on the web and has fewer lines of code to achieve common tasks. As a complete software technology for a Web application, the famous lamp stack (Linux Apache MySQL PHP) is free and has good documentation and tutorials. Many programmers are familiar with their syntax because it resembles well-known languages such as C and Java. PHP's behavior is always very strong?? Use implicit type conversions, keep warning warnings, and error warnings only when a critical error occurs (this is an advantage for beginners, but also a development trap for complex code). These factors give PHP a strong user base and contribute to many systems.

2.2 Python

Python is a language that is not particularly focused on Web applications at first, until a time when Web scripts begin to become common in Python. The first method is to use a CGI (Public gateway Interface) as shown in Listing 1.3.
Listing 1.3. A simple Python script that returns a Hello World field


Web frameworks are written in Python, but they use different techniques, such as Cgi,mod Python, to communicate with the Web server gateway. Therefore, the framework is incompatible with different Web servers or different gateway interfaces. The solution to this problem is Wsgi: "Wsgi is the Web server gateway interface. It is a canonical Web application that communicates with the Web server and application server (although it is far less applicable). It is a Python standard that is described in detail in Pep 333. "[7]WSGI allows the gateway system to change the environment or network application without touching the source code.] So it has the advantage of being more convenient. According to Wsgi, a Python Web application can be implemented in its simplest form, as shown in Listing 1.4.

Listing 1.4. Via WSGI's Hello World program


Having a unified interface is good for this approach, but it's also a bit complicated for beginners. More detail must be explicit rather than implicitly defined, just like in PHP or the above CGI solution.

Listing 1.5 shows the same section as the PHP login verification example, but is now implemented in Python. [19] This is also the work from Armin Ronacher on the security of Web applications.

Listing 1.5. Verifying login information in the Python function


Python is an object-oriented language from the beginning, compared to PHP, but it is not limited to this pattern, but also supports procedural programming and some function features. Some people prove that its grammar is easy to read and understand because it has only a few keywords. Python syntax differs from one of the main syntax attributes of PHP and Ruby: Indentation within a block is mandatory (for example, a function body). This means that the source code is always strictly structured, and most other programming languages are not so mandatory. In Python, statement definitions do not need to be separated by colons (line breaks represent the end line), but they are allowed to be used.
Python's type system is powerful. At run-time errors There is a recent call to Traceback, which provides debugging information to the developer.

2.3 Ruby

Ruby is a programming language that has only one major web framework: Ruby on Rails. It uses CGI as a gateway and also provides its own web server, but it is only recommended for development and testing. Here I will skip a Hello World example. Listing 1.6 shows an example of the authentication login feature implemented with Ruby.

Listing 1.6. Verifying login information with Ruby


Ruby syntax is similar to Python, but the semantics are a little different: Ruby is purely object-oriented and is structured in Smalltalk language syntax. This means that the original type is different from the complex type, and the objects communicate between them by sending messages. Each object can receive any message and handle unknown messages in a way that is handled abnormally. All language structures, including primitive objects such as jobs, are treated as objects that receive specific parameter messages.
Ruby also separates the statement by a newline character, or it can be appended with a semicolon at the end. Ruby does not use forced indentation like Python, which uses do as a keyword (or as an abbreviated form of curly braces) to represent blocks of code. It also supports procedural programming paradigms, some functional language constructs, and meta-data programming.
Ruby follows the principle of least astonishment, which means that the language is designed to be used intuitively and the expected behavior should correspond to the actual behavior. Ruby is an extremely dynamic language that can change the behavior of each object at run time, including the ability to mutate the semantics of built-in types. This can lead to completely unexpected results, such as reversing the meaning of ' true ' and ' false ' in a conditional sentence that will break most programs. It is therefore necessary to ensure that all programs are trustworthy, and to define rules or guidelines that describe what can be changed and what cannot be changed.

2.4 Readability and usability

For programming language users, it is difficult to define how to make readability and usability. PHP follows a very special method that is widely documented and may be most familiar to C programmers. Python's keywords with its strict mandatory indentation and small set of keys may be the best choice for beginners in programming. Finally, Ruby may attract Smalltalk enthusiasts and experienced programmers because of their elegant and powerful programming expressiveness.
Although Python seems to have the most readable syntax in three languages (because of the forced indentation structure), Ruby seems to be the most useful (because of its least surprising principle). Of course, PHP is a highly readable language, because most programmers are familiar with C-based syntax.

3. Comparison of language features

This chapter will list some of the features of programming languages that are useful in some cases and useful in Web application development.

3.1 Exception handling

Exception handling is available in all three languages. Python and Ruby are available from the start, and PHP is added in version 5. So some PHP content management systems lack proper exception handling support in their code and frameworks?? The popularity of this feature is not widespread.
The difference between languages is only a grammar that is made up of other keywords. PHP has "try/catch/finally" to handle exceptions and "throw" operations to trigger exceptions. Python uses "try/except/finally" and "raise", and Ruby provides "Begin/rescue/ensure" and "raise". The system works in all languages very similar, dealing with as most programmers expect it. Python version 2.5 introduces a new add-on feature that allows objects to define standard cleanup operations (such as file object shutdown regardless of whether the operation was unsuccessful or successful). Programmers do not have to worry about "finally", which can reduce the length of the source code and ensure proper cleanup, which can have a large program impact on performance. See pep 343[1] for reference.

3.2 Relational Database Abstraction

Almost all modern Web applications require a database underlying storage and retrieval of data. In order to develop an easy-to-use, secure, vendor-independent relational database, a good way to digest from common, old-fashioned SQL statements is necessary.
PHP and MySQL database system have a long history. PHP Web applications have been and are now tightly coupled to a particular database. Since the release of PHP 5.1, a concept called PHP Data Objects (PDO) has been introduced and used as an abstraction layer for SQL-based database systems. By using PDO and standard SQL statements, you can now change the database system without changing the source code of too many Web applications. Object-Relational mapping (ORM) from third-party libraries can also be exploited, but they are not used by most existing content management systems, and the PHP Web framework uses only some of them.
Python specifies a database api[2] in PEP 249, which encourages the development of similarity modules when accessing different database systems in access to various databases. When using the popular Python web framework, it is often seen that some ORM tools are included and further layers of abstraction are added to allow object-oriented database access.
Ruby in the only popular web framework?? Ruby on Rails uses the ActiveRecord system to provide an ORM mode. It can perform similar tasks as an ORM tool like any other language framework.

In summary, there is support for database abstraction in three languages, and ORM is widely used in all web frameworks. PHP is a bit behind the other two languages, because its database abstraction has not yet been applied by existing PHP projects that exist for a long time.

3.3 Functional language Features

Both Python and Ruby support the features of functional languages. They all have a list-understanding mechanism that applies to lists and set types, a function that is treated as a first-class citizen, and a "lambda" keyword for writing anonymous functions.
Ruby implements closures?? A concept that takes a block of code as a function call parameter (Python can achieve the same behavior). This is a functional feature that uses first class functions and free variables to maintain their scope and life cycle in closures.
PHP does not pay particular attention to functional programming, although it can also implement a function name as a string stored in a variable, and then use it to invoke a function reference. This is a very basic and incomplete functional behavior, so PHP cannot gracefully provide a functional paradigm.

3.4 Interactive Interpretation

The PHP, Python, and Ruby Standard implementations provide the ability to interactively interpret the window. This means that the translation can be initiated in an interactive mode in which some command lines accept statements and expressions on a row-by-line basis and print out the results immediately. It can be used for example to directly test small snippets and observations, or to experiment directly with the syntax without having to edit, save, and run the files that contain the code. This feature is especially valuable for beginners, and it also has some testing effect on experienced programmers.
Interactive development and testing is present and is well applied in all three languages.

3.5 Duck Type

Duck type is a polymorphic paradigm in object-oriented dynamic type language. The properties and methods of an object determine the applicability of the object and not the type of the object. Python and Ruby promote and encourage the use of the duck type and provide the appropriate mechanism for catching exceptions, while PHP is not designated to be able to take advantage of the duck type of language, but instead recommends the use of inherited polymorphism. PHP introduces a concept called type hints, where the parameters of a function or method are specified by a particular type, and an error is thrown when the error type is passed.

Programmers who write software using the Duck type should consider using Python or ruby instead of PHP.

3.6 Main drawbacks of PHP

The PHP platform has some major drawbacks, Nikolaj Cholakov[8] Describes these and we summarize here. PHP allows the use of uninitialized variables, usually with unique naming conventions and similar functions using a different parameter command. There is also no namespace, so functions need to have a unique function name, and the number of available functions is very large, some of which perform the same task and are easy for programmers to confuse. Error handling is resolved two times: process-oriented uses "Set_error_handler ()" and object-oriented exception handling.
PHP is also notorious for features such as "Register_globals" and "magic quotes", but they have been removed from the syntax and this article will not be discussed.

3.7 Other differences

There are other detailed differences between the two languages, but these are not particularly important for Web applications. PHP does not support threading (concurrent programming) and Python and Ruby provide "yield" statements as generating functions (there is a semantic difference between Python and ruby in yield usage), here is only a little bit of detail, not too much involved.

4. Security comparison

The first part of a Web application that emphasizes security most is the user's input. To avoid attacks, it is critical to clean and secure the data that is submitted to the Web application from the outside, such as user name and password credentials, comments, forum posts, or other aspects of the content. In this section, I'll discuss some popular attack techniques.

4.1 SQL injection

SQL injection is a special use of SQL statement characters (such as the string "??") that are used to query the database. Used as a comment escape sequence) for an attack. In PHP, it is possible to use functions to get rid of this special character (see listing 1.2 for example), but this is database-independent and non-portable. The practice of using SQL statements with PDO (PHP Data Objects) is advocated, where queries are established in a secure manner (malicious data will be encoded or automatically escaped). Python also implements the same approach using the database API (see listing 1.5), and Ruby also provides this automatic support in the rails framework. If you use these APIs, then SQL injection is not an issue for all of these three languages.

4.2 Cross-site scripting attacks (XSS)

A cross-site script is an attack that inserts a pre-prepared malicious script fragment into the content of the Web application and executes it in the victim's browser. The corresponding countermeasure is to strictly clean the input provided to the user (in this case, the attacker provides). PHP, Python, and Ruby provide functions to evade potentially dangerous inputs, and many template engines in the Web framework provide escape or even auto-evasion. All of these three languages are designed to handle this attack in advance.

4.3 Server-side code execution

Scripting languages often have a very dangerous feature?? To compromise the security of a Web application: "eval ()" or "exec ()". The purpose of this function is to execute the code stored in a string variable. If a string variable is made up of user-generated content, using eval will result in a huge security vulnerability. All of these three languages offer this functionality, but are not encouraged to use it.

4.4 PHP Security Flaws

PHP can be used in a safe way, but there are some core security issues that stem from a poor language design. There are projects like Suhosin that provide a protection system and a PHP hardening patch to fix issues related to buffer overflow or format string vulnerabilities. PHP allows for a lack of programming practices that can lead to many bugs in the Web application development process. In the national vulnerability database, about One-third of the storage vulnerabilities are related to PHP. With this in mind, PHP may not be the best choice for emphasizing secure applications.

4.5 Performance Comparison

Performance, speed, and responsiveness are important factors for Web applications, although these features are difficult to measure objectively. The overall system environment affects performance: such as network speed and response time, database connectivity, Web server performance, server hardware performance, and the number of requests that occur.
However, the choice of programming language also has an impact, that is, the implementation of a particular language. Computer language benchmark score game [3] You can try to compare the performance of different programming languages. The Web page says, "How do we implement the test language?" We can't, we measure a particular program. "Solve programming tasks in a common language, and run on the same hardware and operating system." Rank PHP, Python, and Ruby based on the results on the final list. Mainly because these scripting languages are not compiled into machine code, but interpreted at runtime, the three languages are relatively close and perform no more than 10% in the overall test ranking. None of these three languages showed a significant advantage over the other two cases. Interestingly, Ruby has a huge performance boost from version 1.8 to 1.9, with the median of 1.9 being about twice times that of version 1.8 (which seems to be related to the byte-code compiler and virtual machine execution for the 1.9 version). There is also a JRuby implementation in the manifest, which performs a very similar reference implementation.

A common way to improve performance is to use the speed optimization of the caching system. PHP extensions are very common and widely used in caching to compile bytecode to avoid parsing and compiling the source code in every request. Python also provides a caching system for Web applications, MEMCACHED2, a more general-purpose memory caching system that was originally applied to the Django Web development Framework. Ruby can also apply caching mechanisms, such as the memcached just mentioned.
In short, it is difficult to summarize a overall performance winner, after all, the results of all ratings in these languages are almost the same.

6. Related work

There's a lot of literature on Web application engineering: Mehdi Jazayeri wrote an interesting article on the trends and realities of Web applications [14],vosloo and Kourie Web presents an overview and concept of the web framework [22],armin [19] Ronacher recorded a very practical safety-related issue. The entry point of this article is only an explicit use of a small selection, and it is expected that as web development continues to grow, there will be more discoveries in the future.
The scripting language also involves a number of articles, such as Luis Rei et al. 's work on the great picture of scripting languages, such as Ronald Loui, which describes the pragmatism of expression programming using scripting languages [16].
In addition, there are some materials about the contrast between each language. Nikolaj Cholakov The PHP analysis and summarizes some of the drawbacks [8] and Xavier Spriet some suggestions about PHP security and configuration [21]. Gred LINDSTROM[15] Introduced and explained Python programming, and David Geer a general introduction to Ruby on Rails [11].
Because PHP, Python, and Ruby are both free and open source languages, there are a lot of relevant work and help available on the Web, and you can refer to this article for a reference to the resources [13][10][9].

7. Conclusion

This article presents three dynamic programming languages from a Web application engineering perspective: PHP, Python, and Ruby. Among them, the nature, the characteristic and the safety we have carried on the corresponding discussion and the analysis to give the language comparison. The pros and cons of the appropriate programmers (or users) for each language are pointed out.
Deciding which language to choose should first be based on the following use case: What is the goal of the Web application to accomplish? A PHP Content management system may be the best choice if it is used for common tasks such as Web stores or news sites. It supports rapid development and can be scaled to suit individual needs. The disadvantage is flexibility: scaling is closely related to the system's data model and internal program flow. If the software is intended for more specialized purposes, it is best to build the web framework from scratch. In this case consider table 1, where the criteria are important for your choice of different languages in different cases, from best choice to worst choice.

Listing 1. PHP, Python and Ruby based on different case comparisons

Feature Selection

Detailed description

Best

Medium

Worst

Popular level

Job market

Php

Python

Ruby

Reliability

In most systems that exist

Php

Python

Ruby

Readability

Maintainability and varies by person

Python

PHP Ruby

-

Availability of

Rapid prototyping and development

Ruby

Python

Php

Security

For important applications

Python Ruby

Php

-

Performance

Run speed and execution time

PHP Python Ruby

-

-

Database abstraction

Supply-independent and object-relational mapping

Python Ruby

Php

-

Exception handling

Error control and recovery

Python Ruby

Php

-

function features

Technical possibilities of functional programming

Python Ruby

-

Php

To better understand the differences between different languages, refer to Figure 1.

Figure 1 relative comparisons between languages, measured from 0 (worst) to 10 (best)


Disclaimer: Programming languages PHP, Python, and Ruby are all permanent developments, so this table may change in the next few months or years to come. We try to get results from objective facts and analyze the language. However, the choice of programming language is always related to personal experience, so the discussion of language is often a personal inclination and with some irrational factors.
As a final recommendation, I think that using Python Web applications as a common use case, Ruby has a strong backing but has yet to form a popular trend. PHP can only use popular content management systems, where requirements are not too much programming and customization is necessary.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.