View source code using PHP


This tutorial will show you how to take a URL, read in the source CODE and then format it.
The code listed will assume that you are passing the URL as an encoded variable via GET with the name u.
First off here are the CSS styles you’ll need to format the code (you should customise these to suit your needs):

View Source Code CSS

<style type=”text/css”>

    body {
    
        background-color: #111111;
        font-family: Courier New, Courier, mono;
        font-size: 11px;
        color: #66CCFF;
    
    }
    
    span {
    
        color: #FFFFFF;
    
    }
    
    .linenumber {

        color: #FF9900;    
    
    }
    
    em {
    
        color: #666666;
    
    }
    
    h3 {
    
        font-family: Tahoma, Trebuchet MS, Arial;
        text-decoration: none;
    
    }
    
    .codelink {
    
        font-family: Tahoma, Trebuchet MS, Arial;
        text-decoration: none;
        font-size: 10px;
        color: #EEEEEE;
    
    }
    
    .codelink:hover {
    
        font-family: Tahoma, Trebuchet MS, Arial;
        text-decoration: underline;
        font-size: 10px;
        color: #66CCFF;
    
    }

</style>
Now we needs to decode the URL and use it to read the HTML in via an HTTP file stream. This is very easy to do, we just use PHP’s file() function.

Read in HTML from URL

<?php

    $url = “http://” . $_SERVER[ 'HTTP_HOST' ] . “/” . urldecode( $_GET[ "u" ] );
    $lines = file( $url );

?>
No we’ve got the HTML stored in a variable we need to use htmlspecialchars() to make the source code display the same way through the browser as it would look like if we were to view the source. We then do some string replacement to insert out CSS styles into the HTML so that the tags and the tag contents are different colours:

Display and Format the HTML

<?php

    foreach( $lines as $line_num => $line ) {

    $line = htmlspecialchars( $line );
    $line = str_replace( “&lt;”, ‘<span>&lt;’, $line );
    $line = str_replace( “&gt;”, ‘&gt;</span>’, $line );
    $line = str_replace( “&lt;!–”, ‘<em>&lt;!–’, $line );
    $line = str_replace( “–&gt;”, ‘–&gt;</em>’, $line );

    echo “<span class=\”linenumber\”>Line <strong>$line_num </strong></span> : ” . $line . “<br/>\n”;

}

?>
That’s all there is to it! If you saved this page as viewsource.php then you’d link to it like this:

The View Source Code Link

<a href=”viewsource.php?u=<?= $_SERVER[ "PHP_SELF" ] ?>”>View Source</a>


0 Response to View source code using PHP

Post a Comment