Script for removing blank spaces before and after PHP tags

blank_spaces2.jpg 

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.

<?php
/***********************
*@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
clearstatcache();

//============ Code borrowed from php.net ===============
// 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 ){
            continue;
        }
        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/adodb-errorhandler.inc.php — contains trailing spaces
D:/xampp/xampp/htdocs/memento/vendors/rdfapi-php/api/util/adodb/adodb-memcache.lib.inc.php — contains trailing spaces

====================

About these ads

About Ritesh Agrawal

I am a applied researcher who enjoys anything related to statistics, large data analysis, data mining, machine learning and data visualization.
This entry was posted in PHP. Bookmark the permalink.

18 Responses to Script for removing blank spaces before and after PHP tags

  1. Pingback: Removing blank spaces before and after PHP tags - Part II « memento

  2. Kim Bach says:

    What an annoying bug (or is it a feature), thank you for posting your experiences

  3. Pingback: Kim Bach . Org » Blog Archive » PHP blues - drawing a blank

  4. ragrawal says:

    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.

  5. Pingback: Cannot modify header information - headers already sent « memento

  6. 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.

  7. ragrawal says:

    you are most welcome :-)

  8. Andy J says:

    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?
    Thanks,
    Andy

  9. ragrawal says:

    @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.

  10. Andy J says:

    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,
    Andy

  11. Tiago says:

    Just to say thanks! You save my day! lol

  12. edwinallenz says:

    Thanks it save me a lot of time.

  13. Shadab Shaikh says:

    Great! That script saved my life :) Thanks you Ritesh :)

  14. D says:

    Thanks for this script! It was a great help for me, I was becoming crazy.

  15. Pete says:

    Very old post at this point but this helped me very much today. Thanks :)

  16. Andy T says:

    Hi Ritesh,

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

  17. eddie says:

    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
    C:/wamp/www/wp-content/a/plugins/efplugin_class

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

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

    Thanks so much
    eddie

  18. Ammu says:

    wow thanks it saved me

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s