It seems that all FILTER_VALIDATE_URL is doing is calling parse_url(), which makes it effectively useless since parse_url() only fails on really malformed urls.
<?php
$url = 'http://...';
var_dump(filter_var($url, FILTER_VALIDATE_URL));
?>
Will display: string(10) "http://..."
None of the flags help either, so you're better off with regular expressions to validate a url.
Funciones de Filtro
Introducción
Esta extensión sirve para validar y filtrar datos provenientes de alguna fuento insegura, tal como entrada del usuario.
Los siguientes filtros existen en este momento; asegúrese de leer la sección Constantes de Filtros para más información sobre el comportamiento de cada constante:
| ID | Nombre | Opciones | Banderas | Descripción |
|---|---|---|---|---|
| FILTER_VALIDATE_INT | "int" | min_range , max_range | FILTER_FLAG_ALLOW_OCTAL, FILTER_FLAG_ALLOW_HEX | Valida el valor como entero, opcionalmente entre el rango especificado. |
| FILTER_VALIDATE_BOOLEAN | "boolean" | FILTER_NULL_ON_FAILURE |
Devuelve TRUE para "1", "true", "on" y "yes". Devuelve FALSE de lo contrario. Si FILTER_NULL_ON_FAILURE está definido, se devuelve FALSE solo para "0", "false", "off", "no", y "", y NULL es devuelto para todos los valores no-booleanos. |
|
| FILTER_VALIDATE_FLOAT | "float" | decimal | FILTER_FLAG_ALLOW_THOUSAND | Valida el valor como un flotante. |
| FILTER_VALIDATE_REGEXP | "validate_regexp" | regexp | Valida el valor contra una expresión regular compatible con Perl regexp . | |
| FILTER_VALIDATE_URL | "validate_url" | FILTER_FLAG_PATH_REQUIRED, FILTER_FLAG_QUERY_REQUIRED | Valida el valor como una URL, opcionalmente con los componentes requeridos. | |
| FILTER_VALIDATE_EMAIL | "validate_email" | Valida el valor como correo electrónico. | ||
| FILTER_VALIDATE_IP | "validate_ip" | FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_FLAG_NO_PRIV_RANGE, FILTER_FLAG_NO_RES_RANGE | Valida el valor como una dirección IP, opcionalmente solo IPv4 o IPv6, o que no pertenezca a los rangos privados o reservados. | |
| FILTER_SANITIZE_STRING | "string" | FILTER_FLAG_NO_ENCODE_QUOTES, FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | Remueve etiquetas, opcionalmente removiendo o codificando caracteres especiales. | |
| FILTER_SANITIZE_STRIPPED | "stripped" | Alias para el filtro "string". | ||
| FILTER_SANITIZE_ENCODED | "encoded" | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH | Codificar estilo URL una cadena, opcionalmente remover o codificar caracteres especiales. | |
| FILTER_SANITIZE_SPECIAL_CHARS | "special_chars" | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_HIGH | Escapar como HTML '"<>& y caracteres con valores ASCII menores a 32, opcionalemnte remover o codificar otros caracteres especiales. | |
| FILTER_UNSAFE_RAW | "unsafe_raw" | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | No hacer nada, opcionalmente remover o codificar caracteres especiales. | |
| FILTER_SANITIZE_EMAIL | "email" | Remover todos los caracteres excepto las letras, dígitos y !#$%&'*+-/=?^_`{|}~@.[]. | ||
| FILTER_SANITIZE_URL | "url" | Remover todos los caracteres excepto letras, dígitos y $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=. | ||
| FILTER_SANITIZE_NUMBER_INT | "number_int" | Remover todos los caracteres excepto dígitos y +-. | ||
| FILTER_SANITIZE_NUMBER_FLOAT | "number_float" | FILTER_FLAG_ALLOW_FRACTION, FILTER_FLAG_ALLOW_THOUSAND, FILTER_FLAG_ALLOW_SCIENTIFIC | Remover todos los caracteres excepto dígitos, +- y opcionalmente .,eE. | |
| FILTER_SANITIZE_MAGIC_QUOTES | "magic_quotes" | Aplicar addslashes(). | ||
| FILTER_CALLBACK | "callback" | función callback o método | Llamar una función definida por el usuario para filtrar los datos. |
Requisitos
No se necesitan bibliotecas externas para construir esta extensión
Instalación
Una corta nota de inslatación: simplemente escriba
$ pecl install filter
Configuración en tiempo de ejecución
El comportamiento de estas funciones está afectado por los valores definidos en php.ini.
| Nombre | Predeterminado | Modificable | Registro de cambios |
|---|---|---|---|
| filter.default | "unsafe_raw" | PHP_INI_PERDIR | PHP_INI_ALL en filter <= 0.9.4. Disponible desde PHP 5.2.0. |
| filter.default_flags | NULL | PHP_INI_PERDIR | PHP_INI_ALL en filter <= 0.9.4. Disponible desde PHP 5.2.0. |
A continuación se presenta una corta explicación de las directivas de configuración.
- filter.default string
-
Filtrar todos los datos $_GET, $_POST, $_COOKIE y $_REQUEST con este filtro. Los datos originales pueden ser accesados mediante filter_input().
Acepta el nombre del filtro que desa usar por omisión. Vea la lista de filtros existentes para conocer los nombres.
- filter.default_flags integer
-
Banderas predeterminadas
Tipos de recursos
Esta extensión no tiene ningún tipo de recurso definido.
Constantes predefinidas
Estas constantes están definidas por esta extensión y estarán disponibles solamente cuando la extensión ha sido o bien compilada dentro de PHP o grabada dinámicamente en tiempo de ejecución.
- INPUT_POST (integer)
- Variables POST.
- INPUT_GET (integer)
- Variables GET.
- INPUT_COOKIE (integer)
- Variables COOKIE.
- INPUT_ENV (integer)
- Variables ENV.
- INPUT_SERVER (integer)
- Variables SERVER.
- INPUT_SESSION (integer)
- Variables SESSION. (aun no implementado)
- INPUT_REQUEST (integer)
- Variables REQUEST. (aun no implementado)
- FILTER_FLAG_NONE (integer)
- Ninguna bandera.
- FILTER_REQUIRE_SCALAR (integer)
- Bandera usada para requerir un valor escalar como entrada
- FILTER_REQUIRE_ARRAY (integer)
- Requerir una matriz como entrada.
- FILTER_FORCE_ARRAY (integer)
- Siempre devolver una matriz.
- FILTER_NULL_ON_FAILURE (integer)
- Usar NULL en lugar de FALSE en caso de fallos.
- FILTER_VALIDATE_INT (integer)
- ID del filtro "int".
- FILTER_VALIDATE_BOOLEAN (integer)
- ID del filtro "boolean".
- FILTER_VALIDATE_FLOAT (integer)
- ID del filtro "float".
- FILTER_VALIDATE_REGEXP (integer)
- ID del filtro "validate_regexp".
- FILTER_VALIDATE_URL (integer)
- ID del filtro "validate_url".
- FILTER_VALIDATE_EMAIL (integer)
- ID del filtro "validate_email".
- FILTER_VALIDATE_IP (integer)
- ID del filtro "validate_ip".
- FILTER_DEFAULT (integer)
- ID del filtro predeterminado ("string").
- FILTER_UNSAFE_RAW (integer)
- ID del filtro "unsafe_raw".
- FILTER_SANITIZE_STRING (integer)
- ID del filtro "string".
- FILTER_SANITIZE_STRIPPED (integer)
- ID del filtro "stripped".
- FILTER_SANITIZE_ENCODED (integer)
- ID del filtro "encoded".
- FILTER_SANITIZE_SPECIAL_CHARS (integer)
- ID del filtro "special_chars".
- FILTER_SANITIZE_EMAIL (integer)
- ID del filtro "email".
- FILTER_SANITIZE_URL (integer)
- ID del filtro "url".
- FILTER_SANITIZE_NUMBER_INT (integer)
- ID del filtro "number_int".
- FILTER_SANITIZE_NUMBER_FLOAT (integer)
- ID del filtro "number_float".
- FILTER_SANITIZE_MAGIC_QUOTES (integer)
- ID del filtro "magic_quotes".
- FILTER_CALLBACK (integer)
- ID del filtro "callback".
- FILTER_FLAG_ALLOW_OCTAL (integer)
- Permitir notación octal (0[0-7]+) en el filtro "int".
- FILTER_FLAG_ALLOW_HEX (integer)
- Permitir notación hexadecimal (0x[0-9a-fA-F]+) en el filtro "int".
- FILTER_FLAG_STRIP_LOW (integer)
- Remover caracteres con valores ASCII menores a 32.
- FILTER_FLAG_STRIP_HIGH (integer)
- Remover caracteres con valores ASCII más altos de 127.
- FILTER_FLAG_ENCODE_LOW (integer)
- Codificar caracteres con valores ASCII menores que 32.
- FILTER_FLAG_ENCODE_HIGH (integer)
- Codificar caracteres con valores ASCII mayores que 127.
- FILTER_FLAG_ENCODE_AMP (integer)
- Codificar &.
- FILTER_FLAG_NO_ENCODE_QUOTES (integer)
- No codificar ' y ".
- FILTER_FLAG_EMPTY_STRING_NULL (integer)
- (Sin uso por ahora.)
- FILTER_FLAG_ALLOW_FRACTION (integer)
- Permitir la parte de fracción en el filtro "number_float".
- FILTER_FLAG_ALLOW_THOUSAND (integer)
- Permitir el separador de miles (,) en el filtro "number_float".
- FILTER_FLAG_ALLOW_SCIENTIFIC (integer)
- Permitir la notación científica (e, E) en el filtro "number_float".
- FILTER_FLAG_SCHEME_REQUIRED (integer)
- Requerir un esquema en el filtro "validate_url".
- FILTER_FLAG_HOST_REQUIRED (integer)
- Requerir un host en el filtro "validate_url".
- FILTER_FLAG_PATH_REQUIRED (integer)
- Requerir una ruta en el filtro "validate_url".
- FILTER_FLAG_QUERY_REQUIRED (integer)
- Requerir una cadena de consulta en el filtro "validate_url".
- FILTER_FLAG_IPV4 (integer)
- Permitir únicamente direcciones IPv4 en el filtro "validate_ip".
- FILTER_FLAG_IPV6 (integer)
- Permitir únicamente direcciones IPv6 en el filtro "validate_ip".
- FILTER_FLAG_NO_RES_RANGE (integer)
- No permitir direcciones reservadas en el filtro "validate_ip".
- FILTER_FLAG_NO_PRIV_RANGE (integer)
- No permitir direcciones privadas en el filtro "validate_ip".
Table of Contents
- filter_has_var — Verifica si la variable del tipo especificado existe
- filter_id — Devuelve el ID del filtro con el nombre dado
- filter_input_array — Obtiene múltiples variables desde afuera de PHP y opcionalmente las filtra
- filter_input — Obtiene una variable desde afuera de PHP y opcionalmente la filtra
- filter_list — Devuelve una lista de todos los filtros soportados
- filter_var_array — Obtiene múltiples variables y opcionalmente las filtra
- filter_var — Filtra una variable con un filtro específico
Filtro
26-Nov-2007 11:35
12-Aug-2007 08:54
I recommend you to use the FILTER_REQUIRE_SCALAR (or FILTER_REQUIRE_ARRAY) flags, since you can use array-brackets both to access string offsets and array-element -- however, not only this can lead to unexpected behaviour. Look at this example:
<?php
$image = basename(filter_input(INPUT_GET, 'src', FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW));
// further checks
?>
/script.php?src[0]=foobar will cause a warning. :-(
Hence my recommendation:
<?php
$image = basename(filter_input(INPUT_GET, 'src', FILTER_UNSAFE_RAW, FILTER_REQUIRE_SCALAR | FILTER_FLAG_STRIP_LOW));
// further checks
?>
13-Jun-2007 09:15
There is an undocumented filter flag for FILTER_VALIDATE_BOOLEAN. The documentation implies that it will return NULL if the value doesn't match the allowed true/false values. However this doesn't happen unless you give it the FILTER_NULL_ON_FAILURE flag like this:
<?php
$value = 'car';
$result = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
?>
In the above $result will equal NULL. Without the extra flag it would equal FALSE, which isn't usually a desired result for this specific filter.
08-May-2007 06:02
Beware, the FILTER_SANITIZE_STRING flag functions much like strip_tags, so < will get filtered from input regardless of it's actually part of a tag. We were getting unexepected results with a graphic library we wrote when trying to print < on a dynamic button. The url came in something like ?string=%3C (<) but after filter ran it was empty. To get around this, you could use FILTER_UNSAFE_RAW on that one param.
02-Feb-2007 10:15
Below is some code using filter API to restrict access to LAN by IPv4 private address range.
These notes may save someone else a little time:
filter_input_array() is useless for running multiple filters on the same key.
No way to chain or negate filters.
<?php
/* Merciful comment! */
function FILTER_NEGATE_HACK($_){ return (bool)!$_; }
function client_is_private_ipv4(){
return (filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) &&
FILTER_NEGATE_HACK(filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE));
}
if (! client_is_private_ipv4())
exit('This application is restricted to local network users');
?>
21-Dec-2006 04:38
Also notice that filter functions are using only the original variable values passed to the script even if you change the value in super global variable ($_GET, $_POST, ...) later in the script.
<?php
echo filter_input(INPUT_GET, 'var'); // print 'something'
echo $_GET['var']; // print 'something'
$_GET['var'] = 'changed';
echo filter_input(INPUT_GET, 'var'); // print 'something'
echo $_GET['var']; // print 'changed'
?>
In fact, external data are duplicated in SAPI before the script is processed and filter functions don't use super globals anymore (as explained in Filter tutorial bellow, section 'How does it work?').
21-Dec-2006 03:13
Just to note that "server and env support may not work in all sapi, for filter 0.11.0 or php 5.2.0" as mentioned in Filter tutorial bellow.
The workaround is obvious:
Instead of
<?php
$var = filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_DEFAULT);
?>
use
<?php
$var = filter_var(isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : NULL, FILTER_DEFAULT);
?>
12-Nov-2006 07:34
Examples of ALL filters and flags here:
http://phpro.org/tutorials/Filtering-Data-with-PHP.html
01-Nov-2006 04:00
Filter tutorial here:
* http://devzone.zend.com/node/view/id/1113
