Script for removing blank spaces before and after PHP tags


For last four days, I have been trying to get a valid RSS output using CakePHP. Everything was working fine, except that there were some blank spaces before RSS declaration. Because of this, none of the browsers were recognizing cakephp output as RSS feed. The problem was simple; I left blank spaces and few new lines before and after PHP opening and closing tags somehwere in model, controller, view, component or in a helper. But the challenge was identifying which filset of files contains these spaces. Since, I didn’t find any script that can go recursively through each directory and identify PHP files that contain any blank spaces, I wrote one myself (see below). And, I would like to thank AD7six, seacloud9, Jon, Mike, francky for keeping patience and helping me in solving my RSS feed problem. I almost eat up all of their brains on CakePHP forum 😦 . You can see the actual CakePHP forum discussion here

Note: This script only identifies files that contains leading or trailing blank spaces. It does not modify the file itself.

*@author: Ritesh Agrawal
*@description: Identifies php files that contain leading or trailing spaces before or after PHP opening or closings tags
*@version: 1.0
*@date: Nov 06, 2007
@todo – check only *.PHP or *.CTP files rather than checking all of the files
      – html based output
//Set Source Path
$sourcepath = “D:/xampp/xampp/htdocs/memento”;
//Regex Express to test leading and trailing spaces
define(“PRE”, “#^[\n\r|\n\r|\n|\r|\s]+<\?php#”);
define(“POST”, “#\?>[\n\r|\n\r|\n|\r|\s]+$#”);

//Clear the file Status Cache

//============ Code borrowed from ===============
// Replace \ by / and remove the final / if any
$root = ereg_replace( “/$”, “”, ereg_replace( “[\\]”, “/”, $sourcepath ));
// Touch all the files from the $root directory
if( false === m_walk_dir( $root, “check”, true )) {
    echo “‘{$root}’ is not a valid directory\n”;

// Walk a directory recursively, and apply a callback on each file
function m_walk_dir( $root, $callback, $recursive = true ) {
    $dh = @opendir( $root );
    if( false === $dh ) {
        return false;
    while( $file = readdir( $dh )) {
        if( “.” == $file || “..” == $file ){
        call_user_func( $callback, “{$root}/{$file}” );
        if( false !== $recursive && is_dir( “{$root}/{$file}” )) {
            m_walk_dir( “{$root}/{$file}”, $callback, $recursive );
    closedir( $dh );
    return true;
//============== end ======================
//If file, checks whether there is any leading spaces before opening PHP tag or
// trailing spaces after closing PHP tag
function check( $path ) {
    if( !is_dir( $path )) {
        $fh = file_get_contents($path);
    if(preg_match(PRE, $fh))
        echo $path. ” — contains leading spaces \n”;
  if(preg_match(POST, $fh))
        echo $path . ” — contains trailing spaces \n”;


To run this script, copy it in a blank file and name it as cleaner.php. Change the sourcepath variable to your cakephp application folder. Finally run the file from the command prompt using the following command

d:>PHP cleaner.php > output.txt

This will create an output.txt file like this

======= Output.txt ==========

 D:/xampp/xampp/htdocs/memento/vendors/rdfapi-php/api/syntax/RssParser.php — contains trailing spaces
D:/xampp/xampp/htdocs/memento/vendors/rdfapi-php/api/util/adodb/ — contains trailing spaces
D:/xampp/xampp/htdocs/memento/vendors/rdfapi-php/api/util/adodb/ — contains trailing spaces


Posted in PHP

22 thoughts on “Script for removing blank spaces before and after PHP tags

  1. hi Kim,

    Thanks. I understand the frustration of leaving blank spaces in PHP. I struggled with my more than 100s of PHP files and finally thought it might be worth to spend some time writing a script that can tell me where the blank spaces are.

  2. Wow. You have saved my life. Thank you so much for posting this script. I have been going insane trying to track down all those white spaces, digging through hundreds of files. Yikes. I owe you a beer.

  3. Hiya,
    Thanks for posting this. I do have a problem with:
    $sourcepath = “C:/xampp/htdocs/cake/reuser”;

    in my output.txt I have:
    Parse error: syntax error, unexpected ‘:’ in C:\xampp\htdocs\utils\cleaner.php on line 11

    I wonder if you could please advise?

  4. @Andy,

    you will need to replace ` with quotes. Paste the above code in any text editor and search and replace “ with ” (double quote). Then, search and replace ` with ‘ (single quote).

    This should solve your problem.

  5. Hi Ritesh,

    Thanks for the quick reply. The script now works perfectly. This is very useful to me as I’m new to PHP and CakePHP and I’ve already stumbled into the “Cannot modify header information – headers already sent by ..” problem.

    Thanks very much,

  6. Hi Ritesh,

    Many thanks for the script, it has helped me uncover trailing space issues in my WordPress themes.

  7. Hi Ritesh,
    Sorry I am really new to running scripts like this, hence I don’t know how to use the script
    my questions are:
    can I use it for any PHP file?

    In what directrory do i put cleaner.php ?

    I have localhost

    and in that folder I have a files named “phpluginClass.php”

    I am using this c:>PHP cleaner.php > output.txt

    Thanks so much

  8. Thanks for this wonderful script… I was getting this same error on my wordpress site, after removing all white spaces from mentioned files, my issue is also fixed now.

  9. Thank you so much! Helped me as well, found an errant leading whitespace that I would probably have lost all my hair trying to find!

    Note ereg_replace has to be updated to preg_replace for this to work– I just skipped the replacement on non-windows hosts by changing $root ereg_replace… to:

    //============ Code borrowed from ===============
    // Replace \ by / and remove the final / if any
    $root = $sourcepath;

Leave a Reply to Shadab Shaikh Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.