Sunday, February 17, 2008

Como manejar archivos con Php

Apertura de un archivo con PHP

La función utilizada para abrir un archivo en PHP es fopen, la sintaxis.

fp_handler=fopen(“path”,”modo”);

Path es la ruta completa del archivo a abrir, si el path comienza con “http://” se realiza una conexión a la URL indicada y se abre la página como si fuera un archivo (con las limitaciones lógicas, por ejemplo no es posible escribir).
Los modos en los que se puede abrir un archivo son:

r Sólo lectura
r+ Lectura y escritura
w Sólo escritura, si no existe el archivo lo crea, si existe lo trunca
w+ Lectura y escritura, si existe lo trunca, si no existe lo crea
a Modo append sólo escritura si no existe lo crea
a+ Modo append lectura y escritura si no existe lo crea

La función devuelve un file_handler que luego debe ser usado en todas las funciones de tipo fnombre_funcion, como por ejemplo fgets, fputs, fclose, fread, fwrite, etc.

Lectura desde un archivo con Php

Las funciones que pueden usarse para leer un archivo son:

string=fgets(file_handler, longitud) : Lee una línea de texto hasta el fin de línea o bien hasta que se cumpla la longitud indicada, devuelve el resultado en la variable pasada. El archivo debe estar abierto con fopen.

var=fread(file_handler, cantidad): Lee la cantidad de bytes indicados ignorando saltos de línea y deja el resultado en la variable var.

Ejemplo

$buffer=fread($fp, 1024); //Lee 1Kb desde el archivo cuyo handler es $fp

string=fgetss(file_handler, longitud) Idéntica a fgets con la diferencia de que los tags html son eliminados del archivo a medida que se lee el mismo. Opcionalmente puede pasarse una lista de tags que no deben ser eliminados.

Ejemplo:

$string=fgetss($fp,999999,”<b> <i> <table> <tr> <td>”);

Lee una línea (de cualquier longitud) eliminando los tags html excepto los indicados como segundo parámetro. Los tags que cierran los tags especificados en la lista de tags permitidos tampoco son eliminados.

Escritura a un archivo con Php

fwrite(file_handler, variable, longitud);

Escribe la variable al archivo indicado por file_handler. Si esta indicado el parámetro “longitud” (que es opcional) se escribirán tantos bytes como la longitud indicada por dicho parámetro o como la longitud de la variable, en aquellos casos en que el parámetro longitud es mayor que la longitud de la variable.
La función devuelve la cantidad de bytes escritos en el archivo.

Ejemplo:

$q = fwrite($fp,$buffer,999999);

fputs es idéntico a fwrite y funciona de la misma manera. (es un alias).

Cierre de archivos con Php

fclose(file_handler)

Cierra un archivo abierto con fopen.

Fin de archivo con Php

boolean = feof(file_handler);

Devuelve verdadero si no quedan más bytes para leer en el archivo o si se produce algún tipo de error al leer.

Ejemplo:
$fp=fopen(“/usr/luis/archivo.txt”,”r”);
while(!feof($fp)) {
$s=fgets($fp,999999);
print(“$s”);
}



Manejo de archivos con Php

PHP provee funciones para copiar, renombrar, mover y borrar archivos y directorios, las funciones son:

rename(path_origen, path_destino); Renombra un archivo.

Ejemplo:
$newname=”/usr/eduardo/file.txt”;
Rename(“/usr/eduardo/archivo.txt”,”$newname”);

unlink(path_a_borrar); Elimina un archivo.

rmdir(directorio_a_borrar); Elimina un directorio (debe estar vacío)

mkdir(path_a_crear); Crea un directorio Nuevo.

copy(path_origen, path_destino); Copia un archivo o varios.

Otras funciones útiles con Php

fseek(file_handler,posicion,desde) Posiciona el puntero de lectura/escritura de un archivo en el offset indicado. El parámetro “desde” es opcional y puede tomar uno de los siguientes valores:

SEEK_SET (el offset es absoluto)
SEEK_CUR (el offset es relativo a la posición actual)
SEEK_END (el offset es desde el final del archivo)

El default es SEEK_SET

ftruncate(file_handler, longitud) Trunca el archivo indicado a la longitud en bytes especificada.

array=file(path) Lee un archivo de texto y devuelve un vector donde cada elemento del vector es una línea del archivo.

file_exists(path) Devuelve true/false según el path indicado exista o
no.

filemtime(path) Devuelve la fecha de última modificación de un archivo en formato Unix. (ver manejo de fechas)

filesize(path) Devuelve el tamaño de un archivo.

filetype(path) Devuelve el tipo de un archivo.

flock(file_handler,modo) Lockea un archivo (independientemente del filesystem),
el modo puede ser:

1: Lock en modo lectura (compartido)
2: Lock en modo escritura (exclusivo)
3: Release del lock adquirido.

Al hacer un fclose del archivo se liberan automáticamente los locks adquiridos sobre el mismo.
Si flock no puede obtener el lock espera hasta que el lock este disponible, si se quiere que flock no bloquee el script sumar 4 al modo (modos: 5,6,7) y consultar por el valor devuelto por la función: true si el lock fue adquirido o false si no fue adquirido. Usando esta función pueden implementarse mecanismos de sincronización entre procesos.

fpassthru(file_handler) Escribe al standard_output el contenido del archivo.

readfile(path) Lee todo el archivo y lo escribe al standard output.

is_dir(path) True/false según el path sea un directorio

is_file(path) True/false según el path sea un archivo

tempnam(path) Dado el nombre de un directorio devuelve un nombre de archivo que no existe en el directorio dado (útil para crear archivos temporarios)

Manejo de directorios con Php

Las siguientes funciones de PHP están orientadas a recorrer directorios y obtener los archivos que se encuentran dentro de ellos. Las funciones son independientes del file-system con lo cual funcionan correctamente tanto en UNIX como en Windows.

directory_handle = opendir(path);
Abre el directorio pasado como parámetro y devuelve un handler al directorio, previamente puede usarse la función is_dir(path) para verificar si el path es un directorio en caso de que esta validación sea necesaria.

string = readdir(directory_handler)
Lee la próxima entrada en el directorio abierto con opendir, usualmente las dos primeras entradas de un directorio con “.” y “..” por lo que el código que procesa los archivos del directorio debe tener esto en cuenta para no procesar dichas entradas en caso de que tal cosa no sea deseable.

closedir(directory_handler)
Cierra un handler abierto con opendir.

rewinddir(directory_handler)
Rebobina el puntero interno de un directorio para que apunte nuevamente al comienzo del mismo.

Estructuras de control en php: la estructura "if"

El caso de la instruccion "IF" es una de las características más importantes de muchos idiomas, incluido PHP. Permite la ejecución condicional de fragmentos de código. PHP cuenta con una estructura que es similar a la de C:

if (expr)

statement

La expresión se evalúa a su valor Boolean. Si la expresión evalúa a TRUE, PHP ejecutará las instrucciones, y si se evalúa a FALSE la ignora.

El siguiente ejemplo se mostrará que "a es mayor que b" si $ a es mayor que $ b:

<?php

if ($a > $b)

echo "a is bigger than b";

?>

A menudo, lo que se quiere es tener más de una declaración para ser ejecutado condicionalmente. Por supuesto, no hay necesidad de envolver cada declaración con una cláusula IF. En lugar de ello, podemos agrupar varias sentencias. Por ejemplo, este código mostrará "a es mayor que b" si $ a es mayor que $ b, y luego asignar el valor de $ a a $ b:

<?php

if ($a > $b) {

echo "a is bigger than b";

$b = $a;

}

?>

La declaracion IF se pueden anidar indefinidamente en el marco de otras estructuras de control, que le proporciona una total flexibilidad para la ejecución condicional de las diferentes partes de tu programa.

Estructuras de Control en PHP: elseif

elseif, como su nombre sugiere, es una combinación de if y else. Como else, extiende una sentencia if para ejecutar una sentencia diferente en caso de que la expresión if original se evalúa como FALSE. No obstante, a diferencia de else, ejecutará esa expresión alternativa solamente si la expresión condicional elseif se evalúa como TRUE. Por ejemplo, el siguiente código mostraría a es mayor que b, a es igual a b o a es menor que b:

  

<?php

if ($a > $b) {

print "a es mayor que b";

} elseif ($a == $b) {

print "a es igual que b";

} else {

print "a es mayor que b";

}

?>


Puede haber varios elseifs dentro de la misma sentencia if. La primera expresión elseif (si hay alguna) que se evalúe como TRUE se ejecutaría. En PHP, también se puede escribir 'else if' (con dos palabras) y el comportamiento sería idéntico al de un 'elseif' (una sola palabra). El significado sintáctico es ligeramente distinto (si estas familiarizado con C, es el mismo comportamiento) pero la línea básica es que ambos resultarían tener exactamente el mismo comportamiento.

La sentencia elseif se ejecuta sólo si la expresión if precedente y cualquier expresión elseif precedente se evalúan como FALSE, y la expresión elseif actual se evalúa como TRUE.

Variables variables en PHP

A veces es conveniente tener nombres de variables variables. Dicho de otro modo, son nombres de variables que se pueden establecer y usar dinámicamente. Una variable normal se establece con una sentencia como:

<?php

$a = "hello";

?>

Una variable variable toma el valor de una variable y lo trata como el nombre de una variable. En el ejemplo anterior, hello, se puede usar como el nombre de una variable utilizando dos signos $. p.ej.

<?php

$$a = "world";

?>

En este momento se han definido y almacenado dos variables en el árbol de símbolos de PHP: $a, que contiene "hello", y $hello, que contiene "world". Es más, esta sentencia:

<?php

echo "$a ${$a}";

?>

produce el mismo resultado que:

<?php

echo "$a $hello";

?>

p.ej. ambas producen el resultado: hello world.

Para usar variables variables con matrices, hay que resolver un problema de ambigüedad. Si se escribe $$a[1] el intérprete necesita saber si nos referimos a utilizar $a[1] como una variable, o si se pretendía utilizar $$a como variable y el índice [1] como índice de dicha variable. La sintaxis para resolver esta ambigüedad es: ${$a[1]} para el primer caso y ${$a}[1] para el segundo.

Tener en cuenta que variables variables no pueden usarse con Matrices superglobales. Esto significa que no se pueden hacer cosas como ${$_GET}.

Qué es PHP?

PHP (acrónimo de "PHP: Hypertext Preprocessor") es un lenguaje de "código abierto" interpretado, de alto nivel, embebido en páginas HTML y ejecutado en el servidor.

Una respuesta corta y concisa, pero, ¿qué significa realmente? Un ejemplo nos aclarará las cosas:

 

<html>

<head>

<title>Ejemplo</title>

</head>

<body>

<?php

echo "Hola, soy un script PHP!";

?>

</body>

</html>

Puede apreciarse que no es lo mismo que un script escrito en otro lenguaje de programación como Perl o C -- En vez de escribir un programa con muchos comandos para crear una salida en HTML, escribimos el código HTML con cierto código PHP embebido (incluido) en el mismo, que producirá cierta salida (en nuestro ejemplo, producirá un texto). El código PHP se incluye entre etiquetas especiales de comienzo y final que nos permitirán entrar y salir del modo PHP.

Lo que distingue a PHP de la tecnología Javascript, la cual se ejecuta en la máquina cliente, es que el código PHP es ejecutado en el servidor. Si tuviésemos un script similar al de nuestro ejemplo en nuestro servidor, el cliente solamente recibiría el resultado de su ejecución en el servidor, sin ninguna posibilidad de determinar qué código ha producido el resultado recibido. El servidor web puede ser incluso configurado para que procese todos los archivos HTML con PHP.

Lo mejor de usar PHP es que es extremadamente simple para el principiante, pero a su vez, ofrece muchas características avanzadas para los programadores profesionales.

Que se puede hacer con PHP?

PHP puede hacer cualquier cosa que se pueda hacer con un script CGI, como procesar la información de formularios, generar páginas con contenidos dinámicos, o enviar y recibir cookies. Y esto no es todo, se puede hacer mucho más.

Existen tres campos en los que se usan scripts escritos en PHP.

Scripts del lado del servidor. Este es el campo más tradicional y el principal foco de trabajo. Se necesitan tres cosas para que esto funcione. El intérprete PHP (CGI ó módulo), un servidor web y un navegador. Es necesario correr el servidor web con PHP instalado. El resultado del programa PHP se puede obtener a través del navegador, conectándose con el servidor web. Consultar la sección Instrucciones de instalación para más información.

Scripts en la línea de comandos. Puede crear un script PHP y correrlo sin ningún servidor web o navegador. Solamente necesita el intérprete PHP para usarlo de esta manera. Este tipo de uso es ideal para scripts ejecutados regularmente desde cron (en *nix o Linux) o el Planificador de tareas (en Windows). Estos scripts también pueden ser usados para tareas simples de procesamiento de texto.

Escribir aplicaciones de interfaz gráfica. Probablemente PHP no sea el lenguaje más apropiado para escribir aplicaciones gráficas, pero si conoce bien PHP, y quisiera utilizar algunas características avanzadas en programas clientes, puede utilizar PHP-GTK para escribir dichos programas. También es posible escribir aplicaciones independientes de una plataforma. PHP-GTK es una extensión de PHP, no disponible en la distribución principal.

PHP puede ser utilizado en cualquiera de los principales sistemas operativos del mercado, incluyendo Linux, muchas variantes Unix (incluyendo HP-UX, Solaris y OpenBSD), Microsoft Windows, Mac OS X, RISC OS y probablemente alguno más. PHP soporta la mayoría de servidores web de hoy en día, incluyendo Apache, Microsoft Internet Information Server, Personal Web Server, Netscape e iPlanet, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd y muchos otros. PHP tiene módulos disponibles para la mayoría de los servidores, para aquellos otros que soporten el estándar CGI, PHP puede usarse como procesador CGI.

De modo que, con PHP tiene la libertad de elegir el sistema operativo y el servidor de su gusto. También tiene la posibilidad de usar programación procedimental o programación orientada a objetos. Aunque no todas las características estándar de la programación orientada a objetos están implementadas en la versión actual de PHP, muchas bibliotecas y aplicaciones grandes (incluyendo la biblioteca PEAR) están escritas íntegramente usando programación orientada a objetos.

Con PHP no se encuentra limitado a resultados en HTML. Entre las habilidades de PHP se incluyen: creación de imágenes, archivos PDF y películas Flash (usando libswf y Ming) sobre la marcha. Tambié puede presentar otros resultados, como XHTM y archivos XML. PHP puede autogenerar éstos archivos y almacenarlos en el sistema de archivos en vez de presentarlos en la pantalla.

Quizás la característica más potente y destacable de PHP es su soporte para una gran cantidad de bases de datos. Escribir un interfaz vía web para una base de datos es una tarea simple con PHP. Las siguientes bases de datos están soportadas actualmente:

  • Adabas D
  • Ingres
  • Oracle (OCI7 and OCI8)
  • dBase
  • InterBase
  • Ovrimos
  • Empress
  • FrontBase
  • PostgreSQL
  • FilePro (read-only)
  • mSQL
  • Solid
  • Hyperwave
  • Direct MS-SQL
  • Sybase
  • IBM DB2
  • MySQL
  • Velocis
  • Informix
  • ODBC
  • Unix dbm

También contamos con una extensión DBX de abstracción de base de datos que permite usar de forma transparente cualquier base de datos soportada por la extensión. Adicionalmente, PHP soporta ODBC (el Estándar Abierto de Conexión con Bases de Datos), asi que puede conectarse a cualquier base de datos que soporte tal estándar.

PHP también cuenta con soporte para comunicarse con otros servicios usando protocolos tales como LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (en Windows) y muchos otros. También se pueden crear sockets puros. PHP soporta WDDX para el intercambio de datos entre lenguajes de programación en web. Y hablando de interconexión, PHP puede utilizar objetos Java de forma transparente como objetos PHP Y la extensión de CORBA puede ser utilizada para acceder a objetos remotos.

PHP tiene unas características muy útiles para el procesamiento de texto, desde expresiones regulares POSIX extendidas o tipo Perl hasta procesadores de documentos XML. Para procesar y acceder a documentos XML, soportamos los estándares SAX y DOM. Puede utilizar la extensión XSLT para transformar documentos XML.

Si usa PHP en el campo del comercio electrónico, encontrará muy útiles las funciones Cybercash, CyberMUT, VeriSign Payflow Pro y CCVS para sus programas de pago.

Para terminar, contamos con muchas otras extensiones muy interesantes, las funciones del motor de búsquedas mnoGoSearch, funciones para pasarelas de IRC, utilidades de compresión (gzip, bz2),, conversión de calendarios, traducción, etc.

Como saber que navegador usa un visitante con PHP

Para hacerlo, vamos a consultar la información que el navegador nos envía como parte de su petición HTTP. Esta información es guardada en una variable. Las variables siempre comienzan con un signo de dólar ("$") en PHP. La variable que vamos a utilizar en esta situación es $_SERVER["HTTP_USER_AGENT"].

$_SERVER es una variable reservada por PHP que contiene toda la información del servidor web. Es conocida como Autoglobal (o Superglobal).

Para poder ver esta variable solo necesitamos el siguiente codigo:

<?php echo $_SERVER["HTTP_USER_AGENT"]; ?>

esto nos dara un resultado similar a:

Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)

$_SERVER es simplemente una variable que se encuentra disponible automáticamente en PHP.

Por ejemplo, si quisiéramos detectar el uso de "Internet Explorer", haríamos algo así:

   

<?php

if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE")) {

echo "Está usando Internet Explorer<br />";

}

?>

esto nos dara un resultado similar a:

Esta usando Internet Explorer

En el caso anterior estamos buscando "MSIE" dentro de $_SERVER["HTTP_USER_AGENT"]. Si la cadena fue encontrada, la función devolverá verdadero ("TRUE"), la declaración "if" se evalúa a verdadero ("TRUE") y el código adentro de las llaves {} es ejecutado. De otra manera no resulta ejecutado.

Contador de usuarios activos con PHP

Con este script podemos contar los usuarios activos con PHP.

No vamos a usar ninguna base de datos. En su lugar usaremos un archivo llamado usuarios.dat

Creamos nuestro script PHP y lo llamamos activos.php

<?php

$tiempo_logout = 600; // segundos tras los cuales un usuario es marcado como inactivo

$arr = file("usuarios.dat");

$contenido = $REMOTE_ADDR.":".time()." ";

for ( $i = 0 ; $i < sizeof($arr) ; $i++ )

{

$tmp = explode(":",$arr[$i]);

if (( $tmp[0] != $REMOTE_ADDR ) && (( time() - $tmp[1] ) < $tiempo_logout ))

{

$contenido .= $REMOTE_ADDR.":".time()." ";

}

}

$fp = fopen("usuarios.dat","w");

fputs($fp,$contenido);

fclose($fp);

$array = file("usuarios.dat");

$USUARIOS_ACTIVOS = count($array);

?>

La explicación de lo que hace el codigo anterior es la siguiente:

  • Cargamos usuarios.dat a un array
  • Creamos el archivo de texto con las IP y la hora de visita de los que visitan nuestra web
  • “Borramos” de ese archivo los que llevan más de $tiempo_logout sin actividad
  • Escribimos el archivo
  • Declaramos una variable $USUARIOS_ACTIVOS que contiene el número de usuarios activos del momento

Para utilizar este Script, al principio de cualquier página ponemos

<?php

include(”activos.php”)

?>

y donde queremos mostrar el número de usuarios, usamos la variable $USUARIOS_ACTIVOS.

Como poner comentarios en el codigo Php

PHP soporta el estilo de comentarios de 'C', 'C++' y de la interfaz de comandos de Unix. Por ejemplo:

 

<?php

echo "Esto es una prueba"; // Esto es un comentario de una linea al estilo c++

/* Esta es una linea de un comentario multilíneas

Esto es otra linea de un comentario multilinea */

echo "Esto es otra prueba";

echo "Y esto otra prueba mas"; # comentario tipo shell de unix

?>

Ejemplo:

   

<h1>Esto es un <?php # echo "simple";?> ejemplo.</h1>

<p>El encabezado de arriba dice 'Esto es un simple ejemplo'.

Hay que tener cuidado con no anidar comentarios de estilo 'C', algo que puede ocurrir al comentar bloques largos de código.

  

<?php

/*

echo "esto es una prueba"; /* Este comentario puede causar problemas */

*/

?>

Los estilos de comentarios de una linea comentan hasta el final de la linea o del bloque actual de código PHP, lo primero que ocurra. Esto implica que el código HTML tras // ?> será impreso: ?> sale del modo PHP, retornando al modo HTML, el comentario // no le influye.

Formas de Entrar y salir de PHP

Para interpretar un archivo, php símplemente interpreta el texto del archivo hasta que encuentra uno de los carácteres especiales que delimitan el inicio de código PHP. El intérprete ejecuta entonces todo el código que encuentra, hasta que encuentra una etiqueta de fin de código, que le dice al intérprete que siga ignorando el código siguiente. Este mecanismo permite embeber código PHP dentro de HTML: todo lo que está fuera de las etiquetas PHP se deja tal como está, mientras que el resto se interpreta como código.

Hay cuatro conjuntos de etiquetas que pueden ser usadas para denotar bloques de código PHP. De estas cuatro, sólo 2 (<?php. . .?> y <script language="php">. . .</script>) están siempre disponibles; el resto pueden ser configuradas en el fichero de php.ini para ser o no aceptadas por el intérprete. Mientras que el formato corto de etiquetas (short-form tags) y el estilo ASP (ASP-style tags) pueden ser convenientes, no son portables como la versión de formato largo de etiquetas. Además, si se pretende embeber código PHP en XML o XHTML, será obligatorio el uso del formato <?php. . .?> para la compatibilidad con XML.

Las etiquetas soportadas por PHP son:

Ejemplo: Formas de escapar de HTML

1. <?php echo("si quieres servir documentos XHTML o XML, haz como aquí\n"); ?>

2. <? echo ("esta es la más simple, una instrucción de procesado SGML \n"); ?>

<?= expression ?> Esto es una abreviatura de "<? echo expression ?>"

3. <script language="php">

echo ("muchos editores (como FrontPage) no

aceptan instrucciones de procesado");

</script>

4. <% echo ("Opcionalmente, puedes usar las etiquetas ASP"); %>

<%= $variable; # Esto es una abreviatura de "<% echo . . ." %>

El método primero, <?php. . .?>, es el más conveniente, ya que permite el uso de PHP en código XML como XHTML.

El método segundo no siempre está disponible. El formato corto de etiquetas está disponible con la función short_tags() (sólo PHP 3), activando el parámetro del fichero de configuración de PHP short_open_tag, o compilando PHP con la opción --enable-short-tags del comando configure. Aunque esté activa por defecto en php.ini-dist, se desaconseja el uso del formato de etiquetas corto.

El método cuarto sólo está disponible si se han activado las etiquetas ASP en el fichero de configuración: asp_tags.

nota: El soporte de etiquetas ASP se añadió en la versión 3.0.4.

nota: No se debe usar el formato corto de etiquetas cuando se desarrollen aplicaciones o bibliotecas con intención de redistribuirlas, o cuando se desarrolle para servidores que no están bajo nuestro control, porque puede ser que el formato corto de etiquetas no esté soportado en el servidor. Para generar código portable y redistribuíble, asegúrate de no usar el formato corto de etiquetas.

La etiqueta de fin de bloque incluirá tras ella la siguiente línea si hay alguna presente. Además, la etiqueta de fin de bloque lleva implícito el punto y coma; no necesitas por lo tanto añadir el punto y coma final de la última línea del bloque PHP.

PHP permite estructurar bloques como:

Ejemplo: Métodos avanzados de escape

<?php

if ($expression) {

?>

<strong>This is true.</strong>

<?php

} else {

?>

<strong>This is false.</strong>

<?php

}

?>

Este ejemplo realiza lo esperado, ya que cuando PHP encuentra las etiquetas ?> de fin de bloque, empieza a escribir lo que encuentra tal cual hasta que encuentra otra etiqueta de inicio de bloque. El ejemplo anterior es, por supuesto, inventado. Para escribir bloques grandes de texto generamente es más eficiente separalos del código PHP que enviar todo el texto mediante las funciones echo(), print() o similares.

Uso de Formularios en PHP

Otra de las características de PHP es que gestiona formularios de HTML. El concepto básico que es importante entender es que cualquier elemento de los formularios estará disponible automáticamente en su código PHP. Observemos un ejemplo:

Ejemplo: Un formulario HTML sencillo

<form action="accion.php" method="POST">

Su nombre: <input type="text" name="nombre" />

Su edad: <input type="text" name="edad" />

<input type="submit">

</form>

No hay nada especial en este formularo, es HTML limpio sin ninguna clase de etiquetas desconocidas. Cuando el cliente llena éste formulario y oprime el botón etiquetado "Submit", una página titulada accion.php es llamada. En este archivo encontrará algo así:

Ejemplo: Procesamiento de información de nuestro formulario HTML

Hola <?php echo $_POST["nombre"]; ?>.

Tiene <?php echo $_POST["edad"]; ?> años

Un ejemplo del resultado de este script podría ser:

Hola José.

Tiene 22 años

Es aparentemente obvio lo que hace. No hay mucho más que decir al respecto. Las variables $_POST["nombre"] y $_POST["edad"] son definidas automáticamente por PHP. Hace un momento usamos la variable autoglobal $_SERVER, ahora hemos introducido autoglobal $_POST, que contiene toda la información enviada por el método POST. Fíjese en el atributo method en nuestro formulario; es POST. Si hubiéramos usado GET, entonces nuestra información estaría en la variable autoglobal $_GET. También puede utilizar la autoglobal $_REQUEST si no le importa el origen de la petición. Ésta variable contiene una mezcla de información GET, POST y COOKIE.

Separación de instrucciones en PHP

Las separación de instrucciones se hace de la misma manera que en C o Perl - terminando cada declaración con un punto y coma.

La etiqueta de fin de bloque (?>) implica el fin de la declaración, por lo tanto lo siguiente es equivalente:

<?php

echo "This is a test";

?>

<?php echo "This is a test" ?>

Tipos de datos en Php

PHP soporta ocho tipos primitivos.

Cuatro tipos escalares:
• boolean
• integer
• float (número de punto-flotante, también conocido como 'double')
• string

Dos tipos compuestos:
• array
• object

Y finalmente dos tipos especiales:
• resource
• NULL

También algunos pseudo-tipos por razones de legibilidad:
• mixed
• number
• callback

Y la pseudo-variable $....

También puede encontrar algunas referencias al tipo "double". Considere al tipo double como el mismo que float, los dos nombres existen solo por razones históricas.

El tipo de una variable usualmente no es declarado por el programador; en cambio, es decidido en tiempo de compilación por PHP dependiendo del contexto en el que es usado la variable.
nota: Si desea chequear el tipo y valor de una cierta expresión, use var_dump().
Si tan solo desea una representación legible para humanos del tipo para propósitos de depuración, use gettype(). Para chequear por un cierto tipo, no use gettype(); en su lugar utilice las funciones is_tipo. Algunos ejemplos:

<?php
$un_bool = TRUE; // un valor booleano
$un_str = "foo"; // una cadena
$un_str2 = 'foo'; // una cadena
$un_int = 12; // un entero

echo gettype($un_bool); // imprime: boolean
echo gettype($un_str); // imprime: string

// Si este valor es un entero, incrementarlo en cuatro
if (is_int($un_int)) {
$un_int += 4;
}

// Si $bool es una cadena, imprimirla
// (no imprime nada)
if (is_string($un_bool)) {
echo "Cadena: $un_bool";
}
?>

Si quisiera forzar la conversión de una variable a cierto tipo, puede moldear la variable, o usar la función settype() sobre ella.
Note que una variable puede ser evaluada con valores diferentes en ciertas situaciones, dependiendo del tipo que posee en cada momento.

Tipo de datos Booleanos en Php

Este es el tipo más simple. Un boolean expresa un valor de verdad. Puede ser TRUE or FALSE.
nota: El tipo booleano fue introducido en PHP 4.

Sintaxis:
Para especificar un literal booleano, use alguna de las palabras clave TRUE o FALSE. Ambas son insensibles a mayúsculas y minúsculas.

<?php
$foo = True; // asignar el valor TRUE a $foo
?>

Usualmente se usa algún tipo de operador que deuelve un valor boolean, y luego éste es pasado a una estructura de control.

<?php
// == es un operador que prueba por
// igualdad y devuelve un booleano
if ($accion == "mostrar_version") {
echo "La versión es 1.23";
}

// esto no es necesario...
if ($mostrar_separadores == TRUE) {
echo "<hr>\n";
}

// ...porque se puede escribir simplemente
if ($mostrar_separadores) {
echo "<hr>\n";
}
?>

Conversión a booleano

Para convertir explícitamente un valor a boolean, use el moldeamiento (bool) o (boolean). Sin embargo, en la mayoría de casos no es necesario usar el moldeamiento, ya que un valor será convertido automáticamente si un operador, función o estructura de control requiere un argumento tipo boolean.

Cuando se realizan conversiones a boolean, los siguientes valores son considerados FALSE:

• el boolean FALSE mismo
• el integer 0 (cero)
• el float 0.0 (cero)
• el valor string vacío, y el string "0"
• un array con cero elementos
• un object con cero variables miembro (sólo en PHP 4)
• el tipo especial NULL (incluyendo variables no definidas)
• objetos SimpleXML creados desde etiquetas vacías

Cualquier otro valor es considerado TRUE (incluyendo cualquier resource).

aviso : ¡-1 es considerado TRUE, como cualquier otro número diferente a cero (ya sea negativo o positivo)!

<?php
var_dump((bool) ""); // bool(false)
var_dump((bool) 1); // bool(true)
var_dump((bool) -2); // bool(true)
var_dump((bool) "foo"); // bool(true)
var_dump((bool) 2.3e5); // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array()); // bool(false)
var_dump((bool) "false"); // bool(true)
?>

Datos Enteros en Php

Un integer es un número del conjunto Z = {..., -2, -1, 0, 1, 2, ...}.

Sintaxis

Los enteros pueden ser especificados en notación decimal (base-10), hexadecimal (base-16) u octal (base-8), opcionalmente precedidos por un signo (- o +).
Si usa la notación octal, debe preceder el número con un 0 (cero), para usar la notación hexadecimal, preceda el número con 0x.

Ejemplo: Literales tipo entero

<?php
$a = 1234; // número decimal
$a = -123; // un número negativo
$a = 0123; // número octal (equivalente al 83 decimal)
$a = 0x1A; // número hexadecimal (equivalente al 26 decimal)
?>

Formalmente, la posible estructura para literales enteros es:

decimal     : [1-9][0-9]*
| 0

hexadecimal : 0[xX][0-9a-fA-F]+

octal : 0[0-7]+

integer : [+-]?decimal
| [+-]?hexadecimal
| [+-]?octal


El tamaño de un entero es dependiente de la plataforma, aunque un valor máximo de aproximadamente dos billones es el valor usual (lo que es un valor de 32 bits con signo). PHP no soporta enteros sin signo. El tamaño de un entero puede determinarse a partir de PHP_INT_SIZE, o el valor máximo de PHP_INT_MAX a partir de PHP 4.4.0 y PHP 5.0.5.

aviso : Si un dígito inválido es pasado a un entero octal (p.ej. 8 o 9), el resto del número es ignorado.

Ejemplo: Curiosidad de valores octales

<?php
var_dump(01090); // 010 octal = 8 decimal
?>

Desbordamiento de enteros

Si especifica un número más allá de los límites del tipo integer, será interpretado en su lugar como un float. Asimismo, si realiza una operación que resulta en un número más allá de los límites del tipo integer, un float es retornado en su lugar.

<?php
$numero_grande = 2147483647;
var_dump($numero_grande);
// salida: int(2147483647)

$numero_grande = 2147483648;
var_dump($numero_grande);
// salida: float(2147483648)

// también es cierto para enteros hexadecimales especificados entre 2^31 y 2^32-1:
var_dump( 0xffffffff );
// salida: float(4294967295)

// esto no ocurre con los enteros indicados como hexadecimales más allá de 2^32-1:
var_dump( 0x100000000 );
// salida: int(2147483647)

$millon = 1000000;
$numero_grande = 50000 * $millon;
var_dump($numero_grande);
// salida: float(50000000000)
?>

No hay un operador de división de enteros en PHP. 1/2 produce el float 0.5. Puede moldear el valor a un entero para asegurarse de redondearlo hacia abajo, o puede usar la función round().

<?php
var_dump(25/7); // float(3.5714285714286)
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7)); // float(4)
?>

Conversión a entero

Para convertir explícitamente un valor a integer, use alguno de los moldeamientos (int) o (integer). Sin embargo, en la mayoría de casos no necesita usar el moldeamiento, ya que un valor será convertido automáticamente si un operador, función o estructura de control requiere un argumento tipo integer. También puede convertir un valor a entero con la función intval().

Desde booleans

FALSE producirá 0 (cero), y TRUE producirá 1 (uno).

Desde números de punto flotante

Cuando se realizan conversiones desde un flotante a un entero, el número será redondeado hacia cero.
Si el flotante se encuentra más allá de los límites del entero (usualmente +/- 2.15e+9 = 2^31), el resultado es indefinido, ya que el flotante no tiene suficiente precisión para dar un resultado entero exacto. No se producirá una advertencia, ¡ni siquiera una noticia en este caso!
aviso : Nunca moldee una fracción desconocida a integer, ya que esto en ocasiones produce resultados inesperados.

<?php
echo (int) ( (0.1+0.7) * 10 ); // imprime 7!
?>

Desde otros tipos

El comportamiento de convertir desde entero no es definido para otros tipos. Actualmente, el comportamiento es el mismo que si el valor fuera antes convertido a booleano. Sin embargo, no confíe en este comportamiente, ya que puede ser modificado sin aviso.

Tuesday, February 12, 2008

Control structures in Php: include_once()

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.
include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
For more examples on using require_once() and include_once(), look at the » PEAR code included in the latest PHP source code distributions.
Return values are the same as with include(). If the file was already included, this function returns TRUE

Note: include_once() was added in PHP 4.0.1

Note: Be aware, that the behaviour of include_once() and require_once() may not be what you expect on a non case sensitive operating system (such as Windows).

Example: include_once() is case insensitive on Windows

<?php
include_once "a.php"; // this will include a.php
include_once "A.php"; // this will include a.php again on Windows! (PHP 4 only)
?>


This behaviour changed in PHP 5 - the path is normalized first so that C:\PROGRA~1\A.php is realized the same as C:\Program Files\a.php and the file is included just once.

Warning:

Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled.

Control structures in Php: require_once()

The require_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the require() statement, with the only difference being that if the code from a file has already been included, it will not be included again.
require_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
For examples on using require_once() and include_once(), look at the » PEAR code included in the latest PHP source code distributions.
Return values are the same as with include(). If the file was already included, this function returns TRUE

Note: require_once() was added in PHP 4.0.1

Note: Be aware, that the behaviour of require_once() and include_once() may not be what you expect on a non case sensitive operating system (such as Windows).

Example: require_once() is case insensitive on Windows

<?php
require_once "a.php"; // this will include a.php
require_once "A.php"; // this will include a.php again on Windows! (PHP 4 only)
?>


This behaviour changed in PHP 5 - the path is normalized first so that C:\PROGRA~1\A.php is realized the same as C:\Program Files\a.php and the file is required just once.

Warning:

Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled.

Control structures in Php: include()

The include() statement includes and evaluates the specified file.
The documentation below also applies to require(). The two constructs are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well. Be warned that parse error in included file doesn't cause processing halting in PHP versions prior to PHP 4.3.5. Since this version, it does.
Files for including are first looked for in each include_path entry relative to the current working directory, and then in the directory of current script. E.g. if your include_path is libraries, current working directory is /www/, you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/libraries/ and then in /www/include/. If filename begins with ./ or ../, it is looked only in the current working directory.
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Example: Basic include() example

vars.php
<?php

$color = 'green';
$fruit = 'apple';

?>

test.php
<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>


If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs.

Example: Including within functions

<?php

function foo()
{
global $color;

include 'vars.php';

echo "A $color $fruit";
}

/* vars.php is in the scope of foo() so *
* $fruit is NOT available outside of this *
* scope. $color is because we declared it *
* as global. */

foo(); // A green apple
echo "A $color $fruit"; // A green

?>


When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.
If "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL (via HTTP or other supported wrapper, instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.

Warning:

Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled.

Example: include() through HTTP

<?php

/* This example assumes that www.example.com is configured to parse .php
* files and not .txt files. Also, 'Works' here means that the variables
* $foo and $bar are available within the included file. */

// Won't work; file.txt wasn't handled by www.example.com as PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';

// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
include 'file.php?foo=1&bar=2';

// Works.
include 'http://www.example.com/file.php?foo=1&bar=2';

$foo = 1;
$bar = 2;
include 'file.txt'; // Works.
include 'file.php'; // Works.

?>


Security warning

Remote file may be processed at the remote server (depending on the file extension and the fact if the remote server runs PHP or not) but it still has to produce a valid PHP script because it will be processed at the local server. If the file from the remote server should be processed there and outputted only, readfile() is much better function to use. Otherwise, special care should be taken to secure the remote script to produce a valid and desired code.
Handling Returns: It is possible to execute a return() statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files. You can take the value of the include call as you would a normal function. This is not, however, possible when including remote files unless the output of the remote file has valid PHP start and end tags (as with any local file). You can declare the needed variables within those tags and they will be introduced at whichever point the file was included.
Because include() is a special language construct, parentheses are not needed around its argument. Take care when comparing return value.

Example: Comparing return value of include

<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
echo 'OK';
}

// works
if ((include 'vars.php') == 'OK') {
echo 'OK';
}
?>


Note: In PHP 3, the return may not appear inside a block unless it's a function block, in which case the return() applies to that function and not the whole file.

Example: include() and the return() statement

return.php
<?php

$var = 'PHP';

return $var;

?>

noreturn.php
<?php

$var = 'PHP';

?>

testreturns.php
<?php

$foo = include 'return.php';

echo $foo; // prints 'PHP'

$bar = include 'noreturn.php';

echo $bar; // prints 1

?>


$bar is the value 1 because the include was successful. Notice the difference between the above examples. The first uses return() within the included file while the other does not. If the file can't be included, FALSE is returned and E_WARNING is issued.
If there are functions defined in the included file, they can be used in the main file independent if they are before return() or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about functions defined after return(). It is recommended to use include_once() instead of checking if the file was already included and conditionally return inside the included file.
Another way to "include" a PHP file into a variable is to capture the output by using the Output Control Functions with include(). For example:

Example: Using output buffering to include a PHP file into a string

<?php
$string = get_include_contents('somefile.php');

function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return false;
}

?>


In order to automatically include files within scripts, see also the auto_prepend_file and auto_append_file configuration options in php.ini.

Note: Because this is a language construct and not a function, it cannot be called using variable functions

Control structures in php: require()

The require() statement includes and evaluates the specific file.
require() includes and evaluates a specific file. Detailed information on how this inclusion works is described in the documentation for include().
require() and include() are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, don't hesitate to use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well.

Example: Basic require() examples

<?php

require 'prepend.php';

require $somefile;

require ('somefile.txt');

?>


Note: Prior to PHP 4.0.2, the following applies: require() will always attempt to read the target file, even if the line it's on never executes. The conditional statement won't affect require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed. Similarly, looping structures do not affect the behaviour of require(). Although the code contained in the target file is still subject to the loop, the require() itself happens only once.

Note: Because this is a language construct and not a function, it cannot be called using variable functions

Warning:

Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled.


Control structures in Php: return

If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of an eval() statement or script file.
If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call. If return() is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file's execution is ended.

Note: Note that since return() is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case.

Note: You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value of $a).

Control structure in Php: declare

The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs:

declare (directive)
statement


The directive section allows the behavior of the declare block to be set. Currently only one directive is recognized: the ticks directive.
The statement part of the declare block will be executed -- how it is executed and what side effects occur during execution may depend on the directive set in the directive block.
The declare construct can also be used in the global scope, affecting all code following it.

<?php
// these are the same:

// you can use this:
declare(ticks=1) {
// entire script here
}

// or you can use this:
declare(ticks=1);
// entire script here
?>


Ticks

A tick is an event that occurs for every N low-level statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare blocks's directive section.
The event(s) that occur on each tick are specified using the register_tick_function(). See the example below for more details. Note that more than one event can occur for each tick.

Example: Profile a section of PHP code

<?php
// A function that records the time when it is called
function profile($dump = FALSE)
{
static $profile;

// Return the times stored in profile, then erase it
if ($dump) {
$temp = $profile;
unset($profile);
return $temp;
}

$profile[] = microtime();
}

// Set up a tick handler
register_tick_function("profile");

// Initialize the function before the declare block
profile();

// Run a block of code, throw a tick every 2nd statement
declare(ticks=2) {
for ($x = 1; $x < 50; ++$x) {
echo similar_text(md5($x), md5($x*$x)), "<br />;";
}
}

// Display the data stored in the profiler
print_r(profile(TRUE));
?>


The example profiles the PHP code within the 'declare' block, recording the time at which every second low-level statement in the block was executed. This information can then be used to find the slow areas within particular segments of code. This process can be performed using other methods: using ticks is more convenient and easier to implement.
Ticks are well suited for debugging, implementing simple multitasking, background I/O and many other tasks.

Control structures in php: switch

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

Note: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.

Note: Note that switch/case does loose comparision.

The following two examples are two different ways to write the same thing, one using a series of if and elseif statements, and the other using the switch statement:
Example: switch structure

<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}

switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>


Example: switch structure allows usage of strings

<?php
switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
echo "i is bar";
break;
case "cake":
echo "i is cake";
break;
}
?>


It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:

<?php
switch ($i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
case 2:
echo "i equals 2";
}
?>


Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).
In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.
The statement list for a case can also be empty, which simply passes control into the statement list for the next case.

<?php
switch ($i) {
case 0:
case 1:
case 2:
echo "i is less than 3 but not negative";
break;
case 3:
echo "i is 3";
}
?>


A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:

<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>


The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type.
The alternative syntax for control structures is supported with switches.

<?php
switch ($i):
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
endswitch;
?>

Contro strucrutes in Php: continue

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
Note: Note that in PHP the switch statement is considered a looping structure for the purposes of continue.
continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.

<?php
while (list($key, $value) = each($arr)) {
if (!($key % 2)) { // skip odd members
continue;
}
do_something_odd($value);
}

$i = 0;
while ($i++ < 5) {
echo "Outer<br />\n";
while (1) {
echo " Middle<br />\n";
while (1) {
echo " Inner<br />\n";
continue 3;
}
echo "This never gets output.<br />\n";
}
echo "Neither does this.<br />\n";
}
?>


Omitting the semicolon after continue can lead to confusion. Here's an example of what you shouldn't do.

<?php
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue
print "$i\n";
}
?>


One can expect the result to be :

0
1
3
4


but this script will output :

2


because the return value of the print() call is int(1), and it will look like the optional numeric argument mentioned above.

Control structures in Php: break

break ends execution of the current for, foreach, while, do-while or switch structure.
break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

<?php
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}

/* Using the optional argument. */

$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting<br />\n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}
?>

Control structures in php: foreach

PHP 4 introduced a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first:

foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement


The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).
The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.
As of PHP 5, it is possible to iterate objects too.
Note: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.

As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

This is possible only if iterated array can be referenced (i.e. is variable).
Warning
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().
Note: foreach does not support the ability to suppress error messages using '@'.
You may have noticed that the following are functionally identical:

<?php
$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
echo "Value: $value<br />\n";
}

foreach ($arr as $value) {
echo "Value: $value<br />\n";
}
?>

The following are also functionally identical:

<?php
$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) {
echo "Key: $key; Value: $value<br />\n";
}

foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
?>

Some more examples to demonstrate usages:

<?php
/* foreach example 1: value only */

$a = array(1, 2, 3, 17);

foreach ($a as $v) {
echo "Current value of \$a: $v.\n";
}

/* foreach example 2: value (with key printed for illustration) */

$a = array(1, 2, 3, 17);

$i = 0; /* for illustrative purposes only */

foreach ($a as $v) {
echo "\$a[$i] => $v.\n";
$i++;
}

/* foreach example 3: key and value */

$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);

foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}

/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}

/* foreach example 5: dynamic arrays */

foreach (array(1, 2, 3, 4, 5) as $v) {
echo "$v\n";
}
?>

Expressions in PHP

Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".

The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant).
After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.
Slightly more complex examples for expressions are functions. For instance, consider the following function:

<?php
function foo ()
{
return 5;
}
?>

Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something.

Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports four scalar value types: integer values, floating point values (float), string values and boolean values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.

PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, '$a = 5'. It's easy to see that there are two values involved here, the value of the integer constant '5', and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that '$a = 5', regardless of what it does, is an expression with the value 5. Thus, writing something like '$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write '$b = $a = 5'.

Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP/FI 2, the statement '$a++' has no value (is not an expression), and thus you can't assign it or use it in any way. PHP enhances the increment/decrement capabilities by making these expressions as well, like in C. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is identical. The difference is with the value of the increment expression. Pre-increment, which is written '++$variable', evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written '$variable++' evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').
A very common type of expressions are comparison expressions. These expressions evaluate to either FALSE or TRUE. PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as if statements.

The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of $b by 7), etc.

There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:

<?php
$first ? $second : $third
?>

If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.
The following example should help you understand pre- and post-increment and expressions in general a bit better:

<?php
function double($i)
{
return $i*2;
}
$b = $a = 5; /* assign the value five into the variable $a and $b */
$c = $a++; /* post-increment, assign original value of $a
(5) to $c */
$e = $d = ++$b; /* pre-increment, assign the incremented value of
$b (6) to $d and $e */

/* at this point, both $d and $e are equal to 6 */

$f = double($d++); /* assign twice the value of $d before
the increment, 2*6 = 12 to $f */
$g = double(++$e); /* assign twice the value of $e after
the increment, 2*7 = 14 to $g */
$h = $g += 10; /* first, $g is incremented by 10 and ends with the
value of 24. the value of the assignment (24) is
then assigned into $h, and $h ends with the value
of 24 as well. */
?>

Some expressions can be considered as statements. In this case, a statement has the form of 'expr' ';' that is, an expression followed by a semicolon. In '$b=$a=5;', $a=5 is a valid expression, but it's not a statement by itself. '$b=$a=5;' however is a valid statement.
One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE. The constants TRUE and FALSE (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean.
PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.