Mensajes de error que no deberían aparecer

Aparece el mensaje de error:

Deprecated function: The each() function is deprecated. This message will be suppressed on further calls en menu_set_active_trail() (línea 2405 de /srv/www/edutec.es/web/includes/menu.inc).

Y además, conocemos algo de la estructura de directorios del sitio web.

Excelente.

Este mensaje aparece porque la función each() ha sido “deprecated” en PHP 7.2.0:

Warning
This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

El problema de todos los años

Todos los años planteo el mismo requisito a mis estudiantes, todos los años me encuentro que la mayoría lo hacen mal.

En una aplicación web, se tiene que realizar la comprobación de la credenciales (nombre de usuario, contraseña) para acceder al perfil del usuario. En una primera fase no hay base de datos, así que los datos de los usuarios están codificados en la propia página web.

Inicialmente les pedía que lo hicieran suponiendo que hay dos usuarios. Casi nadie almacenaba los datos de los usuarios en un array.

Después lo incrementé a tres usuarios, con la esperanza de que se dieran cuenta de que usando un array se escribe menos, el código es más legible y mantenible. La mayoría de los estudiantes lo seguían haciendo mal.

Después lo volví a incrementar a cuatro usuarios… todo seguía igual.

¿A cuántos usuarios lo tengo que incrementar para que piensen en utilizar un array?

Aquí dejo el fascinante código de uno de mis estudiantes:

 

if(!empty($_POST['usuario']) && !empty($_POST['pdw'])){



	$usuintro = ($_POST['usuario']);
	$contraintro = ($_POST['pdw']);

	$usu1 = "marcos111";
	$contra1= "marquitos111";

	$usu2 = "marcos222";
	$contra2= "marquitos222";

	$usu3 = "marcos333";
	$contra3= "marquitos333";

	$usu4 = "marcos444";
	$contra4= "marquitos444";


	if(strcmp($usuintro, $usu1) === 0){
		if(strcmp($contraintro, $contra1) === 0){
		
 	  		header('Location: usuario.php');	 
 	  		
 		}
 		else{
			
			echo'Usuario o contraseña incorrecto';
		}
	}
	
	if(strcmp($usuintro, $usu2) === 0){
		if(strcmp($contraintro, $contra2) === 0){
			
 			header('Location: usuario.php');
 		}
 		else{
			echo'Usuario o contraseña incorrecto';
		}
	}

	if(strcmp($usuintro, $usu3) === 0){
		if(strcmp($contraintro, $contra3) === 0){
		
			header('Location: usuario.php');
 		}
 		else{
			echo'Usuario o contraseña incorrecto';
		}
	}

	if(strcmp($usuintro, $usu4) === 0){
		if(strcmp($contraintro, $contra4) === 0){
		
			header('Location: usuario.php');
 		}
 		else{
			echo'Usuario o contraseña incorrecto';
		}
	}


	if(strcmp($usuintro, $usu1) !== 0){
		if(strcmp($usuintro, $usu2) !== 0){
			if(strcmp($usuintro, $usu3) !== 0){
				if(strcmp($usuintro, $usu4) !== 0){
			echo'Usuario o contraseña incorrecto';
				}
			}
		}
	}


}

PHP es bueno

Me ha gustado la respuesta dada a la pregunta Everybody is saying don’t learn PHP. Learn JS frameworks but I find them too tough. I like PHP and its easy for me. I am understanding its concepts. Should I ignore them and learn PHP?:

PHP is an awesome tool. Like others. It has its strong and its weak points, like others.

I mainly develop in PHP, Java, Python, C/C++, C# (and Javascript, only when expressly requested)… and I have to say when I want something actionable and done fast, it’s either PHP or Python and that’s it.

PHP is best for web backends, Python is more general, comes with some awesome A.I. and analysis libraries.

I tell you why “everybody” tells you something wrong:

  • half of them are “language activists” (usually for Python or Javascript), most of them are not even professionals, otherwise they would just deal with the fact we are talking about tools, not ideologies.
  • several are “opportunity hoppers”, only looking websites that tell what language earns the highest income. I would never hire such guys, because they are unreliable. Developing is serious business, you don’t want a guy that after 6 months switches job because language XYZ, in year ABCD, potentiallyearns him $2k a year more.
  • the remaining ones, are ignorant. Ignorant in the literal sense. They read some polemics on some blogs (usually “language purist” blogs) in 2011 and never cared to read updated information.
    Now, 2011 knowledge is stale by any standard. PHP did a drastic change starting from version 5.5, that is since about 2013 (4 years ago) and implemented tons and tons of “cool developer guy” syntax facilities and structures.

    Since version 7, PHP is twice as fast and implemented so many new features, that Java itself got behind in some niche constructs.
    Nowadays you can develop PHP backends that really “taste like Java”.
    From lambda / closures / anon functions to iterators, from nice interfaces to factories, from classic patterns to unit testsprofilingand code coverage statisticsmock upstraitscontinuous integration (still rough), from depenencies packages to bigdata access, large (SymfonyLaravelWordPress(!) (powering millions of websites)), medium (Yii and others) and small (Fat Free Framework and more) MVC / REST frameworks. Just name a feature, it’s very possible today’s PHP got it.
    PHP even gets decent (NetBeansEclipseCodeLobster) to awesome development environments (PHPStorm – payware).

    Plus – and no other language beats PHP at this, since the beginning PHP got blazing fast, ultra-extra-mega-flexible key-value arrays (technically: ordered maps) and tons and tons of arrays management functions.

    So… beware, check PHP out and make yourself an idea. It’s actually very quick to check PHP out and see if it’s the tool for you. Just download one of zillions free “LAMP” or “WAMP” or “MAMP” (Linux / Windows / Mac) distributions, that is pre-configured packages including web server, database server and PHP. Some of those are terrific and include debuggers, control panels, additional services and much more.

¿Es PHP realmente un mal lenguaje?

Yo le enseño PHP a mis estudiantes, considero que es un buen lenguaje/plataforma para aprender los conocimientos básicos del desarrollo web. Sin embargo, PHP tiene muchos enemigos y reconozco que no es un excelente lenguaje/plataforma, debido seguramente a la forma en que se ha desarrollado. Sin embargo, la razón de los comentarios negativos se encuentra en lo siguiente (If people consider PHP a bad language, what’s the alternative?):

The reason that PHP is a bad language is that it’s so easy to learn the basics – which makes it easy for people who don’t understand programming to learn PHP … and write totally insecure programs. SQL injection is horrible, trivial to prevent, but a lot of people still use msql() functions in older installations. There’s no reason not to – if you understand what you’re doing but I guess that so many people don’t that they had to take the whole thing out of version 7. (Mysqli() functions aren’t that much better, PDO is almost inherently safe, but it’s still easier to stick with what you’ve been using for years – even if 10 year old can hack into the resultant site.

The alternative isn’t a different language if you’re comfortable writing PHP code, the alternative to writing bad PHP code is to write good PHP code. C++ is a good language too – yet you can still write terrible code in it. Some people suggest Python. You can write insecure sites in Python too, if you don’t watch what you’re doing.

Security is something the developer does, it’s not something in the language.

Es decir, una de las ventajas de PHP, que sea fácil de aprender y sea elegido como plataforma de iniciación para mucha gente que quiera aprender el desarrollo web se ha convertido en su mayor “enemigo”.

Error de PHP, ordenador embrujado

Me escribe una alumna, me manda la siguiente captura de pantalla, me dice que en su ordenador no aparecen esos mensajes de error, pero en el ordenador de su compañera sí que aparecen, ¿qué está ocurriendo?

tutoria8160855

“Undefined index”, “Undefined variable” significa que se está intentando usar una posición de un array o una variable que no están definidas.

Para evitar que se produzca este error se deben emplear las funciones isset() y empty() para comprobar si la posición o la variable están definidas y tienen algún valor.

Pero, ¿por qué sale el error en un ordenador y no en otro? Porque son diferentes instalaciones y Xampp (o Mamp o lo que sea) puede tener diferente configuración para los mensajes de error que se deben mostrar. El error siempre ha estado ahí, pero al cambiar de ordenador es cuando se han dado cuenta de ello.

¿Qué está fallando?

Lo siguiente es la fotografía de un fragmento de código de un estudiante:

ejemplo-codigo-alumnos

La asignatura que imparto es “Programación Hipermedia I”, asignatura obligatoria en el tercer curso del grado de ingeniería multimedia. Se supone que los estudiantes ya han tenido varias asignaturas sobre programación en primer y segundo curso. Se supone que cuando llegan a tercero ya saben programar. Sin embargo, en el código anterior podemos ver:

  1. Tienen tres sentencias if($_COOKIE && $_COOKIE) que claramente se podrían haber puesto como if-else-if.
  2. Emplean la función strtolower() para pasar a minúsculas algo que claramente ya está en minúsculas.
  3. En vez de almacenar los datos de los usuarios en un array y emplear un bucle para comprobar si los datos son correctos, los datos están mezclados con el código y se escribe una sentencia if de comprobación por cada usuario. ¿Qué pasaría si hubiese mil usuarios?

Y en realidad, este código, programado por dos estudiantes (cuatro ojos ven más que dos), pertenece a una práctica que me sorprendió porque estos estudiantes habían sido los únicos que habían comprobado que los datos recuperados de la cookie eran válidos a la hora de restituir la sesión de un usuario (la típica opción “recordar en este equipo”).

¿Cómo puede explicar conceptos avanzados de programación web si la mayoría de mis estudiantes no son capaces de escribir correctamente unas sentencias básicas?

Ya tenemos PHP 7

Después de un montón de años, por fin, por fin ha llegado PHP 7, PHP 7.0.0 Released:

The PHP development team announces the immediate availability of PHP 7.0.0. This release marks the start of the new major PHP 7 series.

PHP 7.0.0 comes with a new version of the Zend Engine, numerous improvements and new features such as

Improved performance: PHP 7 is up to twice as fast as PHP 5.6
Significantly reduced memory usage
Abstract Syntax Tree
Consistent 64-bit support
Improved Exception hierarchy
Many fatal errors converted to Exceptions
Secure random number generator
Removed old and unsupported SAPIs and extensions
The null coalescing operator (??)
Return and Scalar Type Declarations
Anonymous Classes
Zero cost asserts
For source downloads of PHP 7.0.0 please visit our downloads page, Windows binaries can be found on windows.php.net/download/. The list of changes is recorded in the ChangeLog.

The migration guide is available in the PHP Manual. Please consult it for the detailed list of new features and backward incompatible changes.

The inconvenience of the release lateness in several time zones is caused by the need to ensure the compatibility with the latest OpenSSL 1.0.2e release. Thanks for the patience!

It is not just a next major PHP version being released today. The release being introduced is an outcome of the almost two years development journey. It is a very special accomplishment of the core team. And, it is a result of incredible efforts of many active community members. Indeed, it is not just a final release being brought out today, it is the rise of a new PHP generation with an enormous potential.

Congratulations everyone to this spectacular day for the PHP world!

Grateful thanks to all the contributors and supporters!

En la página Migrar de PHP 5.6.x a PHP 7.0.x se explican las novedades y diferencias de PHP 7.