Escape desde HTML

Todo lo que se encuentra fuera de un par de etiquetas de apertura/cierre es ignorado por el analizador PHP, lo que permite tener ficheros PHP mezclando contenidos. Esto permite a PHP estar contenido en documentos HTML, para crear por ejemplo plantillas.

Ejemplo #1 Integrar PHP en HTML

<p>Esto será ignorado por PHP y mostrado en el navegador.</p>
<?php echo 'Mientras que esto será analizado por PHP.'; ?>
<p>Esto también será ignorado por PHP y mostrado en el navegador.</p>

Esto funciona como se espera porque cuando el intérprete PHP encuentra la etiqueta de cierre ?>, simplemente comienza a mostrar lo que encuentra (a excepción de la nueva línea que es inmediatamente seguida: ver la instrucción de separación) hasta que encuentre otra etiqueta de apertura incluso si PHP se encuentra en medio de una instrucción condicional, en cuyo caso, el intérprete determinará la condición a tener en cuenta antes de tomar una decisión sobre lo que debe ser mostrado. Ver el siguiente ejemplo.

Uso de estructuras con condiciones

Ejemplo #2 Escape avanzado usando condiciones

<?php if ($expression == true): ?>
Esto será mostrado si la expresión es verdadera.
<?php else: ?>
De lo contrario, esto será mostrado.
<?php endif; ?>
En este ejemplo, PHP ignorará los bloques donde la condición no se cumpla, incluso si están fuera de las etiquetas de apertura/cierre de PHP. PHP los ignorará según la condición ya que el intérprete PHP pasará los bloques que contienen lo que no se cumple por la condición.

Para mostrar grandes bloques de texto, es más eficiente salir del modo de análisis de PHP en lugar de enviar el texto a través de la función echo o print.

Nota:

Si PHP está integrado en un documento XML o XHTML, la etiqueta PHP estándar <?php ?> debe ser utilizada para mantener la conformidad con los estándares.

add a note

User Contributed Notes 3 notes

up
404
quickfur at quickfur dot ath dot cx
14 years ago
When the documentation says that the PHP parser ignores everything outside the <?php ... ?> tags, it means literally EVERYTHING. Including things you normally wouldn't consider "valid", such as the following:

<html><body>
<p<?php if ($highlight): ?> class="highlight"<?php endif;?>>This is a paragraph.</p>
</body></html>

Notice how the PHP code is embedded in the middle of an HTML opening tag. The PHP parser doesn't care that it's in the middle of an opening tag, and doesn't require that it be closed. It also doesn't care that after the closing ?> tag is the end of the HTML opening tag. So, if $highlight is true, then the output will be:

<html><body>
<p class="highlight">This is a paragraph.</p>
</body></html>

Otherwise, it will be:

<html><body>
<p>This is a paragraph.</p>
</body></html>

Using this method, you can have HTML tags with optional attributes, depending on some PHP condition. Extremely flexible and useful!
up
77
ravenswd at gmail dot com
15 years ago
One aspect of PHP that you need to be careful of, is that ?> will drop you out of PHP code and into HTML even if it appears inside a // comment. (This does not apply to /* */ comments.) This can lead to unexpected results. For example, take this line:

<?php
$file_contents
= '<?php die(); ?>' . "\n";
?>

If you try to remove it by turning it into a comment, you get this:

<?php
// $file_contents = '<?php die(); ?>' . "\n";
?>

Which results in ' . "\n"; (and whatever is in the lines following it) to be output to your HTML page.

The cure is to either comment it out using /* */ tags, or re-write the line as:

<?php
$file_contents
= '<' . '?php die(); ?' . '>' . "\n";
?>
up
27
sgurukrupa at gmail dot com
11 years ago
Although not specifically pointed out in the main text, escaping from HTML also applies to other control statements:

<?php for ($i = 0; $i < 5; ++$i): ?>
Hello, there!
<?php endfor; ?>

When the above code snippet is executed we get the following output:

Hello, there!
Hello, there!
Hello, there!
Hello, there!
To Top