IMC!


Contents


Photos

 







Browsing around...
News  News Links  Links Blog  Blog Italiano  Español 
Show code in a web page

Maybe you want to show some programming code in a web page. There are some problems about the special characters (or escape sequences), which can give problems for the page rendering or be shown badly. To avoid these problems, PHP gives us the functions highlight_file(filename), which reads the code from a file and visualizes it, and highlight_string(string), which reads code from a string and visualizes it. Both functions substitute the HTML special characters with the right entities, in order to format correctly the code for the web. If the code is PHP, the functions colours the commands (as in the advanced programming editors). Here you can find two PHP functions to show without problems any kind of programming code.

Code of show_code1.php
<?PHP
function show_code($path)
{
# Shows file name
$name=substr(strrchr($path'/'),1);
if (
$name
{
  echo 
'<DIV style="font-family: Verdana; font-size: 12px;" align="left"><B>Code of ' $name '</B></DIV>';
}
else
{
  echo 
'<DIV style="font-family: Verdana; font-size: 12px;" align="left"><B>Code of ' $path '</B></DIV>';
}
#Shows content
echo '<DIV style="padding: 5px; border: dashed 1px #99c; background-color: #eef; width:570px; overflow: auto;">';
highlight_file($path,0);
echo 
'</DIV>';
}

show_code('show_code1.php');
?>


Sometimes the function highlight_file() is disabled for secutiry reasons. In this situation, you have to open the file with the code, read the code to a string, show the string with highlight_string(), which usually is not disabled.This is the code:

Code of show_code2.php
<?PHP
function show_code($path)
{
# Shows file name
$name=substr(strrchr($path'/'),1);
if (
$name
{
  echo 
'<DIV style="font-family: Verdana; font-size: 12px;" align="left"><B>Code of ' $name '</B></DIV>';
}
else
{
  echo 
'<DIV style="font-family: Verdana; font-size: 12px;" align="left"><B>Code of ' $path '</B></DIV>';
}
#Shows content
echo '<DIV style="padding: 5px; border: dashed 1px #99c; background-color: #eef; width:570px; overflow: auto;">';
$codice=file_get_contents($path);
highlight_string($codice,0);
echo 
'</DIV>';
}

show_code('show_code2.php');
?>







Comments

No comment present!

Write a comment

You can write here a comment to the article you've just read. Smiles, links and images are not allowed. The maximum comment length is 4000 characters. Please be polite, all the offensive messages will be deleted.

Your comment (lascia bianco!):
Uses (max 25 characters, required)
Web site (max 255 characters, optional)
e-Mail (max 255 characters, optional, will not be published) Your opinion (lascia bianco!):
Comment (max 4000 characters, required):





Valid HTML 4.01 Transitional
E-Mail - 53.2 ms

Valid HTML 4.01 Transitional