Different Syntax Highlighting
Different Syntax Highlighting

There are different ways of highlighting your PHP code, in this tutorial we will cover some ways of doing it. Highlighting your code makes it look cleaner, easier to read and will make it well... look like an actual code. Below we will explain some of this methods.

highlight_string function

This will highlight your specified PHP code from a variable or database output as shown in example below.

<?php
  
  //Some PHP code and put in a variable
  $code = "<?php echo \"Hello world!\"; ?>";
  
  //Use the highlight_string() function
  highlight_string($code);

?>

Remember to escape any quotes or you will get an error.

highlight_file function

This function will display the highlighted PHP code from a file as shown in the example below.


** IMPORTANT (from PHP.net): Care should be taken when using the highlight_file() function to make sure that you do not inadvertently reveal sensitive information such as passwords or any other type of information that might create a potential security risk.

<?php

  //Some PHP code
  $ip = $_SERVER["REMOTE_ADDR"];
  echo "Your IP $ip";

?>

Save the code above, say you save it as filename.php, then you could use the highlight_file function for the filename.php and include it to another file.

<?php

  //Include filename.php
  highlight_file("filename.php");

?>

That would include the filename.php with PHP code highlighted.

.phps extension

Saving your file with ".phps" extension will automatically highlight your PHP code. All you have to do is run it as shown in example below.
NOTE: This feature is not enable on all server so if you find that it's not working then it might be disable on your webhost server.

<?php
  
   //Save this code with ".phps" extension
   mysql_connect('localhost','user','pass');
   mysql_select_db('database') or die(mysql_error()); 

?>

All you have to do is to run the file. Dont forget the trailing "s" or it will not work.

custom function

This maybe the most convenient way of highlighting your PHP code. All the above are PHP generated and sometimes they have their "flaw". Also they are not XHTML valid with the use of <code> and <font> tag. You could also easily add new features if you make your own function.

This is a great function for highlighting your PHP code. It's XHTML valid, you can easily edit the syntax colors and you dont need the php tag (<?php, ?>).

The End

Well thats about it for this tutorial. I suggest using the custom function above or make your own if you wish to highlight your PHP code.


Print this page | Discuss this tutorial

Home | Site Map | Privacy Policy | Advertising | Contact Us
Copyright © 2006-2014 r2xDesign.net - All Rights Reserved.
eXTReMe Tracker