elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Rompecabezas de Bitcoin, Medio millón USD en premios


+  Foro de elhacker.net
|-+  Programación
| |-+  Desarrollo Web
| | |-+  PHP (Moderador: #!drvy)
| | | |-+  [Solucionado] variables dinamicas dentro de funciones ( is_numeric($$variable) )
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [Solucionado] variables dinamicas dentro de funciones ( is_numeric($$variable) )  (Leído 2,764 veces)
gAb1


Desconectado Desconectado

Mensajes: 731


Ver Perfil
[Solucionado] variables dinamicas dentro de funciones ( is_numeric($$variable) )
« en: 29 Marzo 2016, 03:54 am »

Hola, estoy intentando crear un script que declare y limpie las variables de formularios largos, donde hayan arrays de numeros y strings, pero utilizando un whitelist para los nombres de los elementos. Me están dando errores:

Citar
Warning: Illegal string offset 'name' in /home/aet/website.com/pages/upload.php on line 34

Notice: Undefined variable: a in /home/aet/website.com/pages/upload.php on line 34
Y
Citar
Warning: Illegal string offset 'name' in /home/aet/website.com/pages/upload.php on line 38

Notice: Undefined variable: a in /home/aet/website.com/pages/upload.php on line 38

De momento esto es lo que tengo:

Código
  1. $list = array('name' => 'mandatory', 'surname' => 'optional');
  2.  
  3. foreach ( $list as $name => $nouse ) {
  4.    if (isset($_POST[$name])) {
  5.        if ( is_array($_POST[$name]) ) {
  6.            $$name = filter_input( INPUT_POST , $name , FILTER_SANITIZE_STRING , FILTER_REQUIRE_ARRAY );
  7.            foreach ($$name as $key => $value) {
  8.                $key = preg_replace('[a-z]', '', $key);
  9.                if ( is_numeric($$name[$key]) ) { // this is line 34
  10.                    $$key = (int) $$name[$key];
  11.                    echo $report[$key] = $key . ' variable (from ' . $name . ' ) created1... <span style="color:green;">OK!</span><br>';
  12.                } else {
  13.                    $$key = $$name[$key];  // this is line 38
  14.                    echo $report[$key] = $key . ' variable (from ' . $name . ' ) created2... <span style="color:green;">OK!</span><br>';
  15.                }
  16.            }
  17.        } else {
  18.            if ( is_numeric($_POST[$name]) ) {
  19.                $$name = filter_input( INPUT_POST , $name , FILTER_SANITIZE_NUMBER_INT );
  20.                echo $report[$name] = $name . ' variable created3... <span style="color:green;">OK!</span><br>';
  21.            } else {
  22.                $$name = filter_input( INPUT_POST , $name , FILTER_SANITIZE_STRING );
  23.                echo $report[$name] = $name . ' variable created4... <span style="color:green;">OK!</span><br>';
  24.            }
  25.        }
  26.    } else {
  27.        if ($list[$name] == 'optional') {
  28.            $$name = 0;
  29.            echo $report[$name] = $name . ' (optional) variable not filled5... <span style="color:green;">OK!</span><br>';
  30.        } else die('Error: You must fill all mandatory fields! (' . $name . ')');
  31.    }
  32. }

El html es de lo más sencillo, los arrays los tengo asi:

Código
  1. <input type="text" name="address_book[name]" />
  2. <input type="text" name="address_book[surname]" />

¿Alguna idea de por qué no funciona?  :-\

Gracias!


« Última modificación: 29 Marzo 2016, 20:19 pm por gAb1 » En línea

ivancea96


Desconectado Desconectado

Mensajes: 3.412


ASMático


Ver Perfil WWW
Re: variables dinamicas dentro de funciones ( is_numeric($$variable) )
« Respuesta #1 en: 29 Marzo 2016, 11:58 am »

¿Y así?
Código
  1. <input type="text" name="name" />
  2. <input type="text" name="surname" />


En línea

gAb1


Desconectado Desconectado

Mensajes: 731


Ver Perfil
Re: variables dinamicas dentro de funciones ( is_numeric($$variable) )
« Respuesta #2 en: 29 Marzo 2016, 17:30 pm »

Así seguramente funcionaria, pero el objetivo es automatizar para facilitar el proceso. Cuando hay formularios largos, con muchos campos (unos 40-50) se crean los arrays para agrupar y separar (organizar) los campos.

La cuestión es saber por qué no funciona y saber arreglarlo. Cuando los formularios apenas tienen 10-15 campos pues si que es mejor hacerlo a mano, pero cuando hay más de 40 la cosa cambia, además de poder usarlo en todos los formularios que necesites.
En línea

ivancea96


Desconectado Desconectado

Mensajes: 3.412


ASMático


Ver Perfil WWW
Re: variables dinamicas dentro de funciones ( is_numeric($$variable) )
« Respuesta #3 en: 29 Marzo 2016, 17:56 pm »

Si quieres automatizarlo, puedes poner un nombre del tipo address_book_name.

El caso es que le estas dando un nombre, y luego accedes a él con otro.

Si quieres pasar con el mismo nombre múltiples formularios, puedes pasar un hidden con un identificador del formulario:

Código
  1. <input type="hidden" name="type" value="address_book" />

Luego en el PHP, por ejemplo:

Código
  1. if($_POST['type'] == 'address_book') ...

Y ya, como sea que lo quieras hacer.


Si van a ser muchos campos de un mismo formulario, entonces no hay mucho más que decir. Todos van a tener nombres diferentes. Si quieres automatizar el acceso a todos estos, puedes ponerles un prefijo y acceder mediante el array de POST a los que tengan ese prefijo.
En línea

gAb1


Desconectado Desconectado

Mensajes: 731


Ver Perfil
Re: variables dinamicas dentro de funciones ( is_numeric($$variable) )
« Respuesta #4 en: 29 Marzo 2016, 18:25 pm »

No entiendo lo del hidden, pero entiendo que dices que no use arrays, sea por la razón que sea pero no la dices.

¿Por qué dices que le doy un nombre y luego accedo con otro? Creo que eso no es cierto, el script deja bien claro que el nombre del elemento es el usado para acceder al array:

Código
  1. $name = 'address_book';
  2.  
  3. $$name = $_POST[$name];
  4.  
  5. foreach ($$name as $key => $value) {
  6.    if ( is_numeric($$name[$key]) ) {
  7.        $$key = (int) $$name[$key];
  8.    }
  9. }

Si no me equivoco, lo de arriba es lo mismo que hacer:

Código
  1. $address_book = $_POST['address_book'];
  2.  
  3. foreach ($address_book as $key => $value) {
  4.    if ( is_numeric($address_book[$key]) ) {
  5.        $name/$surname = (int) $address_book[$key];
  6.    }
  7. }

No??

Si es incorrecto lo que intento hacer, dimelo, ya que no me estoy enterando de nada, ¿es un error en la manera de querer hacer esto?

Si no hay nada malo en usar arrays, preferiria hacerlo así a tener que llenar un whitelist con más de 40 nombres. Que pongan lo que quieran en los keys del array, el preg_replace dejará solo letras minusculas y con eso no se puede hacer nada, el prepare dará error al no tener las variables necesarias y no sé ejecutará nada en la base de datos, no veo el problema por ninguna parte.

Código
  1. if ($stmt->error()) {
  2.    die('Database Error');
  3. }

EDITO: Habia otro problema, que al parecer ninguno de los dos nos habiamos dado cuenta... La variable $name que contiene el valor del formulario estaba sobreescribiendo la variable $name del primer foreach... Le he cambiado el nombre y ahora puedo ver el mismo error para todos los campos del array address_book:

Citar
Warning: Illegal string offset 'name' in /home/aet/website.com/pages/upload.php on line 34

Notice: Undefined variable: a in /home/aet/website.com/pages/upload.php on line 34

Warning: Illegal string offset 'name' in /home/aet/website.com/pages/upload.php on line 38

Notice: Undefined variable: a in /home/aet/website.com/pages/upload.php on line 38
name variable (from address_book ) created2... OK!

Warning: Illegal string offset 'surname' in /home/aet/website.com/pages/upload.php on line 34

Notice: Undefined variable: a in /home/aet/website.com/pages/upload.php on line 34

Warning: Illegal string offset 'surname' in /home/aet/website.com/pages/upload.php on line 38

Notice: Undefined variable: a in /home/aet/website.com/pages/upload.php on line 38
surname variable (from address_book ) created2... OK!
« Última modificación: 29 Marzo 2016, 18:55 pm por gAb1 » En línea

gAb1


Desconectado Desconectado

Mensajes: 731


Ver Perfil
Re: variables dinamicas dentro de funciones ( is_numeric($$variable) )
« Respuesta #5 en: 29 Marzo 2016, 19:50 pm »

Ok I got it! ;D

El problema está en que no necesito el nombre del elemento para declarar el array:

Código
  1. foreach ( $list as $element_name => $nouse ) {
  2.    if (isset($_POST[$element_name])) {
  3.        if ( is_array($_POST[$element_name]) ) {
  4.            $filtered_data = filter_input( INPUT_POST , $element_name , FILTER_SANITIZE_STRING , FILTER_REQUIRE_ARRAY );
  5.            foreach ($filtered_data as $key => $value) {
  6.                $key = preg_replace('[a-z]', '', $key);
  7.                if ( is_numeric($value) ) { // this is line 34
  8.                    $$key = (int) $value;
  9.                    echo $report[$key] = $key . ' variable (from ' . $element_name . ' ) created1... <span style="color:green;">OK!</span><br>';
  10.                } else {
  11.                    $$key = $value;  // this is line 38
  12.                    echo $report[$key] = $key . ' variable (from ' . $element_name . ' ) created2... <span style="color:green;">OK!</span><br>';
  13.                }
  14.            }
  15.        } else {
  16.            if ( is_numeric($_POST[$element_name]) ) {
  17.                $$element_name = filter_input( INPUT_POST , $element_name , FILTER_SANITIZE_NUMBER_INT );
  18.                echo $report[$element_name] = $element_name . ' variable created3... <span style="color:green;">OK!</span><br>';
  19.            } else {
  20.                $$element_name = filter_input( INPUT_POST , $name , FILTER_SANITIZE_STRING );
  21.                echo $report[$element_name] = $element_name . ' variable created4... <span style="color:green;">OK!</span><br>';
  22.            }
  23.        }
  24.    } else {
  25.        if ($list[$element_name] == 'optional') {
  26.            $$element_name = 0;
  27.            echo $report[$element_name] = $element_name . ' (optional) variable not filled5... <span style="color:green;">OK!</span><br>';
  28.        } else die('Error: You must fill all mandatory fields! (' . $element_name . ')');
  29.    }
  30. }
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines