Accessing PHP objects’ methods and properties

A couple of participants in Boston PHP‘s self-study PHP Percolate, Jim Wright and Jared Stenquist, are confused about the use of the -> operator, which is introduced on page 44 of PHP Solutions, 2nd Edition. Since others might be in a similar situation, I decided to write a blog post about it.

Although PHP isn’t an object-oriented language, it has extensive support for objects. Also, since PHP 5, many core aspects of the language use objects rather than ordinary (procedural) functions. An object is a special data type that is capable of storing and manipulating values. You create an object from a class, which is a collection of functions and variables that define the object’s characteristics. Some classes, such as DateTime and Mysqli, are predefined by PHP, but you can also define your own.

The advantage of using classes and objects is that, once the class has been defined, they reduce the amount of code you need to write. An object inherits all the functions and variables defined by the class. That’s not all. Each object is independent, so you can create several objects from the same class to store different values, but they all share the same functions. Up to now, I’ve referred to functions and variables, but when talking about objects and classes, a function is called a method, and a variable is called a property. Whenever you want to use an object’s method or property, you need to use the -> operator.

You create an object by calling the class’s constructor method (which has the same name as the class) with the new keyword. Most constructor methods also accept arguments that set the initial properties of the object. In the case of the built-in DateTime class, you can use a string to specify the date. Without any arguments, it creates an object for the current date and time. For example, the following code creates two objects, one for today, and the other for Christmas Day 2011:

$today = new DateTime();
$xmas2011 = new DateTime('12/25/2011');

The $today object now contains the current date and time, but $xmas2011 contains the date for December 25, 2011 (because the time wasn’t specified when creating the object, it’s set to midnight at the start of the day).

To display the day of the week, you need to use the DateTime class’s format() method, and pass it a format string (they’re listed in Table 14-4 on page 402 of PHP Solutions, 2nd Edition) for the weekday name like this:

echo $today->format('l');

This displays whatever day it is today. However, the date stored in $xmas2011 is independent of $today. The following code displays “Sunday”:

echo $xmas2011->format('l');  // Sunday

Using the -> operator is very similar to passing a variable as an argument to a function. Instead of putting the variable between the function’s parentheses, you attach the function (method) to the variable with the -> operator. What it actually means is “use the format() method with the value stored in this object ($xmas2011)”. In addition to format(), the DateTime class has other methods, such as setDate() and add(), that can be used to modify the date.

Many objects also have properties that you can access. An object’s properties are similar to values stored in an array. The big difference is that the class definition can control how a property is accessed and modified by specifying whether it’s public, protected, or private. Only public properties are visible and can be modified outside the class definition; protected and private ones are hidden from view. You access a public property using the -> operator like this:

$someObject->propertyName

This is the equivalent of accessing an array element like this:

$arrayName['elementName']

If you’re familiar with JavaScript, it should be obvious by now that the -> operator plays the same role in PHP as the dot operator in JavaScript. For example, in JavaScript, this produces the date for Christmas Day 2011:

var xmas2011 = new Date(2011, 11, 25); // months are zero-based
alert('Christmas 2011 is on ' + xmas2011.toString());

JavaScript also uses the dot operator for properties:

objectName.propertyName

Hopefully, that clarifies the role of the -> operator. If you still have questions, post them in the Comments section below.

Posted in Books, PHP | 23 Comments

Join others learning PHP with PHP Solutions

So far, more than 90 people have signed up to join a self-study group organized by Boston PHP to learn PHP with the help of my book, PHP Solutions: Dynamic Web Design Made Easy, 2nd Edition. This is the third time that Boston PHP has run this scheme known as PHP Percolate, which begins again . I understand that nearly 200 have taken part in the previous two seasons. The fact that they’re running it again—and that so many have signed up—indicates that it must be a pretty successful way of learning PHP.

There’s no charge to participate. The only cost is buying a copy of my book. Although I have Amazon affiliate links on my website, I encourage you to buy it through the Boston PHP Store. That way, the organizers get a small commission that helps support the activities of Boston PHP.

The way it works is that you commit to reading one chapter of the book (there are 17) and completing the exercises each week. There’s no classroom instruction, but you can get online support through a dedicated forum for each chapter. Also, if you live in the Boston area (the one in Massachusetts, not the one in Lincolnshire or more than a dozen other places), you can get hands-on help at the PHP Percolate Coffee Club, which is usually held every Saturday morning at a Starbucks. Boston PHP also runs occasional all-day events known as Developer Dorm Room in Cambridge, Massachusetts, where you can get help with PHP problems or just bounce ideas about projects off each other.

Although PHP Percolate is based on my book, this isn’t a wacky marketing idea that has been dreamed up by me or my publisher. It’s an idea that Boston PHP came up with independently. In fact, I didn’t learn about it until quite recently. According to the President of Boston PHP, Michael Bourque, Boston PHP is the largest and most active PHP tech community in the world, with more than 1,900 members. It has a focus on education and adoption of open source technology like PHP. Last year, they were looking for the best possible book to learn PHP, and mine was the one they chose. Naturally, I’m delighted, and I have agreed to help in whatever way I can.

Unfortunately, there’s a small matter of the Atlantic Ocean lying between me and Boston, so I won’t be able to attend the PHP Percolate Coffee Club or Developer Dorm Room in person. But that’s one of the joys of the internet. You don’t need to be there in person to share ideas and cooperate with others. From what I understand, PHP Percolate has also attracted people from other countries to join in. A book and an internet connection is all you need.

Committing to working through 17 chapters in as many weeks is a lot to ask. Work, family, and other obligations get in the way. So, not everybody manages to last the whole course. But since there’s no cost (apart from the book), there’s little to lose. In fact, I see that some of the people who dropped out part of the way through season 2 have signed up again for season 3. As one of them said, “It’s fun!”

So, if you’re looking for a little bit of moral support in your efforts to learn PHP, check out PHP Percolate Season 3 with Boston PHP.

Posted in Books, MySQL, PHP | 13 Comments

Book Review: The Book of CSS3 by Peter Gasston

Several months ago, I attended a fascinating talk on CSS3 by Peter Gasston at London Web. As one of the first people to ask a question during the Q&A session at the end of Peter’s talk, I received a free copy of his The Book of CSS3: A Developer’s Guide to the Future of Web Design. Unfortunately, my own manic schedule meant I had to put the book to the side for a while. But now I’ve managed to read it from cover to cover, I’d like to share my thoughts about it.

Let me say it right out: Peter has done a splendid job. The book is extremely well researched, and he obviously knows what he’s talking about. Having said that, the book’s subtitle (A Developer’s Guide to the Future of Web Design) very much sets the tone. If you’re looking for a quick guide on how to create CSS3 eye candy with rounded corners and drop shadows, this is not the book for you. Although Peter covers the relevant properties (border-radius and box-shadow), he takes a much more serious approach through an in-depth exploration of each new property, together with warnings about anomalies in different browsers. Because CSS3 is still evolving and browser makers are bringing out new versions at a breathtaking pace, you might think that Peter’s book will rapidly go out of date. Undoubtedly, some parts of it will; but many of the CSS3 modules that Peter covers are unlikely to change. Color is already a W3C recommendation. Selectors is a proposed recommendation; and Media Queries, Backgrounds and Borders, and Multi-column Layout are all candidate recommendations.  As a result, The Book of CSS3 is a reference book that I’ll be keeping by my side for a considerable time to come.

Even the more experimental areas covered by the book are not really a problem, thanks to the decision by all mainstream browsers to adopt browser-specific prefixes (such as -moz for Firefox and -webkit for Safari and Chrome) until the specifications settle down. Unlike CSS2.1, you won’t need hacks to deal with quirky implementations in older browsers. Just use the browser-specific prefixes in combination with the standard properties. Older versions use the prefixed properties, and when the specification stabilizes, the most up-to-date version will use the standard ones (as long as you put the standard ones lower down in the cascade). Perhaps one exception is the Flexible Box (flexbox) Layout module. Just as the book was going to press, the W3C decided to completely rename the properties. Peter mentions this at the end of the chapter on flexbox layout, but the changes haven’t yet made it through to the browsers that support it (Firefox, Safari, and Chrome). However, they will presumably continue to support the old properties with the browser-specific prefixes. But until Internet Explorer supports flexbox (planned for IE 10), using this type of layout is of limited value anyway.

Although flexbox and other proposed layout systems don’t have much practical value at the moment, I found the chapters devoted to them among the most interesting in the book—mainly because they give me hope for the future. CSS layout has always been a minefield, but if browsers (and the W3C) continue the current rapid pace of development, the job of the web developer should become a lot easier. Or will it? One of the comments in the Q&A session after Peter’s talk was that CSS was becoming more like a programming language. And it was obvious from the questioner’s tone that the thought of handling more code was unwelcome. But if you’re involved in designing websites and want to understand the direction in which CSS is moving, Peter Gasston’s book is an excellent place to start.

Posted in Books, CSS | 9 Comments

Corrections for my books

I hate it when I find a mistake in a technical book—particularly when it’s one of mine. There’s nothing more frustrating than trying to learn a new concept and hitting a brick wall because the code doesn’t work. Mistakes creep in for a variety of reasons. But whatever the reason, I know I’m letting down my readers if there’s a serious error in one of my books. So, as well as trying to avoid errors in the first place, I try to respond to error reports as quickly as possible.

I recently discovered that friends of ED has closed its website and merged it with that of its parent company, Apress. Unfortunately, none of my books’ errata are yet listed on the new site. So, I’ve scrabbled around to put them back together and host them here. You can find the corrections for the following Apress/friends of ED titles on this site:

I find it hard to believe that there weren’t any mistakes in The Essential Guide to Dreamweaver CS4, but I can’t trace any record of corrections. I haven’t gone back to some of my older books. Good though they were, they’re based on versions of software that are no longer supported. What’s more, most of them were reprinted with corrections.

I also plan to keep up to date the corrections pages on this site for the books I have published with Adobe Press.

If you come across any errors or code that doesn’t work, please report them directly to the publisher. That way corrections can be incorporated into reprinted versions of the book. But if you don’t get an acknowledgement from the publisher within a day or so, please leave a comment here, and I’ll try to deal with the issue as quickly as possible.

Posted in Books, Dreamweaver, Flash, PHP | 7 Comments

My book on Dreamweaver CS5.5 is now available online

My new book, Adobe Dreamweaver CS5.5 Studio Techniques: Designing and Developing for Mobile with jQuery, HTML5, and CSS3, is now available as Rough Cuts in the Safari Online Library and Creative Edge. In spite of being published as Rough Cuts, it’s the complete book. The only differerence is that the text and screenshots haven’t been laid out in the way they will be in the final version, which is expected to be published on 10 June.

If you planning to develop sites for multiple platforms, you’ll learn about CSS media queries and how to use the new features in Dreamweaver CS5.5, including setting up a site-wide media queries file. There’s a chapter on making sites available offline, and the download files contain a Dreamweaver extension that automatically builds a manifest file ready for editing. The chapters on jQuery Mobile contain extensive analysis of custom data attributes that control the look and functionality of a jQuery Mobile site.

Stephanie (Sullivan) Rewis (@stefsull) had a sneak preview of the book. Her verdict: “David’s clarity and ability to explain complex subjects clearly makes this a book not to be missed.”

Posted in AJAX/JavaScript, Books, CSS, Dreamweaver | 22 Comments

Taking Dreamweaver into the lions’ den

Last night, the good folks at London Web Standards allowed me to take the floor for a five-minute “lightning talk” to demonstrate some of the new features of Dreamweaver CS5.5, which had been officially announced only 14 hours earlier. It was a daunting task, because I know many professional web developers say they wouldn’t be seen dead using Dreamweaver. Moreover, everyone had come to hear Rob Hawkes talk about developing online games with HTML5 and JavaScript, and Seb Lee-Delisle demonstrate his amazing JavaScript skills. They weren’t there to hear about a product they probably don’t use.

Things didn’t go quite to plan. I had lined up a series of quick demos to show off the way Dreamweaver handles media queries and the creation of rounded corners with the CSS3 border-radius property. Unfortunately, the connection to the projector switched the resolution on my laptop to something crazy like 640 x 480, making it impossible to see the full workspace and preventing me from accessing the document tabs to switch between the demo pages I had prepared. Since I had only a five-minute slot, I decided—perhaps foolishly—to soldier on rather than waste valuable time trying to find a resolution compatible with the projector.

What I did manage to demonstrate was Dreamweaver CS5.5′s support for web fonts, creating and adjusting CSS3 drop shadows visually, jQuery code hinting, and PhoneGap integration. While demonstrating the support for web fonts, I was able to show how you can work in the underlying code and view the result in Live view without needing to save the document or round-trip to a browser.

I got the feeling that the audience remained sceptical about Dreamweaver, but they listened to what I had to say. And with plenty of questions, my original five minutes extended beyond ten. Matt Lucht has given a good summary of what I had to say (together with comments about the main speakers). Matt makes the comment “I’m not sure what value it gave over say a browser plugin such as Firebug.” It’s a fair point. Dreamweaver is an IDE for HTML, CSS, JavaScript, PHP, and other web-related languages, all of which are open standards. Therefore, there are plenty of authoring tools around—some free, others commercial.

What I think Dreamweaver has to offer is the way in which it brings the various web technologies together. I use Firebug and similar tools, such as the Web Inspector in Safari. They’re great, but you need to switch from your IDE and back to use them. Each time you switch is time wasted. Dreamweaver gives me most of the tools I need in a single workspace. Working recently with a jQuery Mobile project, I found Dreamweaver’s Live Code one of the most useful features. It lets you inspect the dynamically generated code inside the Document window, which is essential for dealing with pages generated through DOM manipulation. Yes, I can get the same information by right-clicking in Safari or Chrome and selecting Inspect Element, but it takes me longer to do so. Live Code also lets me inspect what’s happening in response to different events by highlighing all changes in a different colour.

Judging by comments from the audience and in conversation afterwards, there seem to be two main barriers to acceptance of Dreamweaver among professional web developers/designers. The main complaint is the price. I can’t do anything about that, although I have told Adobe on more than one occasion that I think the price differential—between what you pay in dollars in North America and what you pay in pounds or euros in Europe—is totally unjustifiable, particularly for a product that is delivered electronically. Adobe is not alone in charging a premium outside the USA, but it builds up resentment and damages sales. Still, buying software is a business expense. Business must be really bad if you can’t afford the tools for the job.

That brings me to the other main barrier—many web professionals don’t think Dreamweaver is the right tool for the job they’re doing. Maybe they’re right. Far be it from me to question how another person does his or her job. But several people in the audience admitted that they hadn’t used Dreamweaver for a long time. I have used it consistently since Dreamweaver 3 (about 11 years). The Dreamweaver of yesteryear is not the program it is today.

In 2001, the Web Standards Project (WaSP), led at the time by such people as Jeffrey Zeldman, formed a task force to pressure Macromedia (the original creators of Dreamweaver) to improve the standards compliance and accessibility of pages created with Dreamweaver. The initial result was the release of Dreamweaver MX 2004, which produced much cleaner code. It wasn’t perfect, but it was close. The main problem was Layout Mode, a WYSIWYG tool that produced the most horrendous table-based spaghetti code. Another problem was the use of “layers”—absolutely positioned elements with inline styles. With the help of others, I privately lobbied Macromedia and then Adobe to get rid of Layout Mode. Partial success was achieved with the release of Dreamweaver CS3 in 2007, when access to Layout Mode was deliberately hidden. Then, in 2008, Layout Mode was finally killed off in Dreamweaver CS4. Layers also disappeared. You can still create absolutely positioned elements, but they no longer have inline styles.

The WaSP Adobe Task Force was wound up in 2009, but Stephanie (Sullivan) Rewis still acts as WaSP Industry Evangelist to Adobe. I know from my participation in private Adobe forums that she gives the Dreamweaver engineering team a tough time, pressuring them constantly to improve standards. Dreamweaver certainly hasn’t stood still. It has full code hinting support for HTML5 and for CSS3 modules that have reached a reasonable degree of stability. Its support for PHP and JavaScript code introspection has greatly improved its usefulness to developers.

As I see it, Dreamweaver’s main problem is one of perception. It gained a reputation (deservedly so) for producing bad code and for being a WYSIWYG tool. The WYSIWYG image is completely wrong. Most Dreamweaver users that I know work in Split view with the code on the left of the screen, and a visual representation of the page in Design view on the right. If you’re working in Design view, you can keep an eye on the code that’s being generated. But it gets better if you switch into Live view, which renders the page using the WebKit browser engine. You can continue working in the code, and your changes are immediately reflected in Live view by pressing F5 or clicking the refresh icon. What’s more, the Related Files toolbar gives you access to all linked files in Code view. So, I can work in an external JavaScript file while keeping the web page visible on the right of the screen.

If you haven’t used Dreamweaver for a long time, give it a try when CS5.5 is released in May. There will be a 30-day free trial. As long as you’re willing to explore its features, I think you might find there’s a lot to like. If it doesn’t match your needs, fine. But at least I hope you’ll get the chance to see that it’s not Dreamweaver that produces bad code. It’s bad designers/developers who do.

(Disclosure: I’m not an Adobe employee, but I am an Adobe Community Professional, a sort of unpaid evangelist for Dreamweaver. I write books about Dreamweaver and answer questions in the Dreamweaver Help pages. I also teach Dreamweaver and write books about PHP.)

Posted in AJAX/JavaScript, CSS, Dreamweaver | 7 Comments

My Next Book: Dreamweaver CS5.5 for Mobile

I’ve been burning the midnight oil since the beginning of this year, working on my next book—Adobe Dreamweaver CS5.5 for Mobile with jQuery, HTML5, and CSS3: Studio Techniques. The book is now complete, and is scheduled to go live on Safari Online Library and Creative Edge as soon as Dreamweaver CS5.5 is released (the actual date has not yet been made public). The printed book—published by Adobe Press—should be available in early June.

The book guides you through the main new features in Dreamweaver CS5.5 with the help of three case studies. The first one centers on redesigning a website for display on desktops, tablets, and smartphones using HTML5, CSS3, and media queries. The second takes a cut-down version of the same site, and builds a dedicated mobile version using jQuery Mobile, a sophisticated JavaScript and CSS framework designed to work consistently in all major mobile platforms. The final case study uses Dreamweaver CS5.5′s PhoneGap integration to develop a simple app that stores information in a database, accesses a mobile phone’s GPS sensor, and displays a map.

More details later.

Posted in Books, CSS, Dreamweaver | 7 Comments

Dreamweaver CS5.5—More Than a Point Release

Finally, I can reveal details of the version of Dreamweaver that I’ve been experimenting with for the past few months. Officially, it’s called Dreamweaver CS5.5, which makes it sound as though it has a couple of extra features, but not quite enough to justify calling it Dreamweaver CS6. Nothing could be further from the truth.

This is a major upgrade. Here’s what it contains:

  • Full support for jQuery Mobile, including more than a dozen jQuery Mobile widgets.
  • PhoneGap integration to create native apps for Android and iOS using HTML, CSS, and JavaScript.
  • Code hinting for jQuery.
  • New tools for creating CSS3 rounded corners and drop shadows.
  • Support for web fonts.
  • Full support for all CSS3 selectors.
  • The ability to see what pages will look like at different screen resolutions without leaving the Document window.
  • Support for FTPS.

The emphasis in this new version is firmly on  development for multiple screen resolutions and for mobile devices. The New Document dialog box contains starter pages for jQuery Mobile that enable you to build in minutes a simple web application that works consistently in all major mobile platforms. All you need to do is to replace the placeholder text with content of your own. Of course, to create more than just a boilerplate application, you need to do your own coding. But Dreamweaver CS5.5 has full code hinting for both jQuery core and jQuery Mobile, speeding up the development process.

The PhoneGap integration is particularly impressive. At the moment, Dreamweaver supports the development of native apps only for Android and iOS, but there are plans to expand this later to other mobile operating systems. Developing for iOS requires Mac OS X 10.6, but Android is supported on both the Windows and Mac versions of Dreamweaver. If don’t already have the Android SDK (software development kit) installed, Dreamweaver does it for you with just a single click. Having gone through the pain of the manual installation process on both Windows and Mac, I can honestly say that Dreamweaver’s automated installation is a real godsend. After developing your web app with HTML, CSS, and JavaScript, Dreamweaver runs PhoneGap to build the native version and installs it into a simulator.

Smaller, but nonetheless important enhancements that I particularly like are the tools for creating image-less drop shadows and rounded corners with CSS3. Using them in combination with Live view lets you see the effect of your style definition immediately. No constant toing and froing between the style sheet and a browser. Dreamweaver also now has support for rgba() and hsla() colour formats, simplifying the addition of transparent effects to your web pages.

Is there anything not to like? Yes. Bringing out this new version only a year after CS5 and about eight months after the 11.0.3 updater means there are a few rough edges. For example, you need to be careful where your insertion point is when you add a jQuery Mobile widget. Normally, Dreamweaver recognizes if you’re inside a paragraph or other block element and either moves outside the element or splits it. However, with jQuery Mobile widgets, it just puts the new code wherever you happen to be. It’s more of a minor irritation than a major failing; but anyone who doesn’t understand the code that’s being created will end up with a complete mess.

Dreamweaver’s implementation of HTML5 also has some way to go. But then, so has HTML5 itself. There’s full code hinting for HTML5 elements and attributes, but there’s no easy way to insert HTML5 elements except through hand-coding in Code view.

In spite of the shortcomings, I’m really enjoying working with Dreamweaver CS5.5, and hate going back to earlier versions. I strongly recommend that you give it a try when it’s released. I think you’ll like it.

Posted in CSS, Dreamweaver | 17 Comments

Missing file for PHP Solutions, Second Edition

A couple of readers have reported that download.php was missing from the ch07 folder of the download files for PHP Solutions, Second Edition. The zip file on the friends of ED download page has now been updated. If you downloaded the zip file before 4 January, please download the updated version. Many apologies for the inconvenience.

While checking the reports of the missing file, I discovered a mistake in the code on page 211 of the book. A closing curly brace is missing at the bottom of the script. Details are on the book’s corrections page.

Posted in Books, PHP | 51 Comments

Preventing email header injection

More than five years have passed since New York PHP published an extremely useful article warning developers of the dangers of email header injection, and providing detailed instructions of how to prevent it. Yet barely a week goes by without PHP newcomers posting requests for help with email scripts that still contain this vulnerability. Unfortunately, many beginners seem to use outdated scripts or tutorials that ignore basic security, and have never heard of email header injection. When they’re told about it, the NYPHP article is too technical for them to understand. So, this is an attempt to make it simple.

What is email header injection?

The PHP mail() function takes up to five arguments, the first three of which are required: the address(es) the mail is being sent to, the subject line, and the body of the message. The fourth argument allows you to specify additional headers, such as From, Reply-to, Cc, and Bcc. Email header injection usually targets weaknesses in the way this fourth argument is handled to insert bogus headers to turn your online form into a spam relay.

One of the most common uses of the fourth argument is to insert the user’s email address into the From or Reply-to header. It’s extremely convenient, because it allows you to reply directly to an email received from an online form just by clicking the Reply button in your email program. It’s also extremely convenient for an attacker. All that’s necessary is to add a string of spurious headers into the email field of your contact form, and your website becomes an instant spam relay—unless, of course, you take suitable precautions.

Preventing email header injection

The data filters introduced in PHP 5.2 make it easy to check that the value submitted through the email field of an online form contains a single email address and nothing else. So, if you want to put the user’s email address in a Reply-to header, you can check it like this (assuming the input field is named “email”):

$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "Reply-to: $validemail\r\n";
}

Note that INPUT_POST and FILTER_VALIDATE_EMAIL are PHP constants, and must be in uppercase.

Using filter_input() like this is a simple, and effective way to prevent the email field of a contact form being exploited for header injection. Of course, you would probably want to take further action if the email address fails validation (the filter checks only that it’s in a valid format—it doesn’t check whether it’s a genuine address), such as redisplaying the form with an error message. This blog post is concerned only with basic prevention.

Is that all that’s needed?

Although the email field of a contact form is the main target, you also need to be careful about allowing user input in the first and second arguments to mail(): the address the message is being sent to, and the subject line. If both values are hard-coded in your script, there’s nothing to worry about. However, if your form allows the user to select from a choice of destination addresses, or insert a custom subject line, you need to sanitize those values before passing them to mail(). Don’t be fooled by thinking that a drop-down menu in your form limits the values that can be entered. It’s very easy for an attacker to bypass your preselected values.

One way of handling the destination addresses is to create an array of valid addresses, and use in_array() to check that the submitted value is among them.

$destinations = array('me@example.com', 'you@example.com');
if (in_array($_POST['to'], $destinations) {
// the address is OK to use
} else {
// don't send the mail
}

You can do the same with a choice of subjects. But if you want to allow the user to enter a custom subject line, you need to check that it doesn’t contain newline characters or common headers. The following code uses a regular expression to detect characters and values likely to be used in an attack:

$pattern = '/[\r\n]|Content-Type:|Bcc:|Cc:/i';
if (preg_match($pattern, $_POST['subject'])) {
// reject the post, as it's most likely an attack
}

I go into much more detail in my books, but hopefully this help PHP newcomers to adopt more secure coding practices with mail().

Posted in PHP | 6 Comments