Beta

Slashdot: News for Nerds

×

Welcome to the Slashdot Beta site -- learn more here. Use the link in the footer or click here to return to the Classic version of Slashdot.

Thank you!

Before you choose to head back to the Classic look of the site, we'd appreciate it if you share your thoughts on the Beta; your feedback is what drives our ongoing development.

Beta is different and we value you taking the time to try it out. Please take a look at the changes we've made in Beta and  learn more about it. Thanks for reading, and for making the site better!

Extending and Embedding PHP

samzenpus posted more than 7 years ago | from the read-all-about-it dept.

128

Sebastian Bergmann writes "PHP is a widely-used general-purpose scripting language that is especially suited for Web development. The interpreter that executes programs written in the PHP programming language has been designed from the ground up to be easily embeddable (for instance into the Apache Web Server) and extendable. This extensibility is one of the reasons why PHP became the favourite "glue" of the Web: functionality from existing third-party libraries (database clients or image manipulation toolkits, for instance) can be made available through PHP with the ease of use you expect from a scripting language." Read the rest of Sebastian's review.

"Extending and Embedding PHP" by Sara Golemon, a long-time contributor to the PHP project, remedies the fact that the internals of PHP are far from being as well documented as the rest of PHP. It brings writing extensions for PHP "to the masses", so to speak.

After a short introduction that makes the reader familiar with terms like PHP Extension, Zend Extension, Userland, and Internals that are used throughout the book, Chapter 1 ("The PHP Life Cycle") opens with an overview of how the PHP Interpreter works and what parts (TSRM, Zend Engine, SAPI, "PHP") it comprises.

Chapter 2 ("Variables from the Inside Out") shows how PHP handles and stores variables internally. The reader learns how to distinguish types, set and retrieve values, as well as how to work with symbol tables. It is in this chapter that the fundamental unit of data storage in PHP, the so-called zval (short for Zend Value) is discussed.

Chapter 3 ("Memory Management") builds upon the previous chapter and discusses more advanced operations on zvals, for instance creating and dealing with copies of a zval or the destruction of a zval when it is no longer needed. To this extent, the Zend Memory Manager is discussed as well as underlying principles such as Reference Counting and Copy-on-Write, for instance.

Chapter 4 ("Setting Up a Build Environment") guides the reader through setting up an environment, either on *NIX or on Microsoft Windows, for the development and debugging of PHP and PHP extensions.

After these first four chapters, the reader is ready to go about writing his or her first PHP extension. Chapter 5 ("Your First Extension") takes the reader through the steps necessary to write and build a simple working PHP extension. The following chapters build upon the knowledge gained here, so that the reader can ultimately implement or change any type of PHP feature.

Chapter 6 ("Returning Values") explains how to pass values (by value, by reference, and through their parameter stack using references) from internal (C-level) functions or methods to userland (PHP-level).

Chapter 7 ("Accepting Parameters") deals with the mechanisms involved in accepting parameters from userland calls to an internal function or method. This includes the discussion of the zend_parse_parameters() API which makes the parameters that are passed to the internal function or method as indirect zval references usable in your C-code. The handling of optional and arbitrary numbers of parameters is explained as well as the usage of type hinting and its arg_info API.

Chapter 8 ("Working with Arrays and Hash Tables") explains the Zend Engine's HashTable API, which is used to store any piece of data of any size, in detail. Its different data storage mechanisms supported are introduced and compared. To quote from the book, "A HashTable is a specialized form of a doubly linked list that adds the speed and efficiency of vectors in the form of lookup indices". Since these structures are used heavily throughout the Zend Engine and PHP and its extensions, a good understanding of this API is vital for any aspiring PHP extension developer.

Chapter 9 ("The Resource Data Type") introduces the reader to the first complex data type (excluding the Array data type that was discussed in the previous chapter, which is just a collection containing primitive data types like strings or numbers). A resource can be, for instance, a connection to a database. It allows the PHP extension developer to "connect abstract concepts like opaque pointers from third-party libraries to the easy-to-use userspace scripting language that makes PHP so powerful".

Chapters 10 ("PHP 4 Objects") and Chapter 11 ("PHP 5 Objects") delve into the last data type supported by the Zend Engine: objects. Sara Golemon dedicates one chapter each to the respective APIs of PHP 4 and PHP 5 because of the huge advancements that were introduced in PHP 5 and that totally changed the APIs.

After the previous chapter, all data types supported by the Zend Engine have been discussed and the book revisits a topic discussed earlier in the book: that of the PHP Interpreter's life cycle. Chapter 12 ("Startup, Shutdown, and a Few Places in Between") explains how to add state to a PHP extension by using thread-safe globals. Along the way, concepts such as internal and external (super) globals as well as thread safety are discussed.

Chapter 13 ("INI Settings") shows how a PHP extension can be made ready for runtime configuration through php.ini settings.

The next three chapters ("Accessing Streams", "Implementing Streams", and "Diverting the Stream") make the reader familiar with yet another important API of PHP: the Streams API. All file input/output in PHP userspace is processed through PHP's Streams Layer. This layer, that was introduced in PHP 4.3, is what makes working with files, compressed files, and remote files, for instance, seamlessly in PHP. The reader learns how to work with streams as well as how to expose streamable resources, whether remote network input/output or local data sources, using the Streams API, thus avoiding the need to reimplement all the tedious bits and pieces that are normally associated with this.

Chapter 17 ("Configuration and Linking") builds upon the tools and techniques introduced in Chapter 4 and adds the GNU autotools (autoconf, automake, and friends) to the reader's set of tools. These tools, if used correctly, allow the extension to be built in environments that the extension author does not know or has no access to.

Chapter 18 ("Extension Generators") takes a look at ext_skel (which comes with the source distribution of PHP) and PECL_Gen (which can be obtained, as the name suggests, from PECL, the PHP Extension Community Library). These two tools automate most of the steps described in the previous chapter and take a lot of tedious work out of the extension writer's hands.

Starting with simple embedding examples, the reader learns in Chapter 19 ("Setting Up a Host Environment") and Chapter 20 ("Advanced Embedding") how the PHP Interpreter can be embedded into almost any other application.

The book concludes with the "Zend API Reference", "PHP API Reference", "Extending and Embedding Cookbook", and "Additional Resources" appendixes. The first two are a great resource for both novice and experienced PHP extension writers (even for people working on PHP and the Zend Engine itself). The third features a collection of common use code snippets while the last one points the reader into the direction of PECL by suggesting a couple of existing extensions to look at and learn from.

Since the topic of this book is to extend the PHP Interpreter using extensions written in the C programming language (or to embed it into an application that is written in C), a good understanding of C syntax, its datatypes, and pointer management is important to get the most out of this book.

Being a contributor to the PHP project for about six years now, I have been looking forward to this book. True, there is always the source code of the PHP Interpreter as a source of information on how "things work". But although being the ultimate reference, reading the source code cannot replace a thoughtfully structured and well written guide that gets you started. If you are looking for such a guide, look no further: you will find it in this excellent book.

Although it deals with a very technical topic, "Extending and Embedding PHP" is readable and the many code examples are easy to follow. The reader profits from the knowledge of the author, who has been involved in the PHP project as a core developer for over four years now and is also the author and maintainer of a dozen PHP extensions that are available through PECL. The book covers both major versions of PHP that are currently used, PHP 4 and PHP 5, and it will continue to serve its purpose when PHP 6 comes out next year.

Sebastian Bergmann spends his free time with the development of Free Software, is a member of the PHP and Gentoo Linux development teams and author of a variety of PHP software projects such as PHPUnit."


You can purchase Extending and Embedding PHP from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

cancel ×

128 comments

php-embed (5, Informative)

SIGALRM (784769) | more than 7 years ago | (#15819816)

The book sounds interesting. There's also an often-overlooked capability of PHP: the ability to use php-embed [php.net] to run embedded PHP within a C/C++ app. For example, our company created an HL7 accelerator--we chose PHP as the embedded language in our product--by which users can more easily create custom data transformations.

The reason? PHP is easy to use, loosely-typed (which happened to be an advantage in this case), fast, and of course the license works. It was a great decision.

PHP-embed is basically just a TSRMLS function wrapper. It's pretty straightforward; for example, zval integration is easy as pie, as I recall, something like:
zval *zarray;
MAKE_STD_ZVAL(zarray);
...

if ( array_init(zarray) == FAILURE ) {
// ... something wrong
}

add_assoc_string(zarray, str_name, str_val, 1);

ZEND_SET_SYMBOL(&EG(symtab), tokenlevel, zarray);

Re:php-embed (1)

Steve Embalmer (783552) | more than 7 years ago | (#15819918)

OT? I thought it was one of the few informative FPs and exactly what the book review was covering. Sorry I don't have mod points to counter.

Re:php-embed (1)

rycamor (194164) | more than 7 years ago | (#15819986)

Yes, really... an informative and helpful FP getting modded down. Oh wait... this is Slashdot. It was modded down because the canonical form of a first post is in fact an off-topic rant, or some stupid pun on the story title.

Re:php-embed (0)

Anonymous Coward | more than 7 years ago | (#15820401)

probably modded down for praising the usefulness of php too...

Re:php-embed (1)

creepynut (933825) | more than 7 years ago | (#15819923)

Whoa there mods, I fail to see how this is off topic.

Re:php-embed (1)

cerberusss (660701) | more than 7 years ago | (#15823063)

our company created an HL7 accelerator

You bastard. You said the evil word and now I can't sleep for 7 days and 7 nights.

Aaaah.... it brings back fond memories of weeks-long being swamped by specs, hundreds upon hundreds of pages of specs. And when you thought you 'got it', some idiot brought out a new document with rather creative new uses of that same spec. I love this HL7 v2/v3 standard shit!

HOW DO I SHOT WEB \(_o)/ (0)

Anonymous Coward | more than 7 years ago | (#15819817)


Re:HOW DO I SHOT WEB \(_o)/ (0)

Anonymous Coward | more than 7 years ago | (#15819999)

I DUNNO, LOL

Obvious (0)

Anonymous Coward | more than 7 years ago | (#15820122)

The answer is 42.

Re:HOW DO I SHOT WEB \(_o)/ (1)

jahknow (827266) | more than 7 years ago | (#15822299)

You have no chance to survive make your time.

Mod parent up (1)

Freedom451 (966684) | more than 7 years ago | (#15822686)

We get signal.

You CATS with mod points, its you!

You GET SIGNAL!

Your BASE p0wn3d by mod_php!

Lameness filter defeated! Post completed! (0)

Anonymous Coward | more than 7 years ago | (#15820182)


I'd rather see a review (-1, Troll)

Spazntwich (208070) | more than 7 years ago | (#15819823)

of a book that tells you how to expertly pass the blame when various security holes you leave in your PHP application cause the destruction of your company's website and theft of significant information.

Re:I'd rather see a review (0)

Anonymous Coward | more than 7 years ago | (#15819909)

Found one: http://www.oreilly.com/catalog/phpnut/ [oreilly.com]

Re:I'd rather see a review (1, Insightful)

Anonymous Coward | more than 7 years ago | (#15820098)

What makes you think such a book would be PHP specific?

slashdot == teenage hangout (-1, Troll)

Shut the fuck up! (572058) | more than 7 years ago | (#15819828)

Repeated PHP articles, alarmist anti-bush articles, and games. That's about it. I look forward to Slashdot's slow painful death.

"Extending and Embedding PHP" (2, Funny)

Anonymous Coward | more than 7 years ago | (#15819831)

"Extending and Embedding PHP"...

Microsoft involved here? :)

Re:"Extending and Embedding PHP" (-1, Troll)

Schraegstrichpunkt (931443) | more than 7 years ago | (#15820752)

Hopefully. Maybe they'll put PHP out of its misery.

PHP is the "glue" of the web, eh? Must be because of the sticky mess it makes wherever it's used.

BOYCOTTEZ ISRAEL!!! (-1, Troll)

Anonymous Coward | more than 7 years ago | (#15819903)

Arretez l'ignominie!

Other People's Code (2, Insightful)

neonprimetime (528653) | more than 7 years ago | (#15819943)

But although being the ultimate reference, reading the source code cannot replace a thoughtfully structured and well written guide that gets you started.

Agreed, especially when the source code you're reading isn't your own. I claim that 99% of programmers who are not me write totally obfuscated code. Damn them!

Re:Other People's Code (1)

Frightening (976489) | more than 7 years ago | (#15820512)

That's OK. We all also think that you suck.

Re:Other People's Code (1)

neonprimetime (528653) | more than 7 years ago | (#15820562)

Nothing more obfuscated than C++ for loops like this one ...

for( ; ;i++) { if(i 50) { k+=i ; continue ; } break ; }

Re:Other People's Code (1)

Frightening (976489) | more than 7 years ago | (#15821876)

Ok we suck.

Slashdot's book review links (0)

Anonymous Coward | more than 7 years ago | (#15819984)

I know that Slashdot gets kickbacks from B & N, but it's very inconsiderate of them to make their readers pay so much when Amazon has it for less [amazon.com] (see Amazon's third-party sellers, cheapest prices on the 'Net).

Re:Slashdot's book review links (0)

Anonymous Coward | more than 7 years ago | (#15820054)

It's even cheaper here. [bookpool.com]

That's the beauty of e-commerce on the Internets - protection from getting gouged.

Sara Golemon (2, Interesting)

larry bagina (561269) | more than 7 years ago | (#15819994)

I knew her when she worked at berkeley (I think she works for yahoo! now). She really knows her shit.

Re:Sara Golemon (2, Interesting)

SIGALRM (784769) | more than 7 years ago | (#15820141)

Yes, Sara is now at Yahoo [flickr.com] , at least the last I was aware of.

Re:Sara Golemon (1)

chug2k (942834) | more than 7 years ago | (#15820792)

yeah =). i worked with her too! she moved to yahoo a few weeks ago.

Golemon, I choose you! (0)

Anonymous Coward | more than 7 years ago | (#15820233)

I knew her when she worked at berkeley (I think she works for yahoo! now). She really knows her shit.

That doesn't surprise me. With a name like that she'd have to be a real digital monster.

5 of first 7 comments trolling (2, Interesting)

suggsjc (726146) | more than 7 years ago | (#15819997)

Ok, so 5 of the first 7 comments were trolling about how bad PHP is, insecure, buggy, etc (and I think they even managed to take a shot at Bush???)

I've used PHP for some very small applications/sites. Can anyone give an unbiased (almost impossible I know) state of affairs for PHP? I know that it is a pretty common tool, has its strengths and weaknesses. However, is it really that bad or is bashing it just the current /. thing to do?

Re:5 of first 7 comments trolling (0)

Anonymous Coward | more than 7 years ago | (#15820067)

People here like to bash things, it's true. People can easily write insecure code in any language with PHP being no different. And anyone can create an open source application, advertise it, and later when a security hole is found in this poor application PHP gets a bad name. Too bad, really, but I believe this is what some people refer to.

Re:5 of first 7 comments trolling (1)

not already in use (972294) | more than 7 years ago | (#15820100)

A lot of people who bash PHP are perl zealots or come from a strictly typed language like C and see loosely-typed code and lazy and ugly. Being loosely-typed makes it easy to use and as a result, the layperson can pick it up and write scripts. Of course, anyone doing professional work will looks at these scripts and their vulnerabilities and scoff at it, but they fail to realize that a lot of PHP that is floating around is not written by professionals. It is not a fault of PHP but the people who use it. Generally people using perl come from a *nix background and have better practice, but that does not make it a better language in itself.

Re:5 of first 7 comments trolling (3, Insightful)

creimer (824291) | more than 7 years ago | (#15820111)

However, is it really that bad or is bashing it just the current /. thing to do?

I think PHP has replaced Java as the favorite "kick the dog" language on Slashdot. IMHO, PHP is no different than any other language. It takes work to write consistently clear code that other people can understand.

Re:5 of first 7 comments trolling (1)

Schraegstrichpunkt (931443) | more than 7 years ago | (#15820794)

IMHO, PHP is no different than any other language.

You can't have a "humble opinion" about a statement of fact.

I work with PHP on a professional basis every day, and I will tell you that PHP has many shortcomings [google.com] that simply are not present in other languages.

Re:5 of first 7 comments trolling (1)

creimer (824291) | more than 7 years ago | (#15820875)

I was referring to the writing of source code. Not the pecularities of the language itself. If people can't read your source code, it doesn't matter that the langauge itself sucks. Of course, it's easy for a lazy programmer to blame the language instead of cleaning up the source code to make it readable.

Re:5 of first 7 comments trolling (3, Insightful)

sfe_software (220870) | more than 7 years ago | (#15822969)

If people can't read your source code, it doesn't matter that the langauge itself sucks. Of course, it's easy for a lazy programmer to blame the language instead of cleaning up the source code to make it readable.

I couldn't have said it better myself. I personally use PHP for many small applications. I also make sure to heavily comment my code, and I try not to obfuscate my code (it kills me that some people compete to see who can write the most obfuscated Perl, for example. Try interpreting or revising that code a year from now).

Many times I've had to revisit code years after having written it, and when there are no comments, it is difficult to see what exactly I was thinking at the time -- in *any* language. Non-descriptive variable names, or attempting to put as much code in as few lines possible, are, IMHO, bad practices.

Personally I see nothing inherently wrong with PHP. If I'm working with a web-based application, under Apache, using a MySQL database, PHP is the first thing that comes to mind. Image manipulation (now integrated) and HTTP features (headers, cookies, form data, file uploads, etc) make PHP an easy choice for many web applications. I've done all of this in Perl, and some in plain-old-C, but PHP makes these things so easy...

Of course it's not for everything. I try to use whatever platform/language is most appropriate for the application at hand. Sometimes it's C or C++, perhaps it's Perl, whatever - I use whatever makes the most sense for what I'm hoping to accomplish. It just happens that, on my Linux server, PHP often stands out as the best choice. When writing Windows applications, I use a hybrid of VB6 and (in the form of a back-end DLL library) C/C++. On the server, PHP most often comes out as the clear choice. Ease of use, abundance of built-in functions/features, ease of database-to-web integration, and relative security all make PHP a good choice for many of my projects and ideas.

Some have referred to PHP as "loose", and I admit sometimes it can be. There is no equivalent to Perl's "use strict", and it's easy to unintentionally leave an opportunity for a user to pass unexpected variables -- but as long as you are able to keep this in mind, it's not difficult to make a relatively secure PHP script. Just make sure any important variables are declared/set/validated at the start of the script. I admit, I do love Perl's "strict" module, since it leaves no question as to whether a variable's data is trustworthy... but PHP is a different language, with different features. You can't discount it as a viable language because of a single missing feature...

Re:5 of first 7 comments trolling (1)

jdbartlett (941012) | more than 7 years ago | (#15822262)

There's no such thing as a humble opinion.

I think that was Pratchett.

Re:5 of first 7 comments trolling (1)

jdbartlett (941012) | more than 7 years ago | (#15822268)

Especially now that Java is the language most university computer science degree courses are based on.

Re:5 of first 7 comments trolling (1)

Bob of Dole (453013) | more than 7 years ago | (#15820208)

If you know about its flaws (Lousy SQL handling and register_globals foremost among them), it's fine. No real security problems.
The problem (The reason it's got a reputation for bad security) is that many users don't know about these problems, so they don't write secure code. Stuff like:

$user=$_GET["u"];
$res=mysql_query("select data from users where userid=$user;");

(It's a SQL injection waiting to happen, what if I load this page with u="0;drop table users;"?)
The rapid uptake of PHP among new programmers is probably a good deal of the reason for this. It got popular fast, and a lot of people picked it up without much or any previous programming experience, so they don't know to watch out for stuff like this.

So, as someone who has written websites in PHP, Perl, and Python (Current favorite):
PHP is fine, but be careful. Make sure you know about good security practices. Get a good PHP book, try another language that does smarter DB handling (Perl and Python both do this in their standard DB libraries), or use a PHP library to help with it (I think PEAR has a DB wrapper that'd help)

Re:5 of first 7 comments trolling (2, Informative)

self assembled struc (62483) | more than 7 years ago | (#15820529)

(It's a SQL injection waiting to happen, what if I load this page with u="0;drop table users;"?)

Well, one would hope that the READ access you've given to the user you're connecting to the SQL DB with doesn't have the ability to run DROP TABLE.

It's about access control too.

I mean I agree with you on the fact that SQL injection attacks are easier in PHP, but lets face it, you can also design any language to be vunerable. PHP just makes it a little easier by not requiring some sort of connection library (and, in fact, not promoting one either)

Re:5 of first 7 comments trolling (0)

Anonymous Coward | more than 7 years ago | (#15823003)

Well, one would hope that the READ access you've given to the user you're connecting to the SQL DB with doesn't have the ability to run DROP TABLE.

I don't fully agree with the grandparent post, but I had to respond to your response... Many web applications require some kind of write access to the database. For example, a user database that allows new users to sign up.

Yes, it is good practice to allow your scripts no more access than is necessary. But many situations simply don't allow that level of control (for example, if your site is hosted on a shared server; often they only give you a single database user with full control over your particular database(s)).

However, I do agree that making a language so easy to learn can lead to bad programming practices, if a new "programmer" jumps into it without really learning all of the aspects of this type of programming. But that can't be blamed on the language itself -- just because PHP makes it easy to "screw up", doesn't make PHP bad. Hell, it's extremely easy to cause serious problems in C, if the programmer doesn't know how to secure certain things. Look at all the exploits people have found in different C programs over the years, in Windows, Unix, and other environments. And most of these were not caused by lack of experience on the part of the coders, rather, the exploiters found something the original coder overlooked.

Anyway, an easy programming language can't be the blame for the people who exploit programs/scripts written in the language. I don't blame the Internet (and hence it's ease of access to teens) for the actions perverts take. Nor do I blame Windows for the hackers/crackers/virus writers who target the platform so often that many PCs are "zombies" sending SPAM etc... ugh... that was a bad analogy. At least SOME responsibility lies on the creators of the platform...

Dammit, my whole argument just went to shit. I'll post this anon...

Re:5 of first 7 comments trolling (2, Insightful)

Touqen (968504) | more than 7 years ago | (#15820537)

Your example is slightly flawed as mysql_query doesn't allow the execution of multiple sql queries by default. And if you enable it for some reason, then chances are you think you know what you are doing.

Re:5 of first 7 comments trolling (1)

sfe_software (220870) | more than 7 years ago | (#15823051)

Your example is slightly flawed as mysql_query doesn't allow the execution of multiple sql queries by default.

Okay, try this:

$result = mysql_query("select password from users where UID = '$uid'");

Assume $uid was passed from a web form. And suppose you passed this to the script:

&uid=0'%20or%20'uid!=0

So, once parsed by PHP, you have: ...where UID = '$uid' or 'uid!=0'...

Just a simple example, but I have seen more complex queries manipulated in a similar manner if the user input isn't properly escaped/validated. In short, never pass user input to an outside program, database, or (especially) filesystem without validating the data first...

This is not to say I don't love PHP -- which I do -- it is just that in ANY language, it is easy to overlook some detail that some hacker/cracker may exploit. Especially if that person has access to the underlying code (though sometimes looking at the HTML form is enough information to exploit the underlying script...) so be careful with user input no matter what language you use for the back-end code.

Re:5 of first 7 comments trolling (3, Informative)

KidSock (150684) | more than 7 years ago | (#15820759)

For those who may be curious, the proper way to actually prevent SQL injections is to wrap anything coming in with a function that calls stripslashes() and mysql_escape_string() (or equivalent function for another db). For example, the function I use looks like the following (this also adds quotes around anything that is not numeric):

[sorry for the poor formatting, ./ is highly broken when it comes to posting code] // Quote variable to make safe
function quote_smart($value)
{ // Stripslashes
        if (get_magic_quotes_gpc()) {
                $value = stripslashes($value);
        } // Quote if not integer
        if (!is_numeric($value)) {
                $value = "'" . mysql_escape_string($value) . "'";
        }

        return $value;
}

Now you call this through sprintf like:

$res=mysql_query(sprintf("select data from users where userid=%s", quote_smart($_GET['u']));

Now this is perfectly safe from SQL injection. Anyone who has done real web programming knows all about this and knows that you need to deal with this sort of thing regardless of what language you're using.

Also, whenever you emit data that will appear in HTML you also need to wrap it. This time you just use the builtin htmlentities() function like:

echo "<input name=\"u\" type=\"text\" value=\"" . htmlentities($user) . "\">\n";

This prevents cross site scripting. Again, no different from any other language.

PS: IMHO if someone goes out of their way to claim something "sucks" they probably don't know what they're talking about. Try the other languages and read the documentation so that you can evaluate which is best for your project.

Re:5 of first 7 comments trolling (1, Troll)

larry bagina (561269) | more than 7 years ago | (#15821262)

you're inadvertently pointing out more php failures.

  • magic_quotes_gpc (do I need to say more?)
  • magic_quotes_sybase (if enabled, stripslashes() won't fix it)
  • mysql_escape_string() vs mysql_real_escape_string()

When PHP was built, as a set of perl scripts, perl used DBI for databse stuff. And it worked. I don't understand why php fucked it up and then created all the above problems to deal with it.

Re:5 of first 7 comments trolling (1)

pinkstuff (758732) | more than 7 years ago | (#15821317)

"Now this is perfectly safe from SQL injection. Anyone who has done real web programming knows all about this and knows that you need to deal with this sort of thing regardless of what language you're using."

Point taken, in that a lot of web scripting languages you have to be careful with SQL injection - but careful with your statement, I do 'real web programming' and do not have to worry about this per say, as I am using a full MVC framework (struts). If you are truely seperating the 'V' from the 'M' and the 'C', then the web page should never have access to raw SQL. Granted for small apps a MVC can _possibly_ be overkill.

Re:5 of first 7 comments trolling (1)

jdbartlett (941012) | more than 7 years ago | (#15822457)

Fortunately, the Zend Framework will soon come to the rescue. In the meantime, I have written my own PHP DAL. It felt like reinventing the wheel, but my other options at the time were all unstandardized frameworks that were either too restrictive or just poorly written.

RoR is looking more and more attractive. I'm currently considering porting the next version of the application for which I made my own framework.

Re:5 of first 7 comments trolling (0)

Anonymous Coward | more than 7 years ago | (#15821383)

That code is still as ugly as last time! [slashdot.org]

Braces are syntax to mark the beginning and end of a code block, otherwise pointless. I also eliminated a redundant call to sprintf() and stop using is_numeric() when ctype_digit() is the function you want.

function quote_smart_digit($_){
if (get_magic_quotes_gpc()) $_ = stripslashes($_);
if (!ctype_digit($_)) return("'" . mysql_escape_string($_) . "'");
return $_;
}
$res=mysql_query('SELECT data FROM users WHERE uid = ' . quote_smart_digit($_GET['u']) . ';');

Or using PDO:

$res=$db->query('SELECT data FROM users WHERE uid = ' . $db->quote($_GET['u']) . ';');
Using PDO bound parameters, you don't even need to call the quote method yourself.

Re:5 of first 7 comments trolling (1)

KidSock (150684) | more than 7 years ago | (#15821522)

Is it just Firefox on Linux or does that code formatting look bad for anyone else? The code is double spaced. What happened to simple pre style? I would think with all the programmers on ./ that more people would care about how code formatting looks.

Also, regarding sprintf, if your query has 5 parameters using sprintf is a lot easier and it's probably more efficient.

Re:5 of first 7 comments trolling (1)

jdbartlett (941012) | more than 7 years ago | (#15822425)

Looks fine for me, except the lack of preformatted text tag has removed indentations.

Also, semicolons aren't needed at the end of MySQL queries in PHP. But that's nothing to do with the code's presentation!

Glad you didn't mention cross-site scripting (1)

jdbartlett (941012) | more than 7 years ago | (#15822411)

Some people also use a function to strip out less than/greater than signs from data (or simply use htmlspecialchars/htmlentities) before adding it to a database. Their desire is to prevent cross-site scripting attacks. This is a lazy hack. A better way to combat cross-site scripting is to apply htmlentities to data being pulled out of the database for display. If you are using "real" W3C DOM scripting methods and not innerHTML, you can simply add the data as-is (making sure your JSON methods slash out any would-be JavaScript escape characters)--"textContent" will display would-be markup as text.

Re:5 of first 7 comments trolling (1)

sfe_software (220870) | more than 7 years ago | (#15823030)

For those who may be curious, the proper way to actually prevent SQL injections...

I'm not negating your point, as I do agree with it. But it can be put much more simply: a script should NEVER trust ANY user input, period. Anything passed to the script should be validated; make sure a value is within range, or otherwise is an expected input. If the input doesn't match some predefined pattern, it should be rejected.

I do love PHP, and I use it quite frequently, but Perl has the "scrict" module that I personally love. Any variable modified by anything outside the script itself is marked as "tainted", and you have to do some kind of validation before Perl will even let you use it. It is a great fail-safe IMO, so even if you happen to overlook or forget a particular variable, Perl simply won't let you use it until Perl is satisfied that you've checked it...

Other than that, it's not that difficult to write safe PHP code. Just check any variables with user input, and any variables a user might attempt to set (even if you aren't expecting them to). Also, globals are not valid within a function, so be more careful within the top-level of a script; as long as you validate any data passed to a function, a user can't override variables within that function.

register_globals? (1)

Mateo_LeFou (859634) | more than 7 years ago | (#15822004)

Why does this nit always come up? Sincere question, I assure you: pretty much *every book or tutorial on PHP has "Turn Off register_globals" in the first chapter." And it's off-by-default in the last few major versions. I remember some popular (but crummy) big apps like osCommerce required(d?) it and when I discovered that (in 2003!) I about fell out of my chair. And in agreement with another poster, SQL injection is basically-impossible in any language when you set up your privs intelligently.

rethinking (1)

Mateo_LeFou (859634) | more than 7 years ago | (#15822027)

I thought about that last bit a little more and realized there are plenty of situations where simple read-access could be dangerous... well, I use PEAR::DB anyway.

Re:5 of first 7 comments trolling (1, Interesting)

Bogtha (906264) | more than 7 years ago | (#15820348)

I believe PHP has a bad reputation for three reasons:

  • It's a language used by a lot of beginners, so you see a lot of beginner code written in PHP.
  • It's historically had some really poor design decisions that have led people into making grave mistakes.
  • There are a number of better options available that people tend not to use because PHP has greater mindshare and therefore more hosting companies make it available. By comparison to the better options, PHP is crap.

They are gradually fixing the language and the poor design decisions, but change in the language happens slowly, change in the developer attitudes happens even more slowly, and change in the perception of both of these happens glacially slowly.

If you have control over your hosting arrangement, I'd strongly recommend trying out alternatives like Django (Python), Turbogears (Python) or Rails (Ruby) before committing to PHP any more than you already have. But if you need to work with bog-standard cheap web hosts, then stick with PHP, it's not that bad.

Re:5 of first 7 comments trolling (0)

Anonymous Coward | more than 7 years ago | (#15821223)

it's not like php5 has been around for a year which supports oop or the register_globals issue is caused because web hosts go AGAINST the default value of off because beginners need it on.

frankly php made mistakes in the past and the developers are doing what they can to fix them. the problem is webhosts aren't willing to loose the old-style because it's simpler and means if it's easier to make websites it makes money.

Re:5 of first 7 comments trolling (0)

Anonymous Coward | more than 7 years ago | (#15823115)

I believe PHP has a bad reputation for three reasons:

I don't fully disagree with you, but I'll still address each of your points individually.

It's a language used by a lot of beginners, so you see a lot of beginner code written in PHP.

I do not have an argument for this one. PHP is among the easiest to pick up on as a beginner. Personally I was already familiar with C and Perl before PHP came out (well, PHP3, when I discovered it), but I know a lot of beginners do jump right into PHP...

It's historically had some really poor design decisions that have led people into making grave mistakes.

I'm not sure what "poor design decisions" you are referring to. Okay, register_globals *can* be a bad thing, but it is not inherently bad, IMO. If anything, the changes in default behavior of the language has been more of a problem for me (eg, register_globals, or the order of cookie/get/post data)...

There are a number of better options available that people tend not to use because PHP has greater mindshare and therefore more hosting companies make it available.

This is the one I had the biggest problem with. I use PHP for many projects, not because it has "greater mindshare", but because it is often the best choice for the project I have in mind.

Most hosts I've been with (and currently I run my own server) have offered Perl, PHP, and (if you knew what you were doing) C/C++. PHP is admittedly much easier to get started with, but that alone does not make it a bad choice.

I think the biggest problem with PHP is (and you will likely agree) that it has a low "barrier of entry". In other words, a beginner can get started with PHP much more easily than with Perl, C/C++, or Python. Thus, the beginner, having no real experience, can make huge mistakes (trusting user input without validation, etc). But because it's easy doesn't mean the language itself is at fault (hell, it's easy for a first-time driver to kill someone in a fast car, but we don't blame the manufacturer do we? Sure, the driver should have first learned to drive in a slow, 4-cylinder manual-shift car, but the maker of the fast car can't be blamed for the mistakes the driver made?)

Anyway, PHP can be a quite powerful language. If I have a simple idea for a web page that shows data from a MySQL database, PHP is the easiest way to accomplish this. I've done this in Perl (somewhat more difficult) and C (much more difficult), and PHP is the easiest. Especially if the application requires file uploads, image manipulation, custom HTTP headers and cookies (my latest project involves all of these, a photo-sharing site). PHP just makes sense to me for this type of project. Sure, I have to make sure to validate user input, etc, but none of this makes PHP a bad choice.

The biggest problem is, as mentioned earlier, the fact that PHP is easy for beginners to learn. The solution, however, is not to make PHP harder -- nor is it to force new developers to use another language. The solution is to try to educate new developers about the inherent problems with *any* web application. Don't trust user input (or any external data). Validate everything that originates outside the script (even data obtained from other programs/scripts you have written). Handle all error conditions (never ignore an error, and never assume something worked as expected). Finally, never assume anything about your environment -- many conditions and factors may differ between operating systems, or versions of an OS or programming language, etc. Check everything.

And these tips apply to every programming language. The only argument you have is that PHP is easier to learn, therefore you will have more inexperienced coders entering the scene. But my point is simply this: that fact doesn't make PHP inferior to other languages. For the experienced, something like PHP is quite welcome, for its simplicity and abundance of features. It makes things easier. If that also makes it easy for the inexperienced to make mistakes, then so be it. They will learn more from those mistakes than they ever will from you or I telling them what to watch out for...

Yes, its really that bad. (0)

Anonymous Coward | more than 7 years ago | (#15820364)

PHP is missing alot of functionality, impliments alot of things in very bad ways, and has never been written with security in mind. This is a bad combo, and some of the bizzare PHPisms will really warp you way of thinking and make it much harder for you to go to any other language on the planet (like making "arrays" actually be some monster combination of arrays, hashes, stacks, heaps, and queues).

Re:5 of first 7 comments trolling (2, Insightful)

nicklott (533496) | more than 7 years ago | (#15820365)

Ok, so 5 of the first 7 comments were trolling about how bad PHP is, insecure, buggy, etc
and that's even now CyricZ has stopped posting!

Why I don't like PHP (0)

Anonymous Coward | more than 7 years ago | (#15820397)

Comparing PHP with Perl, PHP has no equivalent of "use strict". Consequently, there are simple programming mistakes which Perl will catch but PHP will not. Newbies think that not having to declare variables is a time-saver. Experienced programmers know that the few seconds gained by not having to declare variables, is lost thousands of times over when you have to find a bug that would never have arisen if undeclared variables had been caught by the language.

If you never need to write more than a dozen lines of code, PHP is fine. If you need to do anything more complicated, look elsewhere.

Re:Why I don't like PHP (2, Insightful)

dr. greenthumb (114246) | more than 7 years ago | (#15821609)


Comparing PHP with Perl, PHP has no equivalent of "use strict".


Yes there is: error_reporting(E_STRICT);

Re:5 of first 7 comments trolling (0)

Anonymous Coward | more than 7 years ago | (#15820462)

PHP is no better or worse than any other script language for creating simple dynamical web pages. Things get more complicated, security wise, when databases and user input are added. Just be conscience with what you are coding like any other language.

Re:5 of first 7 comments trolling (0, Troll)

mobby_6kl (668092) | more than 7 years ago | (#15820472)

Mod parent down, preferably Troll. Of all posts up to this (parent one), PHP is only mentioned once in what one might say a negative way (it asks about a PHP security book, doesn't directly imply anything about php). The only post about bush says something like "slashdot sucks with all the ani-bush articles".

PS. PHP sucks donkey balls.

Re:5 of first 7 comments trolling (0)

Anonymous Coward | more than 7 years ago | (#15820506)

--
Think of someone of "average" intelligence. Then think... half the world is dumber than that.


Your sig is wrong...average != median [wikipedia.org] .

Re:5 of first 7 comments trolling (1, Insightful)

Anonymous Coward | more than 7 years ago | (#15820670)

It's pretty bad. To begin with there's therandom() naming_scheme(). On top of that there's the lack of namespace support, so we have str_pad and strlen rather than something like:

use str;
$res = pad($var, len($string), ' ');

The devs should add namespaces and camelCase all function names (Currently function names are case insensitive). They could even have a secondary function table with aliases for backwards compatability, since simple sed commands or search and replace are apparently too esoteric for the PHP userbase :-o



You know, there's simply too much wrong to list it all. Most of the gripes are against PHP4 which I haven't used in 2 years, hopefully PHP5.2 should sound the death toll for PHP4. Overall I'd like to ditch PHP and use a cleaner dynamic language with compilation targeting a JIT'd VM (No, not one designed for languages with static type systems).

I second (1)

jdbartlett (941012) | more than 7 years ago | (#15822493)

Absolutely. More than anything else, these are exactly the things that are driving me away from PHP. magic_quotes* issues can be coded around (though they shouldn't have to be), but when I have to keep php.net open all the time to make sure a function is still called what I think it should be (often I'm still wrong by an underscore), I'm not a happy developer.

Re:5 of first 7 comments trolling (1)

ChronoFish (948067) | more than 7 years ago | (#15820767)

It seems that anything that takes off and allows beginners to gain traction quickly is beaten down by the purist. Windows is beaten down because "only an idiot would need a GUI" - it's that type of attitude that hates PHP or anything else that's more about being productive than being about the technology.

Personally I've been programming in both the *nix and Win* environment for 10 years. I find PHP a fast, fun, language that allows me to build solid (mostly web) apps quickly. The language constructs "just make sense" to me (rather than something like Perl) and I like the fact that I can do OO programming with it from the perspective that every object is a black box rather than the tightly typed academic OO of Java. It's a function of OO allowing you to do more rather than OO protecting you from yourself.

The security issues are there - no doubt. And beginners code is crap. Of course beginners code is crap no matter what language they use.

If you enjoy C programing and find it rediculas that you have to jump through hoops for proper memory managment then I think you'll find PHP a great language. If you love Java or using the STL in C - you'll probably hate PHP because "all the fun part" is already done for you. If you love languages because you like the challenge of mastering a complicated process - then PHP is going to seem gimicky and too simple. But if you enjoy spending more of your time on the problem your trying to solve rather than on mastering a new language then I think you'll find PHP well suited for you.

If you are a good programmer I don't think you'll find many limits to PHP. If you rely on throw-catch and the language to prevent you from adding letters unless you created a class that will allow you to explicitly do so - then I think you'll hate PHP.

If you like a small functional language that is robust - then head towards PHP. If you like extensive languages that rely on extenstions and class structures taken to extreams, then Java (and maybe Ruby?)is your friend.

And here is something that is sure to generate a flame or two. I would love to see a PHP implementation of true "embedded" environment - i.e. at the microprocessor level.

uPHP anyone?

-CF

Re:5 of first 7 comments trolling (0)

Anonymous Coward | more than 7 years ago | (#15823178)

...it's that type of attitude that hates PHP or anything else that's more about being productive than being about the technology.

I agree with your entire post fully. I just wanted to comment on some of it.

First, about PHP being easy to grasp, and not so much about the technology: You are absolutely correct. PHP originally stood for "Personal Home Page". The creator (who's name I cannot recall) originally wrote PHP for himself, to help automate certain tasks he wished to accomplish on his own, Personal Home Page.

Personally I've been programming in both the *nix and Win* environment for 10 years.

I'm in about the same exact boat. Back in 1997, I started writing Windows softare, and shortly after I found myself in need of a web server. It was then that I learned of Linux, and I quickly took to it. To this day, my sites are all hosted on a Linux/Apache webserver, and most of my web applications are PHP.

If you enjoy C programing and find it rediculas that you have to jump through hoops for proper memory managment then I think you'll find PHP a great language.

Personally, my Windows programs are a hybrid of VB and C. The front-end (eg, the windows & graphics you see) are all done in VB. IMO, it's the easiest way to create a Windows application. But the "real work", eg any audio processing, is handled by a DLL written in C. Why? Well, VB can't handle heavy mathematics, but is capable of calling a DLL, passing data and parameters, etc.

So in short, I try to use the best language for the task. On my server, PHP is quite often the best language. I use Perl quite a bit, and even some shell scripts (bash), but if I want a web page to be able to access my MySQL data, PHP always seems like the easiest way to accomplish that goal. To include a common header/footer on all pages of a site, PHP is easy. Sure, I could use SSI includes, but PHP allows me to, whenever I feel like doing so, add additional functionality to a page.

If you like a small functional language that is robust - then head towards PHP.

Agreed. PHP can handle image manipulation, filesystem functions, HTTP headers and cookies, and more, without relying on any external libraries. File uploads, form post data, etc, are all handled with no extra effort.

If you like extensive languages that rely on extenstions and class structures taken to extreams, then Java (and maybe Ruby?)is your friend.

I have nothing against other languages (and, I'm not even familiar with Ruby). But for me, the fact that PHP handles so much without relying on external libraries, is enough to make it my first choice for many applications. Python is one I don't particularly care for, only because of its strict syntax... I only know that PHP can often be the choice that allows for the fastest deployment of an idea, in many cases (certainly not all). It's also quite easy to maintain, if you comment and format your code appropriately. When mixed with tons of HTML/CSS/JavaScript it can be a bit more difficult (and I am quite guilty of this myself), but that's not a problem with the language itself, rather with the programmer, or laziness of said programmer... :)

Re:5 of first 7 comments trolling (1)

imroy (755) | more than 7 years ago | (#15820822)

Apart from a google search for "PHP sucks", here's a few I have bookmarked:

  1. Experiences of Using PHP in Large Websites [ukuug.org] - PHP suffers from "oversimplification leading to excessive complexity".
  2. What I don't like about PHP [bitstorm.org] - a general shopping list of complaints.
  3. "PHP IN CONTRAST TO PERL" [tnx.nl] - How PHP is a mess and Perl does more with less.
  4. List of PHP's shortcomings [perl.org] from perl.advocacy
  5. Re^2: Is Perl a good career move? [perlmonks.org] on PerlMonks

Re:5 of first 7 comments trolling (1)

lewp (95638) | more than 7 years ago | (#15821053)

PHP has a lot of little language quirks that can bite you on the ass pretty regularly while you climb the learning curve. It's easier to get started writing bad PHP code, then distribute it to a mass audience, than just about any other web scripting language. Those two things are responsible for 99% of the bad blood towards it. From me it gets some bonus points in the hate column for basically turning into Java with dynamic typing in PHP5, but I'm pretty anti-Java, and I guess other people like that.

About 70% of my job is PHP programming, and I can live with it. Still, when you apply all the painfully learned practices to make PHP suitable for larger scale development and realize how far you've come from the simple promise of PHP, you can't help but wonder why anyone would ever choose the language over something like Python (or Perl, Ruby, etc.) for all but the tiniest scripts. In my case, it's because I'm buried under a pile of legacy code that was, unfortunately, not written with maintenance in mind.

Re:5 of first 7 comments trolling (1)

Firehed (942385) | more than 7 years ago | (#15822049)

I've just started a decent sized coding project in PHP, and since I'm well aware that it's easy to write Swiss cheese-code, I figured I'd just pick up a book on PHP security. Two actually. They explain how to fix or avoid the stupid problems that unsuspecting n00bs tend to make (and, indeed, I would have), and write code that doesn't require register_globals to be enabled and guards against those ubiquitous SQL injection attacks. Money well spent.

Are there quirks? Certainly. I've had a couple functions give me some headaches. Nothing horrible, but not my idea of fun either. The problem is that since it's relatively easy to write for (at least simple code) and interfaces very easily with MySQL, it's also easy to not guard against security holes if you don't know where to look for them. How many first-timers are going to realize that a user could dump " p' OR 't' = 't " into an input and gain access without a password? Or run a DROP query? So, they implemented magic_quotes. If it worked perfectly and reliably, great, but that's not really the case, so when people rely on it and don't bother running a DB-specific make-safe command (like mysql_real_escape_string), they end up with half a security problem. By nature, any language that's fairly easy to learn is also going to be easy to screw up, and since it's impossible to predict how coders are going to use it, it's impossible to properly safeguard against the problems (and, of course, doing so will generate bad or lazy coding practices).

Any coding language will have natural flaws that you need to guard against. It's the fact that PHP is so popular that you get so many clueless coders not avoiding those flaws. Look at Windows. Who'd attack it if it had 10% of the market share? Linux or OS X aren't necessarily more secure (or, rather, any harder to exploit), but they're not targeted. Just like malicious users don't go after sites coded in something else when there's ten times as many out there in PHP. PHP is the Windows of web coding languages - it's not necessarily any worse, it's just more targeted, and has attracted more senseless users.

Re:5 of first 7 comments trolling (0)

Anonymous Coward | more than 7 years ago | (#15823224)

It's the fact that PHP is so popular that you get so many clueless coders not avoiding those flaws. Look at Windows. Who'd attack it if it had 10% of the market share?

This is a point I've been trying to drive into a few people. Windows is attacked not because it's any less secure (which arguably it may be), but mostly because it's a large target. It's the same reason I write Windows software for a living - there is a significantly larger audience than I would have with Linux, Unix, or Mac software.

Likewise PHP is targeted because it is not only widely used, but is often used by the inexperienced (eg, those more likely to have left security holes). Much like how the typical Windows user will be less likely to have patched the latest hole, compared to a *nix or Mac user.

I personally don't think of PHP as a bad thing at all. In fact I use it quite a lot on my various web sites, especially those requiring access to MySQL, or form/upload data. PHP makes these things easy.

But it is this same reason that makes PHP a target. Beginners tend to take up PHP more easily than other languages, and beginners usually have no knowledge of how scripts are usually exploited; they tend to trust user input, or data obtained from outside sources, not realizing just how many people are out there waiting to exploit their application. They aren't aware of just how these exploits work, and therefore don't know what to even check for.

I'm not saying you should learn a "harder" language first, but you should learn about how exploits typically work, and what to look for, before you start deploying programs/scripts in *ANY* language. PHP just makes it easier to "jump right in" and introduce working, though potentially exploitable, scripts to the world. That doesn't make PHP bad, any more than automatic transmissions, which make it easier for idiots to start driving and making (possibly fatal) mistakes, are to blame. (that's the best analogy I could think of at the time :)

Re:5 of first 7 comments trolling (0)

Anonymous Coward | more than 7 years ago | (#15821093)

and I think they even managed to take a shot at Bush???
Well, it's common knowledge that register_globals was a secret Bush administration initiative to control the Internet through SQL injection.

Proof. [yahoo.com]

Re:5 of first 7 comments trolling (0)

Anonymous Coward | more than 7 years ago | (#15821169)

However, is it really that bad or is bashing it just the current /. thing to do?

If its not mod_perl it is automatically inferior on slashdot. Only perl is acceptable, nothing else. Perl is the holy grail of scripting languages, it is infallible, perfect and suited to every task, no matter what.

Its all about kissing slashass and the pathetic mod system that ruins the continuity of every thread here.

Forget that perl's performance is abysmal. It seems to be the only place I see static versions of dynamically generate pages to reduce server load. (Awstats, slashcode... at least Awstats does what it says on the box, which we cannot say for slashcode...)

PHP is a horrid language because slashcode is written in perl (even though its performance is abysmal and buggy as hell) but slashdot uses perl, so perl is god.

PHP does not sound as cool as Ruby on Rails, therefore it is not as good.

So lets get back to bashing PHP we know we'll never get tired of it and there is guranteed to be a weekly php bashfest on slashdot. I can't wait for the next one, its just so unpredictable I never know what to expect.

How long did this post take to process on submission? Well over 5 seconds... See? Perl is blazing fast and perfect in every way.

Ruby zealots are envious (2, Insightful)

Anonymous Coward | more than 7 years ago | (#15821391)

5 of the first 7 comments were trolling about how bad PHP is, insecure, buggy, etc


That's because there are people who are trying to reinvent a 40+ years old language who do not like the way PHP has taken over the web. They simply hate the way sites with page names ending in ".php" outnumber sites with pages names ending in ".rb".


Those people are too stupid to understand Lisp, too ignorant to know the good points of Lisp, and too close-minded to try learning how to use Lisp, therefore they tried to create a hybrid language by attaching some of the Fortran syntax to Lisp, creating Ruby in the process.

Try Ruby (1)

jdbartlett (941012) | more than 7 years ago | (#15822602)

...outnumber sites with pages names ending in ".rb"

This is a poor excuse for a stab at Ruby. Most Rubyist sites tend to be powered by RoR, which in part explains why you haven't seen many ".rb" pages around. Also, how would Rubyists complain about PHP "taking over" the web (implying this should be the "domain" [pun] of Ruby powered sites) when so few of them were introduced to Ruby before 2000? Though PHP and Ruby were introduced around the same time, it took Ruby slightly longer to reach an English-speaking audience. It didn't really take off until pickaxe was released.

That's right, Ruby is just a horrible mishmash of Lisp and Fortran. Uh-huh. And PHP is a horrible mishmash of Perl (and Perl is a horrible mishmash of shell scripting, C, AWK, and that holy untouchable language Lisp!) Ruby is not the cause of PHP's poor reputation. PHP is the cause of PHP's poor reputation. I speak as an open-minded 6-year PHP developer.

<sarcasm>All these newfangled languages are just for people who are too stupid to understand machine code, too ignorant to learn the good points of machine code, and too closed-minded to try learning how to use machine code. Therefore they tried to create some sort of "higher level" language to escape their ignorance. They might call it programming, but it's not machine code!</sarcasm>

Re:5 of first 7 comments trolling (1)

b17bmbr (608864) | more than 7 years ago | (#15823296)

if it does what you need, then it's a good tool. for you.
if it can help speed a project along, then it's a good tool. for that project,
if it's stregth's fit with your needs, then it's a good choice.
it it's weaknesses aren't neceassrily a problem, then it's a good choice.
you wouldn't write a kernel in java or python, and likewise you wouldn't write a log file parser in C. there's a reason why millions of web sites out there are based on LAMP. and it isn't because they're "free". a good programmer writes good code in whatever language they use. and a good programmer uses the right tool for the job.

Embedding PHP in Python web applications (1)

Bogtha (906264) | more than 7 years ago | (#15820221)

If you're interested in this, you'll probably be interested to know about Ian Bicking's work on embedding PHP in Python web applications [ianbicking.org] via PHP's FastCGI support. It's only in the experimental stages, but it's very promising, especially for developers like me who develop with Python but need to support legacy PHP code.

been there done that (1)

jaimz22 (932159) | more than 7 years ago | (#15820237)

i've got this book, it's very well written and easy to follow. i recommend it.

not another (1)

Nexcet (792231) | more than 7 years ago | (#15820341)

i hate when people post about php books in slashdot.
it's soo damn overrated.

all these php books.
php.net [php.net]

Save $18.50 by buying the book here! (1, Informative)

Anonymous Coward | more than 7 years ago | (#15820371)

Save yourself $18.50 by buying the book here: Extending and Embedding PHP [amazon.com] . And if you use the "secret" A9.com discount [amazon.com] , you can save an extra 1.57%! That's a total savings of $18.99, or 38.58%!

PHP is not just for the web (4, Interesting)

KidSock (150684) | more than 7 years ago | (#15820598)

Yeah, so PHP stands for "Personal Home Pages" but that's is an historical misnomer now. PHP has a CLI binary that can be used to run scripts on the commandline. Obligatory "hello world" follows:

    !#/usr/bin/php
    echo "Hello, world!";

Now consider that PHP ships standard on virtually every Linux distro and comes with a large assortment of libraries. You can write LDAP scripts, do IMAP, generate images, the list is loooong. It amazes me that PHP isn't used more in corporate envirments. PHP is easy to use, arrays are surprisingly useful, and you can do a little OO (which is just the right amount IMO). And something that a lot of people take for granted is that the documentation on php.net is great. Everything is on one place unlike other languages (e.g. Python) where you just get redirected to every little sourceforge scribble and wiki there is.

I'm a C person. I'll continue to use C for heavy lifting but you also need a good scripting language. I just wrote a Zend extension to interface with some of my C work and it exceeded all of my expectations.

If you're looking for the lastest hot new "technology" then Ruby is a good buzzword. Otherwise, if you're just looking to get work done, so you can go home and play with your kids, PHP is a workhorse.

PS: I don't know spit about this book but the tutorial on writing extensions on the Zend website was pretty good. Good enough for me anyway.

Re:PHP is not just for the web (1)

OakDragon (885217) | more than 7 years ago | (#15820687)

In 1997, they "retro-fitted" a new name to it: PHP: Hypertext Preprocessor, and thus it now sits (linguistically) with GNU, et al.

Re:PHP is not just for the web (1)

Andrew Kismet (955764) | more than 7 years ago | (#15820703)

The name was retconned to "PHP Hypertext Preprocessor". Even a quick wiki will tell you that.

Re:PHP is not just for the web (1)

KidSock (150684) | more than 7 years ago | (#15820775)

I did. Wikipedia's PHP page says "Personal Home Pages".

Re:PHP is not just for the web (1)

linvir (970218) | more than 7 years ago | (#15820769)

!#/usr/bin/php
echo "Hello, world!";
I think you meant:
!#/usr/bin/php
<?php
echo "Hello, world!";
?>

GAH! (1)

linvir (970218) | more than 7 years ago | (#15820783)

That'll teach me to copy/paste. I left his shebang mistake in there too. A thousand apologies. I tried to be the King of Pedantry, and I failed.

Re:GAH! (0)

Anonymous Coward | more than 7 years ago | (#15821372)

Actually, I think you'll find that Pedantry is a principality, not a monarchy.

Re:PHP is not just for the web (1)

rycamor (194164) | more than 7 years ago | (#15820859)

Yes, when you think about all the capabilitise you get in such a small package, it puts most large application libraries like Java to shame.

I use PHP extensively as a Unix scripting language. It performs quite well, even running a collection of scripts for an extended time as a daemon. You might be surprised how efficient PHP is at handling very large arrays running in memory.

And yes, it is a workhorse. It may have a few oddities and rough edges, but mostly it just stays out of the way and lets you work.

Re:PHP is not just for the web (1)

azuretek (708981) | more than 7 years ago | (#15821521)

Is this a troll? I just can't tell what's a joke and what's serious anymore. PHP fans and haters are far too ambiguous...

I'm a PHP developer but I also write Perl and C as part of my daily job. I use PHP for all my web development, anything that has a web front end will undoubtedly be written in PHP though I have done Perl and C for web (I still hate cgi). Perl I use mainly for sysadmin type applications, easy way to automate my tasks when they're more complex than a simple BASH script will do (database connections and socket work mainly). I use C when I'm writting applications that need to be quick and light. Creating servers, forking and handling memory just can't be done with perl or php with any kind of grace or speed. Though I have created servers and daemons and other such things with perl and PHP I stick with C for anything that needs to run in the background as a daemon or as an interactive application.

Everything has it's place, and each tool is good for what it's intended. If you want to be a well rounded programer pick a few languages that you think will fit your needs and learn them well.

Re:PHP is not just for the web (2, Insightful)

Decaff (42676) | more than 7 years ago | (#15821975)

I'm a C person. I'll continue to use C for heavy lifting but you also need a good scripting language. I just wrote a Zend extension to interface with some of my C work and it exceeded all of my expectations.

If you're looking for the lastest hot new "technology" then Ruby is a good buzzword. Otherwise, if you're just looking to get work done, so you can go home and play with your kids, PHP is a workhorse.


No, it isn't.

Sorry, but this post sounds very blinkered. You are ignoring the 'elephant in the room'. The dominant thing that many people pretends does not exist.

The workhorse is now Java. It has unmatched support for databases, unparalleled library support. There are so many tools and frameworks for Java that anyone can find something suitable. There are rich and powerful open source and commercial IDEs. Java is now the major language for 'heavy lifting'.

Ruby is not the hot new technology. It is simply the hot new topic of conversation. There is a big difference. Ruby has neither the performance or the capabilities (such as internationalisation) for major use. It has virtually no significant presence in commercial development and has hardly impacted the dominance of PHP for open source web development.

It is sad to see how many people comment on major international forums who aren't prepared to look beyond their own personal experience, and get a real feel for what is actually happening in the industry.

Re:PHP is not just for the web (1)

bytesex (112972) | more than 7 years ago | (#15823426)

"The workhorse is now Java. It has unmatched support for databases, unparalleled library support."

Ouch. That hurts. That's just not true. You may wish it to be true, but it isn't. Not when you compare it to CPAN.

Antimatter for teh haters (3, Interesting)

weasello (881450) | more than 7 years ago | (#15820708)

A lot of PHP bashing going on; I'd just like to chip in my 2 cents on the language (and demonstrate a mild interest in the book). I was big on programming when I was younger - by 14 I had written an adventure game in Basic and I invented a DOS-based graphical application that is eerily similar to Flash (two stickmen and some props on the screen with keyframes and interpolation tracking). Needless to say I was well advanced of my classmates throughout highschool. I also wrote a Chess AI (who hasn't?) in C. But that was the end of it - about 10 years ago now. I longed for programming but Real Life(tm) got in the way and other career paths curbed my free time. Needless to say I had lost a lot of skills and I don't even know what OOP stands for, but getting into the blogging world and creating a custom website to house it resulted in me having to learn some sort of web-based programming. I have to say that PHP was beautifully easy to (re-)learn and I was back in the programming seat with a big grin on my face with just a few weeks of self-learning (by looking at examples and open source, no books). I'm praising PHP as a very easy to learn, easy to use starting point for all my would-be programming friends.

[very offtopic] (1)

linvir (970218) | more than 7 years ago | (#15820819)

Wow. That'd have been the story of my adolescence to the letter, if my otherwise fine secondary school hadn't been an IT wasteland. I got a start in BASIC back in primary school, and was eager to take it further when I moved on. The first chance I got, I logged in and opened the first recognisable name I could see: Visual Basic.

You there! Did I tell you you could run that? No? Well then close it!

And thus endeth my programming career until the lazy days of university some eight years later.

Re:Antimatter for teh haters (1)

weasello (881450) | more than 7 years ago | (#15821312)

Note: my Flash precursor and my highschool coding was in Turbo Pascal (ftw).

I hate PHP. (1)

tehshen (794722) | more than 7 years ago | (#15821323)

Many people just use PHP because it's popular and because they can't be bothered to use anything else. Which is a shame, because it doesn't deserve to be, and many people should be much better than that.

I remember when I picked up PHP. It was brilliant. Look at me, I can create dynamic web pages! I could do for loops, and while loops, and print out numbers without using JavaScript! And now, I can take parameters in from $_GET[], and make a proper website in only one file! :D! I got a website with Tripod (urgh) and that gave me a MySQL database, so I could now make proper sites! PHP was brilliant, and I was excellent with it. Wow, I was on top of the world.

Seriously, I was ecstatic like that, but bear in mind that I only knew C and HTML before this. Oh, and BASIC, but that's just embarrassing.

We were happy, PHP and I. We were nice and friends. Why should I bother to learn something else when PHP was accomplishing what I wanted just fine, thank you very much?

Well, I can now safely say that dumping PHP was a great step forward for... pretty much everything really.

I was so happy with what I was doing that I was willing to see past PHP's shortcomings. It was easy to learn, so I learned it and stuck with it. But PHP has a lot of shortcomings. Sure, I don't see why it's stripslashes() but strip_tags(), the underscore's being there is just random, but it's OK, I could just look it up.

I didn't realise how slow I was coding, from all that looking at the docs.

These days, I can look at PHP and go "what the hell were they thinking?". While it's alright to look at the documentation when you're learning a language, it's not right if I keep having to look at them several years later, to find out if it's array_length() or arraylength() or arrlen() or count(). It's count(). I relied on magic quotes to do all my work for me, when now I see them as a clutch, a poor clutch at that, and now I use taint checking. I draw circles and bang my head on them when I realise there's STILL no namespaces. I laugh at all PHP's inconsistencies, wondering why it's strtolower but str_replace and bin2hex, wondering why it's $haystack, $needle arguments and other times $needle, $haystack. The PHP devs must talk to each other as much as the Slashdot editors do (ooh, low blow).

Seriously, PHP is so bad it's silly - there's just no reason for people to use it when there's far better out there. I don't have to talk about PHP's typing, or its syntax, as they can be dismissed as just a personal preference. I just don't understand why it's so inconsistent. A good language shouldn't be inconsistent.

(Oh, and I don't see what's so special about the PHP docs either. Sure, it's nice that they're there, but pydoc and perldoc and ri beat them any day)

So, I'm totally over PHP now. Totally. I learned Ruby, but you might want to learn Python, or maybe Perl. Maybe more than one. They all have good CGI support, and can do all that PHP can do, and more, better. Ruby's greatly improved my hacking ability, and dumping PHP can improve yours too.

Bash PHP For Fun and Profit (3, Insightful)

KidSock (150684) | more than 7 years ago | (#15821954)

I think that there is a contingent of web programmers that are bored and upset that PHP is still the premier method for scripting websites. They want something new and fresh to work with. I can appreciate that. When you use the same language for a long time, it starts to look "old". This is exacerbated when they inherit sloppy code and are forced to decipher and fix some other dummy's spaghetti. So they declare the language "dead" in hope of creating enough spin and FUD that something new will take over. Something new that will create work and give them more job opportunities. The same something new that they invested a lot of time into learning.

To the PHP bashers - you might succeed in selling something new but after the next guy inherits your spaghetti code they will start bashing *you*.

Don't be fooled people. Every language has it's corners. I spend 90% of my time doing C but I just spent a month doing a standard LAMP site and I just don't see what these guys are hee'n and haw'n about. PHP is just as useful today as it was on 1998 so I'm willing to bet it will be around for a long time still. Don't be influenced by some bored guy saying "it sucks" and "I hate it". That's just not intelligent criticism. Try different things and make up your own mind.

PHP has a huge install base and has served us very well for many years. Let's not forget that. The PHP bashers pushing Python and Ruby should be ashamed of themselves. Post some useful information about how Python or Ruby solves a problem you think PHP has. And no cryptic one liners thank you. Get a spine and post some useful comments.

Re:Bash PHP For Fun and Profit (0)

Anonymous Coward | more than 7 years ago | (#15822240)

I think that there is a contingent of web programmers that are bored and upset that PHP is still the premier method for scripting websites. They want something new and fresh to work with. I can appreciate that. When you use the same language for a long time, it starts to look "old". This is exacerbated when they inherit sloppy code and are forced to decipher and fix some other dummy's spaghetti. So they declare the language "dead" in hope of creating enough spin and FUD that something new will take over. Something new that will create work and give them more job opportunities. The same something new that they invested a lot of time into learning.


I've been doing PHP for almost 5 years now and am beginning to falling into the "bored and upset" category.

But not because its not new or fresh, but because, for larger complicated applications, PHP becomes somewhat of a behemoth to handle. You can, of course, use software engineering techniques to make it easier, but you're still going to be building a lot from the ground up. And for what you don't build yourself, you end up having to pick one of the multitude of template languages, database abstractions, and other handy web packages that do everything their own way, but are all lacking in some respect. Its very frustrating to find 5 packages that all do 4/5ths of what I want, each lacking what another has.

Every PHP developer in existance has a standard library that basically recreates all the typical form elements in some way. Thats completely inane. Everyone has to create the same thing to do the same thing? Its frustrating, to say the least. You would think that a language that is primary used for the web would have some classes or functions available that make writing for the web much easier than while($result) { echo "<option>" }

Thats one of the nice things though - it lets you do things how you want.

PHP is not "more" extendable than other languages (1)

erichschubert (96206) | more than 7 years ago | (#15822479)

You know, other languages have libraries and modules, too...
PHP isn't the first language with MySQL bindings. It's not the first with GD bindings. And so on.
And PHP wasn't really designed to be easy to properly embed in other applications either. It was designed to have the code embedded in HTML, granted. And it was designed to run in the web server. But I doubt it was designed to be put to all kinds of use. Who is embedding PHP except for web servers?

If you want a language that was really designed for embedding, consider looking at lua. From what I know of it, it was really designed to be used as scripting language within other applications. From spreadsheets to games.
I think my brother told me he was developing on a scientific instrument (most likely for fraunhofer, probably for the development of solar power related stuff), and that you could script it in lua.
Then there is enigma, a fun game (port of Oxyd), it uses lua for scripting the levels.

PHP has other uses. Like writing bad code. SCNR. But I do consider PHP a legacy language.
Load More Comments
Slashdot Account

Need an Account?

Forgot your password?

Don't worry, we never post anything without your permission.

Submission Text Formatting Tips

We support a small subset of HTML, namely these tags:

  • b
  • i
  • p
  • br
  • a
  • ol
  • ul
  • li
  • dl
  • dt
  • dd
  • em
  • strong
  • tt
  • blockquote
  • div
  • quote
  • ecode

"ecode" can be used for code snippets, for example:

<ecode>    while(1) { do_something(); } </ecode>
Create a Slashdot Account

Loading...