Spiga
Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Ten Commandments of Collecting Email Addresses on Website

As anyone who runs a website these days knows, or should know, the recently enacted CAN-SPAM Act of 2003 makes it incumbent on emailers to either be able to establish a certain type of relationship with an email recipient or to adhere to certain mailing standards if no such relationship exists. Failure to do so can land one in Federal (or state) court.

However beyond that there is the court of Internet public opinion, and beyond even that is the high court of spam filters and spam blocking. Truly, you don’t want to run afoul of any of these.

The safest way to ensure that you stay on the good side of the law, and spam filters, particularly when building a list of email addresses to which you wish to send business, commercial, or other correspondence related to your website, is to follow this simple list of ten DOs and DON’Ts:

DON’Ts:


1. DON’T trap a website visitor’s email address and then add it to a mailing list without their permission.

2. DON’T use other identifying website visitor information, such as IP address, computer name, etc., to ‘reverse engineer’ or otherwise divine or guess at their email address, and then add it to a mailing list.

3. DON’T pre-check a check box which “opts in” to your mailings, requiring the visitor to uncheck it in order to not receive your mailing or be added to your mailing list.

4. DON’T be coy, cute, or evasive about what your intent and policy are with respect to any email address your visitor provides.

5. DON’T add an email address, even if freely provided, to your mailing list unless you have provided a way for the visitor to clearly indicate that they want to be added to your mailing list, and they so indicate.

DOs:


1. DO state very clearly what you will do with any email address provided by a visitor, including your privacy policy.

2. DO scrupulously adhere to what you have said you will do with their email address, and never, ever share it with someone else without their explicit permission.

3. DO collect and store, with the email address submitted, the source IP address, the date and time of the submission, and any other unique identifying information; store it along with the indication of permission the visitor has provided for you to add their address to your mailing list. I cannot stress this enough. When accused of spamming (and you will be), having this information available to refresh the memory of your accuser, and to prove to your ISP that you were not spamming them, will save your hide. An ounce of prevention here is worth a ton of trying to get off a spam blocking list without this exculpatory information.

4. DO honour opt-out requests religiously, and immediately.

5. DO pick up ISIPP’s CAN-SPAM Compliance Pack, chock full of practical advice and tips, and even audio speeches from lawyers from the FTC and a major ISP, to make sure that you get, are, and remain CAN-SPAM compliant. If not that, at least pick up their CAN-SPAM and You: Emailing Under the Law eBook.

Tips for improving your Web security

Here are a handful specific techniques for improving your Web security.
  • Make it your job to study, follow, and abide by security recommendations.
  • Don’t use user-supplied names for uploaded files.
  • Watch how database references are used. For example, if a person’s user ID is their primary key from the database and this is stored in a cookie, a malicious user just needs to change that cookie value to access another user’s account.
  • Don’t show detailed error messages in the website.
  • Reliably and consistently protect every page and directory that needs it. Never assume that people won’t find sensitive areas just because there’s no link to them. If access to a page or directory should be limited, make sure it is.
  • Don’t store credit card numbers, social security numbers, banking information, and the like. The only exception to this would be if you have deep enough pockets to pay for the best security and to cover the lawsuits that arise when this data is stolen from your site (which will inevitably happen).
  • Use SSL, if appropriate. A secure connection is one of the best protections a server can offer a user.
My final recommendation is to be aware of your own limitations. As the programmer, you
probably approach a script thinking how it should be used. This is not the same as to how it will be used, either accidentally or on purpose. Try to break your site to see what happens.Do bad things, do the wrong thing. Have other people try to break it, too (it’s normally easy to find such volunteers). When you code, if you assume that no one will ever use a page properly, it’ll be much more secure than if you assume people always will.

Changing the PHP Session Behavior

As part of PHP’s support for sessions, there are over 20 different configuration options you can set for how PHP handles sessions. Here I’ll highlight a few of the most important ones here. Note two rules about changing the session settings:

1. All changes must be made before calling session_start().
2. The same changes must be made on every page that uses sessions.

  ini_set (parameter, new_setting);

For example, to require the use of a session cookie (as mentioned, sessions can work without cookies but it’s less secure), use

   ini_set ('session.use_only_cookies', 1);

Another change you can make is to the the name of the session (perhaps to use a more userfriendly one). To do so, use the session_name() function.

  session_name('YourSession');

The benefits of creating your own session name are twofold: it’s marginally more secure and it may be better received by the end user (since the session name is the cookie name the end user will see). The session_name() function can also be used when deleting the session cookie:

  setcookie (session_name(), '', time()-3600);

Finally, there’s also the session_set_cookie_params() function. It’s used to tweak the settings of the session cookie.

  session_set_cookie_params(expire, path, host, secure, httponly);

Note that the expiration time of the cookie refers only to the longevity of the cookie in the Web browser, not to how long the session data will be stored on the server.

How To Prevent Brute Force Attacks

A brute force attack is an attempt to log into a secure system by making lots of attempts in the hopes of eventual success. It’s not a sophisticated type of attack, hence the name "brute force." For example, if you have a login process that requires a username and password, there is a limit as to the possible number of username/password combinations. That limit may be in the billions or trillions, but still, it’s a finite number. Using algorithms and automated processes, a brute force attack repeatedly tries combinations until they succeed.

The best way to prevent brute force attacks from succeeding is requiring users to register with good, hard-to-guess passwords: containing letters, numbers, and punctuation; both
upper and lowercase; words not in the dictionary; at least eight characters long, etc. Also, don’t give indications as to why a login failed: saying that a username and password combination isn’t correct gives away nothing, but saying that a username isn’t right or that the password isn’t right for that username says too much.

To stop a brute force attack in its tracks, you could also limit the number of incorrect login attempts by a given IP address. IP addresses do change frequently, but in a brute force attack, the same IP address would be trying to login multiple times in a matter of minutes. You would have to track incorrect logins by IP address, and then, after X number of invalid attempts, block that IP address for 24 hours (or something). Or, if you didn’t want to go that far, you could use an “incremental delay” defense: each incorrect login from the same IP address creates an added delay in the response (use PHP’s sleep() function to create the delay). Humans might not notice or be bothered by such delays, but automated attacks most certainly would.

Sessions vs. Cookies

Cookies


Cookies are a way for a server to store information on the user’s machine. This is one way that a site can remember or track a user over the course of a visit. Think of a cookie as being like a name tag: you tell the server your name and it gives you a sticker to wear.Then it can know who you are by referring back to that name tag.
  • Cookies are limited to about 4 KB of total data, and each Web browser can remember a limited number of cookies from any one site. This limit is 50 cookies for most of the current Web browsers.
  • Each browser treats cookies in its own way. Be sure to test your Web sites in multiple browsers on different platforms to ensure consistency.
  • users can reject cookies or turn them off in the Web Browsers.

Sessions


Data is stored on the server, not in the Web browser, and a session identifier is used to locate a particular user’s record (the session data). This session identifier is normally stored in the user’s Web browser via a cookie, but the sensitive data itself—like the user’s ID, name, and so on—always remains on the server.

Sessions have the following advantages over cookies.
  • They are generally more secure (because the data is being retained on the server).
  • They allow for more data to be stored.
  • They can be used without cookies.
Whereas cookies have the following advantages over sessions.
  • They are easier to program.
  • They require less of the server.
In general, to store and retrieve just a couple of small pieces of information, use cookies. For most of your Web applications, though, you’ll use sessions.

Three Quick Tips To Make Your PHP Understandable

Producing code that clearly conveys a developer's intent is key to any well written application. That not only applies to PHP, but every programming language. Developers who emphasize the creation of legible code tend to create applications which are easier to both maintain and expand upon. After seven years of programming in PHP I've worked on a variety of projects where well organized and legible code were set aside for numerous reasons. Some of those reasons include time constraints, lack of experience, lost enthusiasm, misdirected pre-optimizing, and the list goes on.

Today we'll look at three simple methods which are commonly ignored by developers for some, if not all of the reasons described above. First, we'll discuss the importance of clean conditional logic. Second, we'll look at how you can cleanly output blocks html of in PHP. And finally, we'll examine the use of sprintf to convey variables placed in stings more legibally.

Tip #1: Write Clean Logic Statements

Example 1.1: Unclean Conditional Logic
<?php

if($userLoggedIn) {
// Hundreds of lines of code
}else{
exit();
}

?>

The above statement seems straight forward, but it's flawed for the reason that the developer is giving this conditional block too much responsibility. I know that might sound a little weird, but stay with me.

The type of conditional organization above makes for unnecessarily complex code to
both interpret and maintain. A brace that's paired with a control structure hundreds of lines above it won't always be intuitive for developers to locate. I prefer the style of conditional logic in example 1.2, which inversely solves the previous example. Let's take a look.

Example 1.2: Clean Conditional Logic
<?php

if(!$userLoggedIn) {
exit();
}

// Hundreds of lines of code

?>

This conditional statement is more concise and easier to understand. Instead of stating: "if my condition is met, perform hundreds of operations, else exit the script", it's saying "if my condition is not met, exit the script. Otherwise, I don't care about what happens after that. I am only concerned with stopping execution". So, by doing this, you've limited the operations that a given control structure has been tasked with, and that will help other developers quickly understand your code.

Read More

Preventing Accidental Deletes

Murphy’s Law states whatever can go wrong will go wrong. So even with the appropriate logging and monitoring measures in place accidents are bound to happen. Even with warning and confirmation screens a legitimate user can still delete information they didn’t really intend to. The problem with DELETE statements is that they are irrecoverable.

One suggestion to prevent the unintentional deletion of data stored in a database is to add a new field to the records named IS_DELETED . The field is a TINYINT(1) which contains either a 0 or 1 to denote if the record is considered deleted . Your application would not issue any actual DELETE queries, rather it would set the field value to 1. It’s trivial to change the value of the field to restore the record in case of an accident.

Depending on the type of application you are developing, you may not want to have stale data in the database. To prevent deleted records from accumulating in the table you can write an administrative script that can run weekly (or even nightly) from cron or Scheduled Tasks to actually delete the records.The code below shows a script that I use.

A SHOW TABLES query is issued to retrieve a list of all tables in the database. For each table name that is returned, the column names are retrieved with a SHOW COLUMNS query and scanned to find any names that are named IS_DELETED . If so then a true DELETE query is issued otherwise the script moves on to analyze the next table.


#! /usr/bin/php
<?php
include ‘../lib/common.php’;
include ‘../lib/db.php’;
// retrieve list of tables
$table_result = mysql_query(‘SHOW TABLES’, $GLOBALS[‘DB’]);
while ($table_row = mysql_fetch_array($table_result))
{
    // retrieve list of column names in table
    $column_result = mysql_query(‘SHOW COLUMNS FROM ‘ . table_row[0], $GLOBALS[‘DB’]);
    while ($column_row = mysql_fetch_assoc($column_result))
    {
        // if the table has an IS_DELETED field then delete old records
        if ($column_row[‘Field’] == ‘IS_DELETED’)
        {
          mysql_query(‘DELETE FROM ‘ . $table_row[0] . ‘ WHERE ‘ . ‘IS_DELETED = 1’ , $GLOBALS[‘DB’]);
          // break out to process next table
          mysql_free_result($column_result);
          break;
        }
    }
    mysql_free_result($column_result);
}
mysql_free_result($table_result);
mysql_close($GLOBALS[‘DB’]);
?>

Securing User Submitted Data in PHP

The greatest weakness in many PHP programs is not inherent in the language itself, but merely an issue of code not being written with security in mind. For this reason, you should always take the time to consider the implications of a given piece of code, to ascertain the possible damage if an unexpected variable is submitted to it.

<?php
// remove a file from the user's home directory... or maybe
// somebody else's?
unlink ($evil_var);

// Write logging of their access... or maybe an /etc/passwd entry?
fwrite ($fp, $evil_var);

// Execute something trivial.. or rm -rf *?
system ($evil_var);
exec ($evil_var);

?>

You should always carefully examine your code to make sure that any variables being submitted from a web browser are being properly checked, and ask yourself the following questions:
  • Will this script only affect the intended files?
  • Can unusual or undesirable data be acted upon?
  • Can this script be used in unintended ways?
  • Can this be used in conjunction with other scripts in a negative manner?
  • Will any transactions be adequately logged?

By adequately asking these questions while writing the script, rather than later, you prevent an unfortunate re-write when you need to increase your security. By starting out with this mindset, you won't guarantee the security of your system, but you can help improve it.

You may also want to consider turning off register_globals, magic_quotes, or other convenience settings which may confuse you as to the validity, source, or value of a given variable. Working with PHP in error_reporting(E_ALL) mode can also help warn you about variables being used before they are checked or initialized (so you can prevent unusual data from being operated upon).

Improving PHP Session Security - Part1

Because important information is normally stored in a session (you should never store sensitive data in a cookie), security becomes more of an issue. With sessions there are two things to pay attention to:

1) Session ID
2) Session data

A malicious person is far more likely to hack into a session through the session ID than the data on the server, so I’ll focus on these things here

The session ID is the key to the session data. By default, PHP will store this in a cookie, which is preferable from a security standpoint. It is possible in PHP to use sessions without cookies, but that leaves the application vulnerable to session hijacking: If I can learn another user’s session ID, I can easily trick a server into thinking that their session ID is my session ID. At that point I have effectively taken over the original user’s entire session and would have access to their data. So storing the session ID in a cookie makes it somewhat harder to steal.

One method of preventing hijacking is to store some sort of user identifier in the session, and then to repeatedly double-check this value. The HTTP_USER_AGENT — a combination of the browser and operating system being used—is a likely candidate for this purpose. This adds a layer of security in that one person could only hijack another user’s session if they are both running the exact same browser and operating system.

Next Post - As a demonstration of this, let’s see an example.

The secret behind PHP Success

So, another “PHP sucks” post, this time from Jeff Atwood. He actually ends up even kind of praising PHP, surprised by its success. I have a couple of thoughts on that topic too.

First, people really need to stop reading something on PHP written somewhere in 2005 (probably about experiences that happened in 2001) and apply it to PHP as it is now, without even checking around for current trends. It’s as if people would dig up books from middle ages saying that there are only seven metals in existence or debating about phlogiston, and would use it speaking about the modern chemistry. Come on!

Then the next thing apparently wrong with PHP is too many functions. Right. Since when? Since when having a lot of functions is a problem? Does it hurt anybody? Does it make writing PHP code harder? Does it make programmer less successful in achieving his goals?

About keywords I could kind of understand - OK, a lot to remember (though I didn’t see anybody really having trouble to remember such complicated keywords as “while”, “if”, “class” or “public”) and it takes out some good English words that could be used as function/method names to confuse the enemy (who wouldn’t want to have function named endforeach() or static(), not to mention function()? too bad those are not available!). But complaining there’s too many actual functions that allow you to do real useful stuff? That is the thing that is bothering people? That is what scares people away from using the language “for years”?

The next beef with PHP is that people write sucky code on it. No, really, they do? Must be something really wrong with this language. It’s not like people write mind-bogglingly sucky code on every other “good” language on the planet. But I get it. The intent was - PHP makes easy to write sucky code. Yes, this is true. As true as “Porsche 997 makes it easy to drive at 100mph into a brick wall”.  PHP makes it easy to write various kinds of code - and if 90% of code written is sucky, then 90% of PHP code would be sucky. But my experience says quality of the production code almost never has much to do with the language, but only with the culture - organizational and personal, and with choosing right ways to do the job. The rest is just bad statistics in play. Like “I know 7-year-old writing websites, and his PHP code sucks”. I bet his Haskell code rules though.

That’s not to say PHP couldn’t use improvement. It could. And it does, actually - and there’s enough room for improvement still, in many areas. But it probably would never satisfy purists. It’s practical. Maybe it doesn’t allow you to write whole programs in one line of uncomprehensible character soup or play with high-level math theory concepts, but it allows people to write web applications. So they do - so where’s the surprise when one morning somebody wakes up and discovers there’s a ton of web applications around and they are written in PHP?.

PHP Debugging Techniques

When it comes to debugging, what you’ll best learn from experience are the causes of certain types of errors. Understanding the common causes will shorten the time it takes to fix errors.

Common PHP Errors
  • Blank Page : HTML problem, or PHP error and display_errors or error_reporting is off.
  • Parse error : Missing semicolon; unbalanced curly braces, parentheses, or quotation marks; or use of an unescaped quotation mark in a string.
  • Empty variable value : Forgot the initial $, misspelled or miscapitalized the variable name, or inappropriate variable scope (with functions).
  • Undefined variable : Reference made to a variable before it is given a value or an empty variable value (see those potential causes).

  • Call to undefined function : Misspelled function name, PHP is not configured to use that function (like a MySQL function), or document that contains the function definition was not included.
  • Cannot redeclare function : Two definitions of your own function exist; check within included files.

  • Headers already sent : White space exists in the script before the PHP tags, data has already been printed, or a file has been included.
How to aviod syntactical Errors
  • End every statement (but not language constructs like loops and conditionals) with a semicolon.
  • Balance all quotation marks, parentheses, curly braces, and square brackets (each opening character must be closed).
  • Be consistent with your quotation marks (single quotes can be closed only with single quotes and double quotes with double quotes).
  • Escape, using the backslash, all single and double-quotation marks within strings, as appropriate.
To debug your scripts
  • Turn on display_errors.
  • Use the print() and echo() functions.
  • Check what quotation marks are being used for printing variables.
  • Use comments.
  • Print array values using print_r() and var_dump().

Updating Twitter with cURL and Wget

Just in case you are a complete noob, let me explain one of the hottest social networking tools, a micro-blogging service called Twitter. Twitter allows you to post messages of up to 140 characters (from your browser or a variety of applications) that can be seen either by the whole Twitter world or by select Twitter users. You can follow what everyone is posting or just follow your Twitter friends. (On Twitter I am "quistuipater".)

So, first up this week is a service that all Twitterholics would love if it actually worked properly: istwitterdown.com. The home page of istwitterdown reads "Yes" or "No" depending on the status of Twitter.com. Sounds cool, but all it actually seems to be telling you is whether the server is responding to pings, which is something that is quite different from whether Twitter is actually working properly, which, at the time of writing, it isn't. Again. Actually, that should be yet again. Come on Twitter, I know it seems like rocket science, but really. . . .

At the end of this discussion we'll come back to how istwitterdown should work. . . .

Anyway, next up, a command line Twitter client. In a corporate context this is something that you might want to use to broadcast a "tweet" (that's what Twitter messages are called) for events such as status updates for a service or device.

The Twitter REST-based (Representational State Transfer) API is relatively simple, and to post a tweet all you need to perform is a straightforward HTTP POST request. (Oh great, now Twitter is going up and down like a yo-yo.)

An easy way to post to tweet from a command line is to use cURL, a free open source tool that lets you use a URL format to perform data transfers.

cURL is dauntingly overblessed with features and can handle all of the major protocols, including HTTP, HTTPS, FTP, FTPS and even LDAP and Telnet. Better still, cURL is available for a large number of operating systems, including AIX, BeOS, DOS, various flavors of BSD, a huge number of Linux distros, OS X, NetWare (our younger readers may have heard of this), Solaris and Windows (both 32- and 64-bit versions).

To post to Twitter you have to have an account because the API requires you to authenticate. So using cURL in a command or terminal window, you enter a command line as follows (this command should be on a single line and the variables are underlined):

curl -u email:passw -d status="text" http://twitter.com/statuses/update.xml

cURL figures out which protocol to use from the URL you provide, and when "http:" is specified will, unless otherwise instructed (using -0), default to using HTTP 1.1. The first argument, -u, instructs cURL to use the next two parameters (separated by a colon) as the account name and password for basic authentication. The next argument, -d, specifies the data (maximum 140 characters) to be sent via a POST request.

Of course what cURL expects is a response to the POST request so the result will be the requested page (update.xml) sent to stdout. This page will be encoded according to the file type used in the request, thus as we just requested update.xml we'll get XML-formatted data. The alternatives are JSON (JavaScript Object Notation), RSS and Atom formats.

If you'd prefer you could do the same exercise using GNU Wget. Wget, which runs on Windows, MSDOS, VMS and Solaris, is similar to cURL but with fewer features and a slightly more complex syntax. This is the same Twitter posting as above in Wget format (this command should also be on a single line):

wget --keep-session-cookies --http-user=email --http-password=passw --post-data="status=text" http://twitter.com:80/statuses/update.xml

Unlike cURL, Wget sends the output to a file named for the target of the request (here it would be update.xml).

It is important to note that you are limited to sending updates to your Twitter account no more frequently than 70 times in any 60-minute period.

So, how should istwitterdown.com work? Rather than just pinging the server, it should set up a Twitter account and, using a query similar to those above, perform an update and then check the return code. The code will show that the service will respond or the Web server will report that the server isn't running or you'll get a timeout. How hard is that?

PHP session cookie refresh

I have always had an issue with PHP Sessions. Albeit, a lot of my issues are now invalid. When they were first implemented, they had lots of issues. Then the $_SESSION variable came to exist and it was better. Then memcached came to exist and you could store sessions there. That was better. But, still, after all this time, there is one issue that still bugs me.

When you start a session, if the user had no cookie, they get a new session id and they get a cookie. You can configure that cookie to last for n seconds via php.ini or session_cookie_set_params(). But, and this is a HUGE but for me, that cookie will expire in n seconds no matter what. Let me explain further. For my needs, the cookie should expire in n seconds from last activity. So, each page load where sessions are used should reset the cookie’s expiration. This way, if a user leaves the site, they have n seconds to come back and still be logged in.

Consider an application that sets the cookie expiration to 5 minutes. The person clicks around on the site, gets a phone call that lasts 8 minutes and then gets back to using the site. Their session has expired!!!! How annoying is that? The only sites I know that do that are banks. They have good reason. I understand that.

My preference would be to either set an ini value that tells PHP sessions to keep the session active as long as the user is using the site. Or give me access to the internal function php_session_send_cookie(). That is the C function that sends the cookie to the user’s browser. Hmm, perhaps a patch is in my future.

In the short term, this is what I do:
<?
setcookie( ini_get("session.name"), session_id(),
time()+ini_get("session.cookie_lifetime"),ini_get("session.cookie_path"),
ini_get("session.cookie_domain"),
ini_get("session.cookie_secure"),
ini_get("session.cookie_httponly"));
?>

That will set the session cookie with a fresh ttl.

Ok, going to dig into some C code now and see if I can make a patch for this.

Zend PHP framework upgraded

Zend Technologies plans to announce availability of the open source Zend Framework 1.5 for building PHP (Hypertext Preprocessor) applications next week.

With this release, Zend Framework is to be made available in a version of the Ubuntu Linux distribution in April. Featuring contributions and sponsorships from such vendors as Microsoft, IBM, and Google, Zend Framework 1.5 supports OpenID and Microsoft InfoCard identity management technologies. Also supported is LDAP authentication and the Nirvanix media content storage and delivery network. PHP programmers using the framework can access Nirvanix capabilities.

Other features include new services and enhancements to make it easier to build Web sites faster, including:

-- Support for an upload capability for YouTube via new YouTube APIs. Users can upload, watch, and comment on YouTube videos on PHP Web sites.

-- Forms, including AJAX (Asynchronous JavaScript and XML) usage patterns for building Web-based forms.

-- Layout and View to implement a consistent look and feel throughout applications and keep Web application views componentized.

-- Lucene search engine to implement advanced queries.

-- Extended AJAX support on the server to automate AJAX detection and responses to make JavaScript and PHP programming easier.

-- UTF-8 character sets in Adobe PDF creation, featuring enablement of non-Latin characters like Kanji and Cyrillic when producing PDF documents.

-- Google GData Web services for building applications that leverage the Google application network.

Zend is offering a Zend Framework subscription support service, featuring consulting and a guaranteed per-incident response time.

Zend Framework has been downloaded more than 4 million times, according to Zend.

PHP's Enterprise Strengths and Weaknesses,Take 2

PHP was designed to solve what I (and others, such as PHP's creator, Rasmus Ledorf) call "The Web Problem," by which we mean the challenges found in the creation of dynamic server-side applications on the Internet or on an intranet. PHP was created to—and continues to evolve to—solve this single problem, which perhaps is the biggest reason why it's been a (if not the) Internet programming language of choice for such a long time. In fact, PHP is the fourth most popular programming language in the world, according to the TIOBE Programming Community Index, above C++, Perl, Python and Ruby.

In this article http://www.cio.com/article/197152 that explain why PHP is the premier solution for server-side Web scripting.

symfony open source php5 framework

Based on the concept of Rails / Django like framework only for PHP, here comes the MIT licensed symfony

Page Compression with PHP

A question that is often asked by new PHP programmers is:

“How do we compress the (HTML) page output?”

First of all, why would anyone want to compress their webpages? There are really two reasons why it is useful:

  1. The page loads faster, especially for users with slower internet connections
  2. The site uses less bandwidth, which means that the site, especially if it gets lots of traffic, is cheaper to run
The downside to compressing page output is that it uses more CPU processing power, but the benefits usually outweigh the extra processing that needs to take place server-side.

Techniques for Compressing Page Output


There are several ways to compress page output, which we will discuss below:

First of all, it is possible to activate it for all content (both PHP and non-PHP) served by your Apache web server by changing the configuration of Apache. However, for this post, we will focus on doing it with PHP, as that is the subject of this blog.

If you have access to your php.ini configuration file, the preferred method of compressing all PHP output is to do it by modifying the following configuration settings in that file to have these values:
zlib.output_compression = On
zlib.output_compression_level = 5

In the above code, 'zlib.output_compression_level' should be set to a value between 1 and 9, with the higher values giving more compression, but using more server (CPU) resources.

Alternatively, if you don’t have access to the php.ini file on your server, you can put the compression code directly in your PHP scripts. To do that, put the following line at the top of all of your PHP pages that you want compressed:
<?
ob_start("ob_gzhandler");?>

Either way you use, once you think you have everything in place, you can use one of many compression testing websites in order to verify that your site is indeed sending compressed output to browsers.

Is it worth it to set up page compression? In most cases, yes.

For example, on one site I was recently working on, we were serving up about 2 Million pages/month without compression. We had complaints of the site loading slowly for some users (the pages were large), as well as the bandwidth getting expensive, so I took steps to set up page compression using the (first) php.ini method.

After getting it configured, I saw a noticeable decrease in page loading time, even for me with my fast internet connection, and the bandwidth bill dropped to only around 30% of what it was before. At the same time, the load on the dual Xeon processor didn’t move up noticeably, so in this case, I considered it to be a success.

Redirects with PHP

Today, I thought I would knock out a relatively light subject before tackling heavier stuff in the upcoming weeks and months. That topic is implementing header redirects with PHP.

Header redirects are redirects that are handled instantaneously and transparently by the browser, and come in two common forms: 301 redirects and 302 redirects.

The difference between the two is that a 301 redirect is used to tell users that a particular page has permanently moved, and a 302 redirect is used to tell users that a page has only been moved temporarily.


To implement a redirect, the following code must be placed in your PHP script before it prints out any output. Because the redirect is sent in the HTTP header, if the PHP script outputs anything before the redirect header is set, PHP will automatically send headers along with the data that is printed out, and it is impossible to add other headers after data is printed.
301 Redirect:

<?
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.suresh-mobileweb.blogspot.com/");
?>


302 Redirect:

<?
header("HTTP/1.1 302 Moved Temporarily");
header("Location: http://www.suresh-mobileweb.blogspot.com/");
?>


One important thing to keep in mind when considering putting up a redirect, is that search engines will generally follow and pass link popularity on through 301 redirects, but not 302 redirects, so if the redirect is more or less permanent and you would like the search engine indexing/ranking to reflect that, then a 301 is the way to go.

PHP Coding Standards

Over at WACT the question of coding standards has raised it’s (ugly?) head. There’s now this page on the WIKI linking to more or less every PHP coding standards document that’s ever made it’s way online (feel free to add more).

By “coding standards” we’re talking whether you use tabs or spaces for indention, whether you name functions likeThis(), LikeThis() or like_this().

Now for some people this is really important. Risking flames, I think it’s just “nice to have”.

If you’re collaborating in a team, so long as you display basic “code hygene”, that’s enough. With reasonably experienced developers, conventions on naming class methods and so on will likely evolve without even needing to discuss them.

What’s more, think the subject is largely a distraction from more important issues. Try asking the next Java developer you meet what the word “standards” means to them… Having clearly defined APIs for things like Iterators is far more important, IMO.

Is it still that important for programs to be efficient?

This is a very interesting and timely question. The writer's original question was longer: "With the advances in processing power and memory is it really important to make programs that utilize them efficiently? Will we really notice the performance difference?" This is a topic that everyone should consider. The immediate answer most people would come up with is "Of course programs should still be efficient" and naturally that's true, but the real question is a matter of how much emphasis should be put on efficiency, and my answer is "Probably not as much as you think."

For example, in PHP, there are certain easy steps you can take to make a program more efficient (such as only connecting to a database when necessary, caching pages, etc.), but I almost always caution people against taking efficiency much past the larger picture. In all likelihood, all of the extra effort would only improve the performance by a minuscule amount. The same is true for most technologies. One of the things that makes Ruby's approach stand out is that the creator started with the understanding that the programmer's time is more valuable than the computer's, so he focused on creating a language that one could program in efficiently, even if that meant that it executed somewhat less so. And this leads me to another point: the technologies selected for a project will probably have a greater impact on the performance than any tweaking you do (although, to be fair, sloppy programming in any language will always be worse than good programming).

Secondarily, outside considerations will likely have a greater impact.  I just bought a new computer and rather than spend any time trying to get it to run as efficiently as possible (e.g., by enabling or disabling features), I dropped another $70 (US) to double the amount of RAM from 2GB to 4GB (and getting 4GB of laptop RAM for only $70 is gluttonous).


So, in short, my advice would be to pay attention to a program's (or site's) overall efficiency without spending too much effort on the little details. An exception would be made for very, very, very popular sites, where a small tweak in performance makes a huge difference to the server. For example, Yahoo! gets 3.5 billion hits a day. Any slight improvement to their site really does matter. For most people, projects, and sites, though, that is not the case.