MANUAL DE PHP

(y algo mas)windsurf pozo izquierdo
Google
search for in the  
ELMARRAJO.COM mysql bulma desarrollo web linux fedora html ayuda

windsurf mercedes camper

highlight_file

(PHP 4, PHP 5)

highlight_file -- Resaltado de sintaxis de un archivo

Descripción

mixed highlight_file ( string nombre_archivo [, bool devolver] )

La función highlight_file() imprime una versión con resaltado de sintaxis del código contenido en nombre_archivo usando los colores definidos en el resaltador de sintaxis incorporado de PHP.

Si el segundo parámetro devolver es definido a TRUE entonces highlight_file() devolverá el código resaltado en lugar de imprimirlo. Si el segundo parámetro no es definido a TRUE entonces highlight_file() devolverá TRUE si tiene éxito, o FALSE en caso de fallo.

Nota: El parámetro devolver apareció en PHP 4.2.0. Antes de esta versión, tenía el comportamiento predeterminado, que es FALSE

Nota: A partir de PHP 4.2.1, esta función es afectada también por safe_mode y open_basedir.

Atención

Debe tenerse cuidado cuando se usan la función highlight_file() para asegurarse de que no se revele inadvertidamente información sensible, tal como contraseñas o cualquier otro tipo de información que pueda crear un riesgo potencial de seguridad.

Muchos servidores son configurados para resaltar automáticamente archivos con la extensión phps. Por ejemplo, cuando se visite ejemplo.phps se mostrará el código fuente del archivo con su sintaxis resaltada. Para habilitar este comportamiento, agregue esta línea al archivo httpd.conf:

AddType application/x-httpd-php-source .phps

Vea también highlight_string().



add a note add a note User Contributed Notes
highlight_file
paul at cheddar dot vaughany dot com
21-Aug-2006 04:53
It's a basic idea but one maybe worth sharing.

<?php
switch($_GET['file']) {
   case
1:
      
highlight_file("file1.php");
       break;
   case
2:
      
highlight_file("file2.php");
       break;
   case
3:
      
highlight_file("file3.php");
       break;
   default:
      
header("Location: ".$_SERVER["PHP_SELF"]);
}
?>

Save the script as showfile.php and access it like this:

<a href="http://indices.com.es/showfile.html">Click here to see file 1 source code</a>

The default case is for people editing the URL to try to access further files. Just don't add any files you don't want users to see, and maybe hard-code in large, random numbers or MD5 hashes.
showsource at gmail dot com
07-Apr-2006 05:18
Please, be aware of just using marlon at mbwp dot nl example to show the sourcecode
Do as told in this manual, "CAUTION", do some check on what code to highlight.
Simply just using $_GET["file"] is very bad.
marlon at mbwp dot nl
05-Mar-2006 05:06
I use the folowing code to highlight a file with line numbers:

<?php
echo "<table bgcolor=#EEEEEE><tr><td width=30>";
for (
$i = 1; $i <= count(file($_GET['file'])); $i++) echo $i.".<br>";
echo
"</td><td>";
highlight_file($_GET['file']);
echo
"</td></tr></table>";
?>
msn at toolskyn dot nl
26-Feb-2006 01:18
I use this (simple and dirty) function in my tutorials to add linenumbers. I let all the linenumbers in one table cell so it is easier for people to copy and paste the code (so they don't have to remove all the linenumbers):

<?php
function highlight_with_linenum($file)
{
  
//open handle, set vars
  
$handle = fopen($file, "r");
  
$count = 1;
  
$lines = "";

  
//look line ends
  
while ($thisone = fread($handle, "1"))
   {
       if (
$thisone == "\n")
       {
          
//add number
          
$lines .= $count . "<br />";
          
$count++;
       }
   }   
  
//close handle
  
fclose($handle);

  
//highlight contents
  
$contents = highlight_file($file, TRUE);
      
  
//print output (you could as well return now)
  
print '<table><tr><td><code>' .
        
$lines . '</code></td><td>' .
        
$contents . '</td></tr></table>';   
}
?>

Maybe it's of use to someone
contact at soulpass dot com
29-Jan-2006 02:52
A couple side notes about my previous post regarding security:

When I previewed the post, one of the backslashes in the regular expression disappeared, so I escaped it with another backslash, and then it worked in the preview. When the note posted, both backslashes appeared. Hopefully it will work in this update. The correct regular expression should be:

(^/|\./)

Please change it if you use the suggestion in the post below.

Also, it would be a good idea to hide your valid_files.txt using .htaccess. The updated .htaccess is as follows:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.+).phps$ http://indices.com.es/index.html?f=$1 [L]
</IfModule>

<Files valid_files.txt>
order allow,deny
deny from all
</Files>

Sorry for the confusion...
contact at soulpass dot com
29-Jan-2006 01:20
I wanted to have a provision for highlighting source files that I have written. I also wanted people to be able to see the highlighted files from links on my blog (i.e. - the general public would be exposed to this as well).

Using highlight_string() would require me to update a second file every time I update the original script, but using highlight_file() brings up a major security risk!

I made the following code that goes at the top of highlighting script. Note that if you want to enable highlighting of a particular file, you'll have to add its path to a text file, as described below.

<?php
if (!isset($_GET['f']) || !file_exists($_GET['f'] . '.php') ||
   !
in_array($_GET['f'], array_map('trim', file('valid_files.txt'))) ||
  
preg_match('(^/|\\./)', $_GET['f']) || $_GET['f'] == 'index') {
   exit(
'Message to malicious visitor.');
}
?>

This just serves to keep people from trying to highlight files below the current directory (in my case, /source/). After this snippet, you could put some simple highlighting code that highlights the file using highlight_file($_GET['f'] . '.php');

Since I have the highlighting script saved as "http://indices.com.es/index.html," in my case the script is called with /source/http://indices.com.es/index.html?f=path/to/file

Notice that there is no .php extension. With this script, it appends ".php" automatically, thus effectively disallowing any file other than a PHP file to be highlighted (i.e., no .htaccess file will be highlighted on accident). The script also aborts if it detects a leading forward slash (/), or a period followed by a forward slash (./) anywhere in the requested file. I couldn't think of a case where ./ would be a valid request, but I could be wrong there.

Also note that a file called "valid_files.txt" goes in the same directory as the highlighting script. The format of this file is as follows:

path/to/file1
path/to/file2

Note that there is no extension here either because PHP is assumed in the script.

Finally, the script does not allow _itself_ to be highlighted. That's where "|| $_GET['f'] == 'index'" comes in. In case a security risk has not been covered here, we don't want anyone to see the measures, or lack thereof, that have been covered.

If you want to use an .htaccess file to clean up the URL, here's an idea for that:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.+).phps$ http://indices.com.es/index.html?f=$1 [L]
</IfModule>

The .htaccess file goes in the same directory as the highlighting script (again, in my case, /source/). With it, the script may be called with this URI: /source/path/to/file.phps

This also adds another security benefit, as people may now see that the files appears to be ending in .phps.

I know it's a bit messy, but it's also a big deal to have the script as secure as possible. If anyone has any suggestions, please post them.
ganchev at design dot bg
13-Jan-2006 12:40
here's a simple way to add line numbers and
optionally highlight the one that has error on it.
just pass file and line arguments as GET variables

<?php

$f
= fopen($_GET['file'], "r");
$count = 1;
$line = "";
echo
"<table>";
while (
$c = fread($f, "1")) {
 
$line .= $c;
  if (
$c == "\n") {
   echo
"<tr style='background: " . (($_GET['line'] == $count) ? "#eedddd" : "#ffffff") . "'><td width='10%'>$count.</td><td>" . highlight_string($line, TRUE) . "</td></tr>\n";
  
$line = "";
  
$count++;
  }
}
echo
"</table>";
fclose($f);

?>
dtroi50 at gmail dot com
09-Jan-2006 02:39
If you run a site that has PHP script examples and you want to show the source, instead of a phps file, just add the following code to the top of the script.

<?php
if(count($_GET)) {
highlight_file(__FILE__);
}
?>

Then to make a source link use this:

<?php
print'<a href="http://indices.com.es/.html">Show source</a>';
?>

Note that you don't have to use souce. If any get variables are set, it'll work.

-Tom
venski at gmail dot com
06-Jan-2006 05:21
I think it will be better if the variable contains the files that are allowed to be viewed. There can always befound a way to pass the name of a forbiddedn file that is not in the prohibited array.

Thus the code will be:

<?php
//array with files to allow
$allowed = array('http://indices.com.es/index.html', 'menu.php', 'about.php');

// get the filename
$file = $_GET[file];
if(
file_Exists($file)){
   if(
in_array($file, $allowed)){
      
// check if it is part of the allowed list
      
highlight_file($file); //highlight file
  
}
   else{
      
// not allowed. just die. do not warn ;)
      
die("");
   }
}
else{
  
// file doesnt exist
  
echo "The file does not exist.";     
}
?>
trukin at gmail dot com
08-Dec-2005 07:46
this function can be a high security risk. use something like in_array to check if a file is prohibited to be shown on screen.

<?
$ar
= array('config.php', 'http://indices.com.es/index.html', 'functions.php');    //array with files to denie
$file = $_GET[file];                    // iniziate the variable
if(file_Exists($file)){
   if(!
in_array($file, $ar)){    // check if it is prohibited
      
highlight_file($file); //highlight file
  
}else{    // prohibited file
      
echo "You do not have permision to see the ".$file." file.";
   }
}else{   
// file doesnt exist
  
echo "That file does not exist.";       
}
?>
Michael Newton (http://mike.eire.ca/)
06-Dec-2005 09:48
To print out the current file:

<?php highlight_file( __FILE__ ); ?>

Useful to add this as a header to all scripts (during development only, of course!)

<?php
if ($_GET['debug']) {
  
highlight_file( __FILE__ );
   exit;
}
?>
Vlad Alexa Mancini valexa at nextcode dot org
21-Feb-2005 11:19
Here is a small bash script that you can type at the console to make recursive symbolic .phps links for all your .php files starting at your curent directory

for f in `find -name '*.php'`; do ln -s `basename $f` $f's'; done

NOTE: You doubtedly want to do this at / as it will make such symlinks for all the php files on your filesystem

NOTE: This places the symlinks in the same directory as the php file that they are simlinking

And a simpler one that is not recursive and does the same thing but only for the php files in your current directory

for f in *.php; do ln -s $f $f's'; done
aidan at php dot net
26-Sep-2004 08:29
To add line numbers to source code, with optional function linking, use the below function:

http://aidan.dotgeek.org/lib/?file=function.highlight_file_linenum.php

A much more thorough and smarter, though slower version is here:

http://aidan.dotgeek.org/lib/?file=PHP_Highlight.php
csst0266 at cs dot uoi dot gr
13-Aug-2004 09:42
Here is a simple, yet useful, tip... Issuing the following command under a Unix-like OS:

ln -s your_script.php your_script.phps

Will result in the creation of a symbolic link (called your_script.phps) to the source code (your_script.php). This way you have (apart from the source code .php) the highlighted version of your script (.phps) accessible via your web browser.
zan at stargeek dot com
08-Jan-2003 10:24
here's how to use highlight_file to create a browseable archive of php scripts http://www.stargeek.com/scripts.php?script=7&cat=blog

Citas célebres

Hobres rectos como cañas... Es decir, que van a doblegarse al primer golpe de viento.

Joseph Joubert
Citas en tu mail
©Contenidos Gratis

Ilusiones Opticas
ilusion_optica_033.jpg
Contenidos Web

Chiste de... Era tan...
Miopía

Era tan miope que tenía las gafas en la nariz y no las veía.
Chistes en tu mail
©ContenidosGratis

Humor Gráfico
humor_grafico_007.jpg
Contenidos Web

Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos
Cake ManiaCake Mania
Jugadores: 6835
Categoría del juego: Acción
Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero.
Rainbow WebRainbow Web
Jugadores: 2199
Categoría del juego: Puzzles
Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente.
Mahjongg FortunaMahjongg Fortuna
Jugadores: 12462
Categoría del juego: Solitarios
Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta.
Chainz 2Chainz 2
Jugadores: 6955
Categoría del juego: Puzzles
Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más.
DeliciousDelicious
Jugadores: 4405
Categoría del juego: Acción
Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues!
BookwormBookworm
Jugadores: 4568
Categoría del juego: Palabras
Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos!
ZumaZuma
Jugadores: 4976
Categoría del juego: Acción
Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás!
Jewel of AtlantisJewel of Atlantis
Jugadores: 3798
Categoría del juego: Puzzles
Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis.
Jewel QuestJewel Quest
Jugadores: 3727
Categoría del juego: Puzzles
Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos!
Bejeweled 2Bejeweled 2
Jugadores: 3659
Categoría del juego: Puzzles
Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca.
Contenidos gratis en tu webSiguiente >>

Fotos divertidas
fotos_increibles_0473.jpg
Contenidos Web
microrobots avion deportes riesgo recetas cocina canaria juegos online gratis moto motociclismo horoscopos naranjas valencianas surf canarias montañismo ciudades turismo postales gratis library Horoscopos Diarios Windsurf Canarias
fregadero microondas placa electrica bañopreparar camper pantalla plananevera compresor electricacamper fiat ducato camper baño quimicomampara enrollable bañocamper aire climatizadofurgoneta surf windsurffurgoneta surf windsurftelevisor furgonetas camperfurgonetas camper cama

Sudoku del día
Nivel de dificultad: Fácil



Cómo jugar:
El juego consiste en colocar los números del 1 al nueve de tal forma que no se repita el mismo número en la columna, fila y caja (bloques 3x3 enmarcados).

©Contenidos Gratis | Sudoku en tu mail
Sucedió el...

30 de agosto de 1617

Fallece Santa Rosa de Lima, por la que se celebra el "Día de la Patrona de América".
Efemérides en tu mail
©Contenidos Gratis
windsurf canarias youtube porno canarias baleares valencia madrid fallera mayor campus party alcacer feria valencia fernando alonso loterias dinero inversiones violencia de genero makro empresas cartera soledad tolerancia metro valencia gobierno de españa violencia de genero UIMP navidad