<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Camilo Herrera on Medium]]></title>
        <description><![CDATA[Stories by Camilo Herrera on Medium]]></description>
        <link>https://medium.com/@camiloandresherrera?source=rss-d00dafbb1ae3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CpxZBQhVsf-ko9UP-fuY-Q.jpeg</url>
            <title>Stories by Camilo Herrera on Medium</title>
            <link>https://medium.com/@camiloandresherrera?source=rss-d00dafbb1ae3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:50:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@camiloandresherrera/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Asignando colores al texto en consola con PHP]]></title>
            <link>https://medium.com/winkhostinglatam/asignando-colores-al-texto-en-consola-con-php-da32d60cabe4?source=rss-d00dafbb1ae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/da32d60cabe4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Camilo Herrera]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 16:54:23 GMT</pubDate>
            <atom:updated>2024-12-03T16:54:23.197Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p1PciXk_RNkq-lcI" /><figcaption>Photo by <a href="https://unsplash.com/@garethharper?utm_source=medium&amp;utm_medium=referral">Gareth Harper</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hola!, tiempo sin vernos. Hoy paso con un artículo corto sobre una funcionalidad de consola que había olvidado y pensé que era específica para scripts bash, y es… darle color a los textos mostrados en aplicaciones de línea de comandos!</p><p>Si, estoy emocionado, es probable que tú sepas que esto existe en PHP pero hasta ahora lo estoy usando de forma recurrente!, (no seas aguafiestas, déjame celebrar mis pequeños triunfos.)</p><p>Para mostrar cómo funciona vamos a crear una pequeña clase en PHP que será nuestro ayudante para colorear textos y mostrarlos en pantalla, esto facilitará incluirla en tus proyectos y mantener la funcionalidad encapsulada para ser usada en cualquier momento.</p><p>Vamos rápidamente con los requisitos para nuestro pequeño proyecto:</p><h4>Requisitos</h4><ul><li>Instalación de PHP 8.2+</li><li>VS Code o tu editor de código preferido</li><li>Acceso a consola de comandos en tu PC Windows/Linux/Mac</li><li>Café, como siempre, de buena calidad!</li></ul><p>Ya con nuestros requisitos cubiertos, vamos a proceder con una pequeña explicación sobre el funcionamiento de los colores en consola de comandos.</p><h4>La historia de los colores en consolas de comandos</h4><p>Todo comenzó en una tarde de verano en la antigua Grecia… ;)</p><p>Bueno, ya en serio, establecer colores en consola se lo podemos agradecer al estándar <strong>ANSI </strong>y sus secuencias de escape que incluyen colores.</p><p>Las secuencias de escape incluyen <strong>\n, \r, \t</strong> seguramente las utilizas regularmente en cadenas de texto, adicionalmente tenemos las secuencias de asignación de colores y estilos al texto en consola que tienen el siguiente formato:</p><p>La cadena debe iniciar con el código <strong>27</strong> decimal pero convertido a <strong>octal</strong>, <strong>hexadecimal </strong>o <strong>Unicode, </strong>dependiendo de tu preferencia y el soporte de tu lenguaje de programación. En esta oportunidad usaremos la versión en octal “<strong>\033” </strong>(también puedes usar “<strong>\e</strong>” que se me hace más fácil)<strong>.</strong></p><p>A continuación debe agregarse el caracter “[“ que es denominado <strong>CSI </strong>(<strong>Control Sequence Introducer</strong> en inglés), y es el encargado de decirle a la consola: — <em>Hey!, aquí viene la secuencia especial para ti bebé ;) </em>—</p><p>La secuencia preliminarmente sería “<strong>\033[</strong>“, pero faltan los colores. La lista de colores básica es restringida, para texto son 8 colores que puedes “convertir” en 16 (si usas la opción de texto en negrita), esta opción de negrita se fija con el primer dígito posterior al caracter <strong>“[“ </strong>y se separa con punto y coma<strong> “0;” </strong>(negrita desactivada) ó <strong>“1;” </strong>(negrita activada).</p><p>Los colores de texto tienen un código numérico que va del 30 al 37.</p><p>A continuación la lista de colores con su respectivo código, sin activar el texto en negrita:</p><p><strong>Colores de Texto</strong></p><pre># Text Colors           Code<br># ---------------------------<br># Black                 0;30<br># White                 0;37<br># Red                   0;31<br># Green                 0;32<br># Brown                 0;33<br># Blue                  0;34<br># Magenta               0;35<br># Cyan                  0;36<br># Grey Bold             0;37</pre><p>Si quieres activar el texto en negrita para el color rojo (Red), por ejemplo, la cadena sería <strong>“1;31”</strong></p><p>Ahora vamos a los colores de fondo del texto, estos también son 8 y están representados por códigos numéricos del 40 al 47 así:</p><p><strong>Colores de Fondo</strong></p><pre># Background Colors     Code<br># ---------------------------<br># Black                 40<br># Red                   41<br># Green                 42<br># Yellow                43<br># Blue                  44<br># Magenta               45<br># Cyan                  46<br># Light Grey            47</pre><p>Los colores de fondo se agregan al final de la cadena antecedidos por “<strong>;</strong>”.</p><p>Para finalizar se usa la letra “<strong>m</strong>” (Solo Dios sabe por qué una letra <strong>m</strong>, si lo sabes agrega un comentario en el artículo y podemos incluir la explicación aquí).</p><p>La cadena completa de color se verá de la siguiente forma:</p><p><strong>“\033[0;37;41m”</strong></p><blockquote><strong>IMPORTANTE: </strong>Ten presente que al fijar un color, todo el texto de consola de ese punto en adelante usará la configuración, para retornar a los valores por defecto de la consola se usa una cadena de scape “<strong>Reset</strong>”, la cadena es “<strong>\033[0m</strong>”</blockquote><p>Una cadena de texto completa con color aplicado se vería así, incluyendo la cadena de reset para volver al color estándar de tu consola:</p><p><strong>“\033[0;37;41m</strong>Mi Texto en Color Blanco y Fondo Rojo<strong>\033[0m”</strong></p><p><strong>Ejemplo en PHP</strong></p><pre>&lt;?php<br><br>$myColorMessage = &quot;\033[0;37;41mMi Texto en Color Blanco y Fondo Rojo\033[0m&quot;.PHP_EOL;<br><br>echo $myColorMessage;</pre><p>Bien, ya entendiendo el concepto y cómo funciona, vamos a implementar nuestra clase para usar en todos esos maravillosos proyectos de línea de comandos en PHP.</p><p>Llamaremos a nuestro archivo y clase “<strong>ConsoleHelper</strong>”, es decir que nuestro archivo se llamará igual con extensión .php</p><p>La clase contiene dos atributos, $<strong>textColors </strong>y $<strong>backgroundColors</strong>, estos son de tipo <strong>array </strong>y tendrán asignados en el constructor los listados de colores disponibles para cada uno de ellos.</p><p>Adicionalmente tendremos un método “<strong>print</strong>()” que será usado para aplicar los colores y mostrar texto en pantalla, este tendrá cinco (5) parámetros, cuatro de los cuales serán opcionales.</p><p>Los parámetros son $<strong>message </strong>(Texto a ser mostrado, obligatorio), $<strong>textColor </strong>(Color del texto usando la llave asignada en el arreglo correspondiente), $<strong>backColor</strong> (Color del fondo usando la llave asignada en el arreglo correspondiente), $<strong>bold </strong>(Indica si se usa o no texto en negrita true/false) y $<strong>newLine </strong>(indica si se agrega un salto de línea al final true/false).</p><p>La implementación es bastante sencilla y finalmente se verá así:</p><p><strong>ConsoleHelper.php</strong></p><pre>&lt;?php<br><br>class ConsoleHelper<br>{<br>    /*<br>    # Text Colors           Code<br>    # ---------------------------<br>    # Black                 0;30<br>    # White                 0;37<br>    # Red                   0;31<br>    # Green                 0;32<br>    # Brown                 0;33<br>    # Blue                  0;34<br>    # Magenta               0;35<br>    # Cyan                  0;36<br>    # Grey Bold             0;37<br><br>    # Background Colors     Code<br>    # ---------------------------<br>    # Black                 40<br>    # Red                   41<br>    # Green                 42<br>    # Yellow                43<br>    # Blue                  44<br>    # Magenta               45<br>    # Cyan                  46<br>    # Light Grey            47<br><br>    */<br><br>    private array $textColors;<br>    private array $backgroundColors;<br><br>    /**<br>     * Inicializa los colores de texto y fondo con sus códigos de escape ANSI.<br>     */<br>    public function __construct()<br>    {<br>        $this-&gt;textColors = [<br>            &#39;black&#39; =&gt; &quot;\033[0;30&quot;,<br>            &#39;white&#39; =&gt; &quot;\033[0;37&quot;,<br>            &#39;red&#39; =&gt; &quot;\033[0;31&quot;,<br>            &#39;green&#39; =&gt; &quot;\033[0;32&quot;,<br>            &#39;yellow&#39; =&gt; &quot;\033[0;33&quot;,<br>            &#39;blue&#39; =&gt; &quot;\033[0;34&quot;,<br>            &#39;magenta&#39; =&gt; &quot;\033[0;35&quot;,<br>            &#39;cyan&#39; =&gt; &quot;\033[0;36&quot;,<br>            &#39;grey&#39; =&gt; &quot;\033[0;37&quot;,<br>            &#39;reset&#39; =&gt; &quot;\033[0m&quot;<br>        ];<br><br>        $this-&gt;backgroundColors = [<br>            &#39;black&#39; =&gt; &quot;40m&quot;,<br>            &#39;red&#39; =&gt; &quot;41m&quot;,<br>            &#39;green&#39; =&gt; &quot;42m&quot;,<br>            &#39;yellow&#39; =&gt; &quot;43m&quot;,<br>            &#39;blue&#39; =&gt; &quot;44m&quot;,<br>            &#39;magenta&#39; =&gt; &quot;45m&quot;,<br>            &#39;cyan&#39; =&gt; &quot;46m&quot;,<br>            &#39;light-grey&#39; =&gt; &quot;47m&quot;,<br>            &#39;reset&#39; =&gt; &quot;\033[0m&quot;<br>        ];<br>    }<br><br>    /**<br>     * Imprime un mensaje en la consola con los colores de texto y fondo especificados.<br>     *<br>     * @param string $message El mensaje a imprimir.<br>     * @param string $textColor El color de texto a aplicar (clave del array textColors).<br>     * @param string $backColor El color de fondo a aplicar (clave del array backgroundColors).<br>     *<br>     * @return void<br>     */<br>    public function print(string $message, string $textColor = &#39;&#39;, string $backColor = &#39;&#39;, bool $bold = false, bool $newLine = true): void<br>    {<br>        $colorMatch = &#39;&#39;;<br>        $resetStr = &#39;&#39;;<br><br>        if (isset($this-&gt;textColors[$textColor]) &amp;&amp; isset($this-&gt;backgroundColors[$backColor])) {<br>            $colorMatch = $this-&gt;textColors[$textColor] . &quot;;&quot; . $this-&gt;backgroundColors[$backColor];<br>            $resetStr = $this-&gt;textColors[&#39;reset&#39;];<br>        }<br><br>        if (isset($this-&gt;textColors[$textColor]) &amp;&amp; !isset($this-&gt;backgroundColors[$backColor])) {<br>            $colorMatch = $this-&gt;textColors[$textColor] . &quot;m&quot;;<br>            $resetStr = $this-&gt;textColors[&#39;reset&#39;];<br>        }<br><br>        if ($bold) {<br>            $colorMatch = str_replace(&quot;[0;&quot;, &quot;[1;&quot;, $colorMatch);<br>        }<br><br>        echo $colorMatch . $message . $resetStr . ($newLine ? PHP_EOL : &#39;&#39;);<br>    }<br>}</pre><p>Ahora vamos a usarla en un script de prueba que llamaremos “<strong>demoConsole.php</strong>” y lo crearemos en el mismo directorio donde se encuentra nuestra clase.</p><p><strong>demoConsole.php</strong></p><pre>&lt;?php<br><br>include(&quot;ConsoleHelper.php&quot;);<br><br>$consoleHelper = new ConsoleHelper();<br><br>$consoleHelper-&gt;print(&quot;Red message&quot;, &quot;red&quot;);<br>$consoleHelper-&gt;print(&quot;Blue message&quot;, &quot;blue&quot;);<br>$consoleHelper-&gt;print(&quot;Green message&quot;, &quot;green&quot;);<br>$consoleHelper-&gt;print(&quot;Yellow message&quot;, &quot;yellow&quot;);<br>$consoleHelper-&gt;print(&quot;Magenta message&quot;, &quot;magenta&quot;);<br>$consoleHelper-&gt;print(message: &quot;Green bold message&quot;, textColor: &quot;green&quot;, bold: true);<br>$consoleHelper-&gt;print(message: &quot;White message with blue background&quot;, textColor: &quot;white&quot;, backColor: &quot;blue&quot;);<br>$consoleHelper-&gt;print(message: &quot;Yellow message with red background&quot;, textColor: &quot;yellow&quot;, backColor: &quot;red&quot;, bold: true);<br>$consoleHelper-&gt;print(message: &quot;Green message with yellow background&quot;, textColor: &quot;green&quot;, backColor: &quot;yellow&quot;, bold: true);<br>$consoleHelper-&gt;print(message: &quot;Cyan message without new line&quot;, textColor: &quot;cyan&quot;, newLine: false);</pre><p>Al ejecutar tu archivo en línea de comandos el resultado debe ser el siguiente:</p><pre>myfolder&gt; php demoConsole.php</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*0qPYTMGbLt-wRa7rmUaqxQ.png" /></figure><p>Y estamos listos para usar nuestra clase y mostrar mensajes que llenen de color el mundo de la consola de tus usuarios!</p><p>No olvides que en <a href="https://winkhosting.co/"><strong>Winkhosting.co</strong></a> somos mucho más que Hosting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da32d60cabe4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/winkhostinglatam/asignando-colores-al-texto-en-consola-con-php-da32d60cabe4">Asignando colores al texto en consola con PHP</a> was originally published in <a href="https://medium.com/winkhostinglatam">winkhostingla</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Assigning Colors to Console Text with PHP]]></title>
            <link>https://medium.com/winkhosting/assigning-colors-to-console-text-with-php-edb78899803d?source=rss-d00dafbb1ae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/edb78899803d</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Camilo Herrera]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 16:45:30 GMT</pubDate>
            <atom:updated>2024-12-03T16:45:30.693Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qpzXTK3z1WTHPqy9" /><figcaption>Photo by <a href="https://unsplash.com/@garethharper?utm_source=medium&amp;utm_medium=referral">Gareth Harper</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello! It has been a while right?. Today, I’m dropping by with a short article about a console feature I had forgotten about and thought was exclusive to bash scripts: <strong>giving color to text displayed in command-line applications!</strong></p><p>Yes, I’m excited! You probably already know this exists in PHP, but I’m only now starting to use it regularly. (let me celebrate my small victories mr. know it all.)</p><p>To show how it works, we’re going to create a small PHP class that will act as our helper for coloring text and displaying it on screen. This will make it easier to include in your projects and keep the functionality encapsulated so it can be used at any time.</p><p>Let’s quickly go over the requirements for our little project:</p><h4>Requirements</h4><ul><li><strong>PHP 8.2+ Installation</strong></li><li><strong>VS Code</strong> or your preferred code editor</li><li><strong>Access to the command line</strong> on your Windows/Linux/Mac PC</li><li><strong>Coffee</strong>, as always, drink the best you can buy! ☕</li></ul><p>With our requirements covered, let’s move on to a brief explanation of how colors work in the command line.</p><h4>History of command line text coloring</h4><p>It’s a warm summer evening in Ancient Greece… ;)</p><p>Well, seriously, we owe the ability to set colors in the console to the <strong>ANSI </strong>standard and its escape sequences, which include colors. Escape sequences like <strong>\n</strong>, <strong>\r</strong>, and <strong>\t</strong> are ones you probably use commonly in text strings. Additionally, we have sequences that assign colors and styles to text in the console, using the following format:</p><p>The string must start with the decimal code <strong>27</strong>, but represented in <strong>octal</strong>, <strong>hexadecimal</strong>, or <strong>Unicode</strong>, depending on your preference and the support provided by your programming language. In this case, we will use the octal version &quot;<strong>\033</strong>&quot; (you can also use &quot;<strong>\e</strong>&quot;, which I find easier).</p><p>Next, you need to add the character “<strong>[</strong>“ which is called <strong>CSI </strong>(<strong>Control Sequence Introducer</strong>), and its job is to tell the console: <em>“Hey! Here comes a special sequence for you, baby ;)”</em></p><p>The preliminary sequence would be &quot;<strong>\033[</strong>&quot;, but we’re still missing the colors. The basic color list is limited: for text, there are 8 colors that you can &quot;turn&quot; into 16 (if you use the bold text option). This bold option is set by the first digit after the &quot;[&quot; character and is separated with a semicolon, using either &quot;<strong>0;</strong>&quot; (<strong>bold off</strong>) or &quot;<strong>1;</strong>&quot; (<strong>bold on</strong>).</p><p>The text color codes range from <strong>30 </strong>to <strong>37</strong>.</p><p>The following is the list of colors with its corresponding numeric code, without using the bold option:</p><p><strong>Text Colors</strong></p><pre># Text Colors           Code<br># ---------------------------<br># Black                 0;30<br># White                 0;37<br># Red                   0;31<br># Green                 0;32<br># Brown                 0;33<br># Blue                  0;34<br># Magenta               0;35<br># Cyan                  0;36<br># Grey Bold             0;37</pre><p>If you want to enable the bold style for the red color, the string would be something like “<strong>1;31</strong>”</p><p>Ahora vamos a los colores de fondo del texto, estos también son 8 y están representados por códigos numéricos del 40 al 47 así:</p><p>Now let’s check the background colors available, there are 8 colors and they are represented by a numeric range from 40 to 47 like this:</p><h4>Background Colors</h4><pre># Background Colors     Code<br># ---------------------------<br># Black                 40<br># Red                   41<br># Green                 42<br># Yellow                43<br># Blue                  44<br># Magenta               45<br># Cyan                  46<br># Light Grey            47</pre><p>Background colors are added at the end of the string, preceded by a semicolon “<strong>;</strong>”.</p><p>The letter “<strong>m</strong>” is used at the end of the scape sequence. (Only God knows why an “<strong>m</strong>” was chosen — if you know, leave a comment on the article, and we can include the explanation here).</p><p>The complete color string will look like this:<br><strong>&quot;\033[0;37;41m&quot;</strong></p><blockquote><strong>IMPORTANT:</strong> Keep in mind that once you set a color, all the console text from that point onward will use the same configuration. To return to the console’s default settings, use a “Reset” escape sequence. The reset string is:<strong>&quot;\033[0m&quot;</strong></blockquote><p>A complete text string with color applied would look like this, including the reset string to return to the standard console color:</p><p><strong>&quot;\033[0;37;41mMy Text in White with Red Background\033[0m&quot;</strong></p><p><strong>PHP example</strong></p><pre>&lt;?php<br><br>$myColorMessage = &quot;\033[0;37;41mMi Texto en Color Blanco y Fondo Rojo\033[0m&quot;.PHP_EOL;<br><br>echo $myColorMessage;</pre><p>Well, now that we understand the concept and how it works, let’s implement our class to use in all those wonderful command-line projects in PHP.</p><p>We will call our file and class “<strong>ConsoleHelper</strong>,” meaning our file will have the same name with a .php extension.</p><p>The class will contain two attributes, <strong>$textColors </strong>and <strong>$backgroundColors</strong>, which are arrays and will have the available color lists assigned in the constructor.</p><p>Additionally, we will have a method called <strong>print()</strong> that will be used to apply the colors and display text on the screen. This method will have five (5) parameters, four of which will be optional.</p><p>The parameters are <strong>$message</strong> (text to be displayed, required), <strong>$textColor</strong> (text color using the corresponding key from the array), <strong>$backColor</strong> (background color using the corresponding key from the array), <strong>$bold</strong> (indicates whether bold text is used or not, true/false), and <strong>$newLine</strong> (indicates whether a newline is added at the end, true/false).</p><p>The implementation is really simple and looks like this:</p><p><strong>ConsoleHelper.php</strong></p><pre>&lt;?php<br><br>class ConsoleHelper<br>{<br>    /*<br>    # Text Colors           Code<br>    # ---------------------------<br>    # Black                 0;30<br>    # White                 0;37<br>    # Red                   0;31<br>    # Green                 0;32<br>    # Brown                 0;33<br>    # Blue                  0;34<br>    # Magenta               0;35<br>    # Cyan                  0;36<br>    # Grey Bold             0;37<br><br>    # Background Colors     Code<br>    # ---------------------------<br>    # Black                 40<br>    # Red                   41<br>    # Green                 42<br>    # Yellow                43<br>    # Blue                  44<br>    # Magenta               45<br>    # Cyan                  46<br>    # Light Grey            47<br><br>    */<br><br>    private array $textColors;<br>    private array $backgroundColors;<br><br>    /**<br>     * Initializes the text and background colors with their ANSI escape codes.<br>     */<br>    public function __construct()<br>    {<br>        $this-&gt;textColors = [<br>            &#39;black&#39; =&gt; &quot;\033[0;30&quot;,<br>            &#39;white&#39; =&gt; &quot;\033[0;37&quot;,<br>            &#39;red&#39; =&gt; &quot;\033[0;31&quot;,<br>            &#39;green&#39; =&gt; &quot;\033[0;32&quot;,<br>            &#39;yellow&#39; =&gt; &quot;\033[0;33&quot;,<br>            &#39;blue&#39; =&gt; &quot;\033[0;34&quot;,<br>            &#39;magenta&#39; =&gt; &quot;\033[0;35&quot;,<br>            &#39;cyan&#39; =&gt; &quot;\033[0;36&quot;,<br>            &#39;grey&#39; =&gt; &quot;\033[0;37&quot;,<br>            &#39;reset&#39; =&gt; &quot;\033[0m&quot;<br>        ];<br><br>        $this-&gt;backgroundColors = [<br>            &#39;black&#39; =&gt; &quot;40m&quot;,<br>            &#39;red&#39; =&gt; &quot;41m&quot;,<br>            &#39;green&#39; =&gt; &quot;42m&quot;,<br>            &#39;yellow&#39; =&gt; &quot;43m&quot;,<br>            &#39;blue&#39; =&gt; &quot;44m&quot;,<br>            &#39;magenta&#39; =&gt; &quot;45m&quot;,<br>            &#39;cyan&#39; =&gt; &quot;46m&quot;,<br>            &#39;light-grey&#39; =&gt; &quot;47m&quot;,<br>            &#39;reset&#39; =&gt; &quot;\033[0m&quot;<br>        ];<br>    }<br><br>    /**<br>     * Prints a message to the console with specified text and background colors.<br>     *<br>     * @param string $message The message to be printed.<br>     * @param string $textColor The text color to apply (key from textColors array).<br>     * @param string $backColor The background color to apply (key from backgroundColors array).<br>     *<br>     * @return void<br>     */<br>    public function print(string $message, string $textColor = &#39;&#39;, string $backColor = &#39;&#39;, bool $bold = false, bool $newLine = true): void<br>    {<br>        $colorMatch = &#39;&#39;;<br>        $resetStr = &#39;&#39;;<br><br>        if (isset($this-&gt;textColors[$textColor]) &amp;&amp; isset($this-&gt;backgroundColors[$backColor])) {<br>            $colorMatch = $this-&gt;textColors[$textColor] . &quot;;&quot; . $this-&gt;backgroundColors[$backColor];<br>            $resetStr = $this-&gt;textColors[&#39;reset&#39;];<br>        }<br><br>        if (isset($this-&gt;textColors[$textColor]) &amp;&amp; !isset($this-&gt;backgroundColors[$backColor])) {<br>            $colorMatch = $this-&gt;textColors[$textColor] . &quot;m&quot;;<br>            $resetStr = $this-&gt;textColors[&#39;reset&#39;];<br>        }<br><br>        if ($bold) {<br>            $colorMatch = str_replace(&quot;[0;&quot;, &quot;[1;&quot;, $colorMatch);<br>        }<br><br>        echo $colorMatch . $message . $resetStr . ($newLine ? PHP_EOL : &#39;&#39;);<br>    }<br>}</pre><p>Now let’s use it in a test script that we will call “<strong>demoConsole.php</strong>” and will be created in the same directory where our class is located.</p><p><strong>demoConsole.php</strong></p><pre>&lt;?php<br><br>include(&quot;ConsoleHelper.php&quot;);<br><br>$consoleHelper = new ConsoleHelper();<br><br>$consoleHelper-&gt;print(&quot;Red message&quot;, &quot;red&quot;);<br>$consoleHelper-&gt;print(&quot;Blue message&quot;, &quot;blue&quot;);<br>$consoleHelper-&gt;print(&quot;Green message&quot;, &quot;green&quot;);<br>$consoleHelper-&gt;print(&quot;Yellow message&quot;, &quot;yellow&quot;);<br>$consoleHelper-&gt;print(&quot;Magenta message&quot;, &quot;magenta&quot;);<br>$consoleHelper-&gt;print(message: &quot;Green bold message&quot;, textColor: &quot;green&quot;, bold: true);<br>$consoleHelper-&gt;print(message: &quot;White message with blue background&quot;, textColor: &quot;white&quot;, backColor: &quot;blue&quot;);<br>$consoleHelper-&gt;print(message: &quot;Yellow message with red background&quot;, textColor: &quot;yellow&quot;, backColor: &quot;red&quot;, bold: true);<br>$consoleHelper-&gt;print(message: &quot;Green message with yellow background&quot;, textColor: &quot;green&quot;, backColor: &quot;yellow&quot;, bold: true);<br>$consoleHelper-&gt;print(message: &quot;Cyan message without new line&quot;, textColor: &quot;cyan&quot;, newLine: false);</pre><p>When you run your file in the command line, the result should be as follows:</p><pre>myfolder&gt; php demoConsole.php</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*0ZPxi7LTRO22e9ndpocXIA.png" /></figure><p>And we’re ready to use our class and display messages that will color the console world for users worldwide!</p><p>Don’t forget that at <a href="https://winkhosting.com/"><strong>Winkhosting.co</strong>m</a>, we’re much more than hosting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edb78899803d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/winkhosting/assigning-colors-to-console-text-with-php-edb78899803d">Assigning Colors to Console Text with PHP</a> was originally published in <a href="https://medium.com/winkhosting">winkhosting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creando un Web Fuzzer con PHP]]></title>
            <link>https://medium.com/@camiloandresherrera/creando-un-web-fuzzer-con-php-246aa3261cf1?source=rss-d00dafbb1ae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/246aa3261cf1</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[fuzzing]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Camilo Herrera]]></dc:creator>
            <pubDate>Sat, 24 Aug 2024 00:09:57 GMT</pubDate>
            <atom:updated>2024-08-24T00:09:57.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b4IpCp8lCkC_4apj" /><figcaption>Photo by <a href="https://unsplash.com/@paulius005?utm_source=medium&amp;utm_medium=referral">Paulius Dragunas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hola!, espero que todo esté marchando muy bien para ti. Hoy quiero compartir contigo este proyecto que nos ayudará a entender internamente cómo funciona un <strong>Web Fuzzer</strong>, si desconoces el término vamos a explicarlo brevemente a continuación.</p><h4>Qué es un Web Fuzzer?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0l4WasiT8ulvsNATHt-PA.png" /></figure><p>Un <strong>Web Fuzzer</strong> es una herramienta utilizada, generalmente, durante la fase de recopilación de información de un objetivo de “auditoría de seguridad” (ya sabes a lo que me refiero verdad ;) ?) en Internet, determinar los posibles URLs activos en un sitio web, esto incluye subdominios, directorios e incluso parámetros usados en peticiones GET, POST ó cualquiera de los tipos permitidos en HTTP</p><p>Se puede considerar al <strong>Web Fuzzer</strong> como una herramienta de fuerza bruta, ya que normalmente se utilizan diccionarios de palabras o parámetros a usar para escanear un sitio web y determinar si las URLs creadas a partir de estos diccionarios existen o no, dependiendo de la respuesta del servidor a cada una de ellas. Por ejemplo, si quieres saber si un sitio web cuyo dominio asignado es “misitioweb.com” cuenta con rutas como “about”, “admin”, “login”, le indicas al fuzzer que quieres intentar realizar peticiones a <a href="http://misitioweb.com/about,">http://misitioweb.com/about,</a> <a href="http://misitioweb.com/admin,">http://misitioweb.com/admin,</a> <a href="http://misitioweb.com/login">http://misitioweb.com/login</a></p><p>Este se encargaría de realizar la operación, capturar los códigos de estado de cada petición y presentarte un informe indicando si existen o no.</p><p>Luego con estas rutas, puedes investigar si existen vulnerabilidades conocidas o si se trata de información privada expuesta en el sitio que puede facilitar un ataque cibernético.</p><blockquote><strong>IMPORTANTE:</strong> Sabemos que eres un buen muchacho y esos ataques no van a venir de ti, recuerda que puedes meterte en problemas si usas este tipo de herramientas sin autorización del objetivo.</blockquote><p>Ahora que sabemos ligeramente de que se trata, vamos a tratar de hacer nuestro propio <strong>Web Fuzzer </strong>con nuestro amado PHP!.</p><h4>Requisitos</h4><p>Vamos a ver los requisitos en nuestro entorno de desarrollo para crear nuestro fuzzer:</p><ul><li>Un editor de código de tu preferencia, aquí usamos VS Code</li><li>PHP 8.3 CLI para ejecutar a través de línea de comandos, esta solución será una herramienta para uso a través de una interfaz de línea de comandos. (comandos, comandos, comandos por todos lados).</li><li>Diccionario de términos a usar para crear las URLs a consultar, puedes encontrar gran cantidad de diccionarios en el siguiente repositorio: <a href="https://github.com/danielmiessler/SecLists">https://github.com/danielmiessler/SecLists</a> veremos más adelante una lista de pruebas que podemos usar, pero el cielo es el límite.</li><li>Un buen café de calidad, no tomes porquerías.</li></ul><h4>Estructura de la solución</h4><p>Siempre acostumbro a plantear mis soluciones desde los componentes, directorios y archivos, esta no será la excepción así que aquí vamos:</p><p>Vamos a dividir nuestra solución en las siguientes partes (archivos):</p><ul><li><strong>Logger.php:</strong> Este se encargará de generar un archivo de registro con los resultados y mostrarlos en pantalla también.</li><li><strong>DictionaryManager.php:</strong> Contendrá todas las rutinas para leer los diccionarios a usar en la generación de las rutas a ser consultadas por nuestro fuzzer.</li><li><strong>FuzzEngine.php: </strong>Este será nuestro motor de fuzzing, se encargará de ejecutar las peticiones al sitio.</li><li><strong>fuzzer.php:</strong> El punto de entrada de nuestra aplicación, recibirá los parámetros de línea de comandos a usar.</li><li><strong>Archivo de diccionario:</strong> Para pruebas usaremos el diccionario con nombre “subdomains-top1million-5000.txt” que se encuentra en el repositorio mencionado al inicio, este archivo se encuentra en la ruta <a href="https://github.com/danielmiessler/SecLists/blob/master/Discovery/DNS/subdomains-top1million-5000.txt">https://github.com/danielmiessler/SecLists/blob/master/Discovery/DNS/subdomains-top1million-5000.txt</a> también puedes considerar clonar el repositorio completo para contar con copia de todos los diccionarios disponibles en tu PC.</li></ul><p>Crearemos nuestros archivos en un directorio y quedarán de la siguiente forma:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*JTUvpKGvMPrHUZDw2ia_Aw.png" /></figure><p>Ahora si, vamos a cada uno de ellos y revisemos el código fuente.</p><h4>Logger.php</h4><p>Este componente es el encargado de registrar los resultados de la consulta de las URLs, los almacena en un archivo con un patrón de nombre “<strong>fuzzer-Y-m-d_H-i-s.log</strong>” y los muestra en pantalla.</p><p>También permite fijar un nombre personalizado para el archivo y la ruta en donde será guardado, estos parámetros son opcionales en el constructor de la clase.</p><p>El código fuente es el siguiente:</p><pre>&lt;?php<br><br>class Logger<br>{<br>    private string $logfile;<br>    private string $logPath;<br><br>    /**<br>     * Construye una nueva instancia de la clase.<br>     *<br>     * @param string|null $logfile El path del archivo de log. Si no se especifica, se utiliza la fecha y hora actuales para nombrar el archivo.<br>     * @param string|null $logPath el path de la carpeta donde se almacenará el archivo de log.<br>     */<br>    public function __construct(?string $logfile = null, ?string $logPath = null)<br>    {<br>        $this-&gt;logPath = $logPath ?? __DIR__;<br>        if ($logfile === null) {<br>            $this-&gt;logfile = $this-&gt;logPath . &quot;/fuzzer-&quot; . date(&quot;Y-m-d_H-i-s&quot;) . &quot;.log&quot;;<br>        } else {<br>            $this-&gt;logfile = $this-&gt;logPath . &quot;/&quot; . $logfile;<br>        }<br>    }<br><br>    /**<br>     * Registra un mensaje en el archivo de log y lo muestra en pantalla.<br>     *<br>     * @param string $message El mensaje a registrar.<br>     * @return void<br>     */<br>    public function log(string $message): void<br>    {<br>        $timestamp = date(&quot;Y-m-d H:i:s&quot;);<br>        $logmessage = &quot;$timestamp $message\n&quot;;<br>        file_put_contents($this-&gt;logfile, $logmessage, FILE_APPEND);<br>        echo $logmessage;<br>    }<br>}</pre><h4><strong>DictionaryManager.php</strong></h4><p>El DictionaryManager es el componente encargado de abrir/cerrar el archivo de diccionario a usar y leer una a una las líneas en él para realizar la petición al sitio web y determine si está activo el URL o no.</p><p>El código fuente de este componente a continuación:</p><pre>&lt;?php<br><br>class DictionaryManager<br>{<br>    private string $file;<br>    private mixed $handle;<br><br>    /**<br>     * Inicializa una nueva instancia de la clase.<br>     *<br>     * @param string $filename El nombre del archivo que se va a abrir.<br>     * @throws Exception Si el archivo no puede ser abierto.<br>     */<br>    public function __construct(string $filename)<br>    {<br>        $this-&gt;file = $filename;<br>        $this-&gt;handle = fopen($this-&gt;file, &#39;r&#39;);<br>        if ($this-&gt;handle === false) {<br>            throw new Exception(&quot;No se puede abrir el archivo $this-&gt;file&quot;);<br>        }<br>    }<br><br>    /**<br>     * Lee una línea del archivo y la devuelve como cadena.<br>     *<br>     * @return string|null La línea leída del archivo, o null si el final del archivo ha sido alcanzado.<br>     * @throws No se lanza excepción alguna por esta función, pero el manejador del archivo se cierra si el final del archivo ha sido alcanzado.<br>     */<br>    public function ReadLine(): ?string<br>    {<br>        $line = fgets($this-&gt;handle);<br>        if ($line === false) {<br>            fclose($this-&gt;handle);<br>            $this-&gt;handle = null;<br>            return null;<br>        }<br>        return trim($line);<br>    }<br><br>    /**<br>     * Destruye la instancia de la clase y cierra el manejador del archivo si está abierto.<br>     */<br>    public function __destruct()<br>    {<br>        if ($this-&gt;handle !== null) {<br>            fclose($this-&gt;handle);<br>        }<br>    }<br>}</pre><h4>FuzzEngine.php</h4><p>Este componente es el encargado de realizar las consultas de URLs a verificar, cuenta con dos funciones, una para iniciar la ejecución “<strong>run</strong>()” y una para validar si el URL consultado está activo o no “<strong>isUrlValid</strong>()”.</p><p><strong>FuzzEngine </strong>usa peticiones de tipo <strong>HEAD</strong>, esto para acelerar el proceso de consulta y evitar la descarga del cuerpo del sitio web, ya que no es necesario.</p><p>El constructor de la clase dentro del archivo permite fijar los siguientes parámetros de ejecución:</p><ul><li><strong>$domain:</strong> Dominio a en el que se verificarán los URLs, ej. <a href="https://misitioweb.com/">https://mywebsite.com</a></li><li><strong>$validResponseCodes:</strong> este es un arreglo que contiene los códigos de estado HTTP que serán considerados válidos para indicar que un URL está activo, por defecto puedes usar 200, pero puedes usar todos los que requieras.</li><li><strong>$dictionaryPath:</strong> Esta es la ruta donde se encuentra el diccionario a usar en la detección de los URLs activos.</li><li><strong>$logFile:</strong> El nombre, <strong>opcional</strong>, que quieras asignar al archivo de log de ejecución de la revisión.</li><li><strong>$logPath:</strong> Este parámetro, <strong>opcional</strong>, permite fijar la ruta donde será guardado el archivo de registro.</li></ul><p>Las peticiones al sitio web son realizadas a través de nuestro querido <strong>cURL</strong> y se registra el resultado en el archivo designado y en pantalla si está activa la dirección.</p><p>El código fuente es el siguiente:</p><pre>&lt;?php<br><br>class FuzzEngine<br>{<br><br>    private string $domain;<br>    private array $validResponseCodes;<br>    private DictionaryManager $dictionaryManager;<br>    private Logger $logger;<br><br>    /**<br>     * Construye una nueva instancia de la clase.<br>     *<br>     * @param string $domain El dominio a utilizar.<br>     * @param array&lt;int&gt; $validResponseCodes Los códigos de respuesta HTTP a considerar válidos.<br>     * @param string $dictionaryPath La ruta al archivo del diccionario.<br>     * @param string|null $logfile La ruta al archivo de registro. Si no se especifica, se utilizar  la fecha y hora para nombrar el archivo.<br>     * @param string|null $logPath La ruta a la carpeta donde se almacenar  el archivo de registro.<br>     */<br>    public function __construct(string $domain, array $validResponseCodes, string $dictionaryPath, ?string $logfile = null, ?string $logPath = null)<br>    {<br>        $this-&gt;domain = $domain;<br>        $this-&gt;validResponseCodes = $validResponseCodes;<br>        $this-&gt;dictionaryManager = new DictionaryManager($dictionaryPath);<br>        $this-&gt;logger = new Logger($logfile, $logPath);<br>    }<br><br>    /**<br>     * Escanea el archivo del diccionario y devuelve una lista de URLs válidas.<br>     */<br>    public function scan(): void<br>    {<br>        while (($line = $this-&gt;dictionaryManager-&gt;ReadLine()) !== null) {<br>            $url = $this-&gt;domain . &#39;/&#39; . trim($line);<br>            $this-&gt;isUrlValid($url);<br>        }<br>    }<br><br>    /**<br>     * Verifica si una URL dada es válida enviando una solicitud HEAD y verificando el código de respuesta HTTP.<br>     *<br>     * @param string $url La URL a verificar para su validez.<br>     */<br>    private function isUrlValid(string $url): void<br>    {<br>        $ch = curl_init($url);<br>        curl_setopt($ch, CURLOPT_NOBODY, true);<br>        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);<br>        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);<br>        curl_exec($ch);<br><br>        $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);<br>        curl_close($ch);<br><br>        $valid = false;<br>        if (in_array($responseCode, $this-&gt;validResponseCodes)) {<br>            $valid = true;<br>            $this-&gt;logger-&gt;log(&quot;Código de respuesta para URL $url: $responseCode &quot; . ($valid ? &quot;ACTIVO&quot; : &quot;INACTIVO&quot;));<br>        }<br>    }<br>}</pre><p>Ahora vamos al punto de entrada de nuestra aplicación.</p><h4><strong>fuzzer.php</strong></h4><p>Nuestro archivo fuzzer.php es el encargado de la interacción con el usuario y recibir los argumentos de línea de comandos necesarios para verificar los URLs.</p><p>Este también valida que los parámetros requeridos estén presentes e inicia el proceso tal como se muestra a continuación:</p><pre>&lt;?php<br><br>/**<br> * Fuzzing de direcciones web para encontrar recursos no<br> * documentados.<br> *<br> * El script utiliza un diccionario de palabras y nombres de<br> * dominio para construir direcciones web y verificar si<br> * existen.<br> *<br> * Uso:<br> *    php fuzzer.php &lt;dominio&gt; &lt;códigos de respuesta válidos&gt; &lt;ruta al diccionario&gt; [&lt;ruta al archivo de log&gt;] [&lt;ruta al directorio de logs&gt;]<br> *<br> * Ejemplo:<br> *    php fuzzer.php ejemplo.com 200,301,302,403 /path/to/subdomains-top1million-5000.txt logfile.log /path/to/logs<br> */<br>require_once &#39;FuzzEngine.php&#39;;<br>require_once &#39;DictionaryManager.php&#39;;<br>require_once &#39;Logger.php&#39;;<br><br>// Captura los argumentos de línea de comandos<br>$domain = $argv[1];<br>$validResponseCodes = explode(&#39;,&#39;, $argv[2]);<br>$dictionaryPath = $argv[3];<br>$logfile = $argv[4] ?? null;<br>$logPath = $argv[5] ?? null;<br><br>// Valida que los argumentos requeridos estén presentes<br>if (empty($domain) || empty($validResponseCodes) || empty($dictionaryPath)) {<br>    echo &quot;Error: Los siguientes argumentos son requeridos:\n&quot;;<br>    echo &quot;  1. Dominio a ser utilizado\n&quot;;<br>    echo &quot;  2. Lista de códigos de respuesta válidos separados por comas\n&quot;;<br>    echo &quot;  3. Ruta al archivo del diccionario\n&quot;;<br>    exit(1);<br>}<br><br>// Crea una nueva instancia de la clase FuzzEngine<br>$fuzzer = new FuzzEngine($domain, $validResponseCodes, $dictionaryPath, $logfile, $logPath);<br><br>$fuzzer-&gt;scan();</pre><p>Ya contando con todos los componentes, vamos a ejecutar nuestro fuzzer de la siguiente forma:</p><p>Inicia una consola de comandos, ingresa al directorio donde se encuentran tus archivos y ejecuta el siguiente comando:</p><h4>Ejecución</h4><pre>/my/folder/&gt;php fuzzer.php http://mysite.com 200 /path/to/my/dictionary/subdomains-top1million-5000.txt</pre><p>Recuerda cambiar las rutas mostradas en el ejemplo por las rutas específicas en tu PC.</p><p>La ejecución debe mostrar algo similar a esto si encuentra URLs activas:</p><pre>2024-08-22 21:01:07 Respuesta para el URL http://localhost/www: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/mail: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/ftp: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/localhost: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/webmail: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/smtp: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/webdisk: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/pop: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/cpanel: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/whm: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/ns1: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/ns2: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/autodiscover: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/autoconfig: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/ns: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/test: 200 ACTIVO<br>2024-08-22 21:01:07 Respuesta para el URL http://localhost/m: 200 ACTIVO</pre><p>Si no indicaste el nombre del archivo de log, o el directorio donde debe guardarse, encontrarás un archivo creado con el resultado de la verificación en el directorio raíz junto a los demás archivos que creamos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*poOgqj38JH_aDZt2-aOtCg.png" /></figure><p>Y con esto finalizamos nuestra historia, ahora que sabes como funciona un web fuzzer, úsalo prudentemente.</p><p>Recuerda que en <a href="https://winkhosting.co/"><strong>Winkhosting.co</strong></a> somos mucho más que hosting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=246aa3261cf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Web Fuzzer with PHP]]></title>
            <link>https://medium.com/@camiloandresherrera/creating-a-web-fuzzer-with-php-5876b9826396?source=rss-d00dafbb1ae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5876b9826396</guid>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[fuzzing]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Camilo Herrera]]></dc:creator>
            <pubDate>Sat, 24 Aug 2024 00:08:53 GMT</pubDate>
            <atom:updated>2024-08-24T00:08:53.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CEfItVGNpxgvhhCC" /><figcaption>Photo by <a href="https://unsplash.com/@paulius005?utm_source=medium&amp;utm_medium=referral">Paulius Dragunas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello, I hope everything is going very well for you. Today I want to share with you this project that will help us to understand internally how a Web Fuzzer works, if you don’t know the term we are going to explain it briefly below.</p><h4>What is a Web Fuzzer?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0Wq4x27A31-b1Aof8ouCcw.png" /></figure><p>A Web Fuzzer is a tool used, generally, during the information gathering phase of a “security audit” (you know what I mean right ;) ?) target on the Internet, to determine the possible active URLs on a website, this includes subdomains, directories and even parameters used in GET, POST requests or any of the types allowed in HTTP.</p><p>The Web Fuzzer can be considered a brute force tool, since it normally uses dictionaries of words or parameters to scan a website and determine whether the URLs created from these dictionaries exist or not, depending on the server’s response to each of them. For example, if you want to know if a website whose assigned domain is “ mywebsite.com” has paths such as “about”, “admin”, “login”, you tell the fuzzer that you want to try to make requests to <a href="http://mywebsite.com/about">http://mywebsite.com/about</a>, <a href="http://mywebsite.com/admin">http://mywebsite.com/admin</a>, <a href="http://mywebsite.com/login">http://mywebsite.com/login</a>.</p><p>It will perform the operation, capture the status codes of each request and present you with a report indicating whether they exist or not.</p><p>Then with these routes, you can research if there are known vulnerabilities or if there is private information exposed on the site that can facilitate a cyber attack.</p><blockquote><strong>WARNING:</strong> We know you are a good boy and these attacks are not going to come from you, remember that you can get into trouble if you use this kind of tools without the target’s authorization.</blockquote><p>Now that we know slightly what it is all about, let’s try to make our own Web Fuzzer with our beloved PHP!</p><h4>Requirements</h4><p>Let’s see the requirements in our development environment to create our fuzzer:</p><ul><li>A code editor of your choice, here we use VS Code</li><li>PHP 8.3 CLI to run through command line, this solution will be a tool for use through a command line interface (commands, commands, commands everywhere).</li><li>Dictionary of terms to use to create the URLs to query, you can find a lot of dictionaries in the following repository: <a href="https://github.com/danielmiessler/SecLists">https://github.com/danielmiessler/SecLists</a> we will see later a list of tests that we can use, but the sky is the limit.</li><li>A good quality coffee, don’t drink junk.</li></ul><h4>Structure of the solution</h4><p>I always use to approach my solutions from components, directories and files, this will not be the exception so here we go:</p><p>Let’s breakdown our solution like this (files):</p><ul><li><strong>Logger.php:</strong> This will generate a log file with the results and display them on the screen as well.</li><li><strong>DictionaryManager.php:</strong> It will contain all the routines to read the dictionaries to be used in the generation of the URLs to be scanned by our fuzzer.</li><li><strong>FuzzEngine.php:</strong> This will be our fuzzing engine, it will be in charge of executing the requests to the target site.</li><li><strong>fuzzer.php:</strong> The entry point of our application, it will receive the command line parameters to use and start the scan.</li><li><strong>Dictionary file:</strong> For testing purposes we will use the dictionary named “subdomains-top1million-5000.txt” found in the repository mentioned at the beginning, this file is located here <a href="https://github.com/danielmiessler/SecLists/blob/master/Discovery/DNS/subdomains-top1million-5000.txt">https://github.com/danielmiessler/SecLists/blob/master/Discovery/DNS/subdomains-top1million-5000.txt</a> you can also consider cloning the complete repository to have a copy of all the dictionaries available on your PC.</li></ul><p>We will create our files in a directory and they will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*p1oFO0W0XAPYEpOgtiGlig.png" /></figure><p>Now, let’s go check each of them and review the source code.</p><h4>Logger.php</h4><p>This component is responsible for collecting the results of the URL request, storing them in a file with a pattern name “fuzzer-Y-m-d_H-i-s.log” and displaying them on the screen.</p><p>It also allows to set a custom name for the file and the path where it will be saved, these parameters are optional in the class constructor.</p><p>The source code is as follows:</p><pre>&lt;?php<br><br>class Logger<br>{<br>    private string $logfile;<br>    private string $logPath;<br><br>    /**<br>     * Constructs a new instance of the class.<br>     *<br>     * @param string|null $logfile The path to the log file. If not specified, the date and time will be used to name the file.<br>     * @param string|null $logPath the path to the folder where the log file will be stored.<br>     */<br>    public function __construct(?string $logfile = null, ?string $logPath = null)<br>    {<br>        $this-&gt;logPath = $logPath ?? __DIR__;<br>        if ($logfile === null) {<br>            $this-&gt;logfile = $this-&gt;logPath . &quot;/fuzzer-&quot; . date(&quot;Y-m-d_H-i-s&quot;) . &quot;.log&quot;;<br>        } else {<br>            $this-&gt;logfile = $this-&gt;logPath . &quot;/&quot; . $logfile;<br>        }<br>    }<br><br>    /**<br>     * Logs a message to the log file and outputs it to the screen.<br>     *<br>     * @param string $message The message to be logged.<br>     * @return void<br>     */<br>    public function log(string $message): void<br>    {<br>        $timestamp = date(&quot;Y-m-d H:i:s&quot;);<br>        $logmessage = &quot;$timestamp $message\n&quot;;<br>        file_put_contents($this-&gt;logfile, $logmessage, FILE_APPEND);<br>        echo $logmessage;<br>    }<br>}</pre><h4>DictionaryManager.php</h4><p>The DictionaryManager is the component in charge of opening/closing the dictionary file to be used and reading one by one the lines in it to perform the request to the web site and determine if the URL is active or not.</p><p>The source code of this component is shown below:</p><pre>&lt;?php<br><br>class DictionaryManager<br>{<br>    private string $file;<br>    private mixed $handle;<br><br>    /**<br>     * Initializes a new instance of the class.<br>     *<br>     * @param string $filename The name of the file to be opened.<br>     * @throws Exception If the file cannot be opened.<br>     */<br>    public function __construct(string $filename)<br>    {<br>        $this-&gt;file = $filename;<br>        $this-&gt;handle = fopen($this-&gt;file, &#39;r&#39;);<br>        if ($this-&gt;handle === false) {<br>            throw new Exception(&quot;Could not open file $this-&gt;file&quot;);<br>        }<br>    }<br><br>    /**<br>     * Reads a line from the file and returns it as a string.<br>     *<br>     * @return string|null The line read from the file, or null if the end of the file has been reached.<br>     * @throws No exception is thrown by this function, but the file handle is closed if the end of the file is reached.<br>     */<br>    public function ReadLine(): ?string<br>    {<br>        $line = fgets($this-&gt;handle);<br>        if ($line === false) {<br>            fclose($this-&gt;handle);<br>            $this-&gt;handle = null;<br>            return null;<br>        }<br>        return trim($line);<br>    }<br><br>    /**<br>     * Destroys the instance of the class and closes the file handle if it is open.<br>     */<br>    public function __destruct()<br>    {<br>        if ($this-&gt;handle !== null) {<br>            fclose($this-&gt;handle);<br>        }<br>    }<br>}</pre><h4>FuzzEngine.php</h4><p>This component is in charge of performing the URL requests to be verified, it has two functions, one to start the execution “<strong>run</strong>()” and one to validate if the URL requested is active or not “<strong>isUrlValid</strong>()”.</p><p>The <strong>FuzzEngine </strong>class uses HEAD requests to speed up the process and avoid downloading the html body, as it is not necessary.</p><p>The class constructor inside the file allows to set the following execution parameters:</p><ul><li><strong>$domain</strong>: Target domain, e.g. <a href="https://mywebsite.com/">https://mywebsite.com</a></li><li><strong>$validResponseCodes</strong>: this is an array containing the HTTP status codes that will be considered valid to indicate that an URL is active, by default you can use 200, but you can use as many as you need.</li><li><strong>$dictionaryPath</strong>: This is the path where the dictionary to be used in the detection of active URLs is located.</li><li><strong>$logFile</strong>: The optional name that you want to assign to the revision execution log file.</li><li><strong>$logPath</strong>: This parameter is optional and allows you to set the path where the log file will be saved.</li></ul><p>Requests to the web site are made through our beloved <strong>cURL </strong>and the result is recorded in the designated file and on screen if the address is active.</p><p>The source code is as follows:</p><pre>&lt;?php<br><br>class FuzzEngine<br>{<br><br>    private string $domain;<br>    private array $validResponseCodes;<br>    private DictionaryManager $dictionaryManager;<br>    private Logger $logger;<br><br>    /**<br>     * Constructs a new instance of the class.<br>     *<br>     * @param string $domain The domain to be used.<br>     * @param array&lt;int&gt; $validResponseCodes The HTTP response codes to be considered valid.<br>     * @param string $dictionaryPath The path to the dictionary file.<br>     * @param string|null $logfile The path to the log file. If not specified, the date and time will be used to name the file.<br>     * @param string|null $logPath the path to the folder where the log file will be stored.<br>     */<br>    public function __construct(string $domain, array $validResponseCodes, string $dictionaryPath, ?string $logfile = null, ?string $logPath = null)<br>    {<br>        $this-&gt;domain = $domain;<br>        $this-&gt;validResponseCodes = $validResponseCodes;<br>        $this-&gt;dictionaryManager = new DictionaryManager($dictionaryPath);<br>        $this-&gt;logger = new Logger($logfile, $logPath);<br>    }<br><br>    /**<br>     * Scans the dictionary file and returns a list of valid URLs.<br>     *<br>     * @return array&lt;string&gt; A list of valid URLs.<br>     */<br>    public function scan(): void<br>    {<br>        while (($line = $this-&gt;dictionaryManager-&gt;ReadLine()) !== null) {<br>            $url = $this-&gt;domain . &#39;/&#39; . trim($line);<br>            $this-&gt;isUrlValid($url);<br>        }<br>    }<br><br>    /**<br>     * Checks whether a given URL is valid by sending a HEAD request and verifying the HTTP response code.<br>     *<br>     * @param string $url The URL to be checked for validity.<br>     */<br>    private function isUrlValid(string $url): void<br>    {<br>        $ch = curl_init($url);<br>        curl_setopt($ch, CURLOPT_NOBODY, true);<br>        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);<br>        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);<br>        curl_exec($ch);<br><br>        $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);<br>        curl_close($ch);<br><br>        $valid = false;<br>        if (in_array($responseCode, $this-&gt;validResponseCodes)) {<br>            $valid = true;<br>            $this-&gt;logger-&gt;log(&quot;Response code for URL $url: $responseCode &quot; . ($valid ? &quot;ACTIVE&quot; : &quot;INACTIVE&quot;));<br>        }<br>    }<br>}</pre><p>Now let’s go to our application entry point.</p><h4>fuzzer.php</h4><p>Our fuzzer.php file is in charge of interacting with the user and receiving the command line arguments needed to perform the scan.</p><p>It also validates that the required parameters are present and starts the process as shown below:</p><pre>&lt;?php<br><br>/**<br> * Web resource fuzzing for finding non-documented resources.<br> *<br> * The script uses a dictionary of words and domain names to<br> * build web addresses and check if they exist.<br> *<br> * Usage:<br> *    php fuzzer.php &lt;domain&gt; &lt;valid response codes&gt; &lt;dictionary path&gt; [&lt;log file path&gt;] [&lt;log directory path&gt;]<br> *<br> * Example:<br> *    php fuzzer.php example.com 200,301,302,403 /path/to/subdomains-top1million-5000.txt logfile.log /path/to/logs<br> */<br>require_once &#39;FuzzEngine.php&#39;;<br>require_once &#39;DictionaryManager.php&#39;;<br>require_once &#39;Logger.php&#39;;<br><br>// Get the command line arguments<br>$domain = $argv[1];<br>$validResponseCodes = explode(&#39;,&#39;, $argv[2]);<br>$dictionaryPath = $argv[3];<br>$logfile = $argv[4] ?? null;<br>$logPath = $argv[5] ?? null;<br><br>// Validate the required arguments<br>if (empty($domain) || empty($validResponseCodes) || empty($dictionaryPath)) {<br>    echo &quot;Error: The following arguments are required:\n&quot;;<br>    echo &quot;  1. Domain to be used\n&quot;;<br>    echo &quot;  2. List of valid response codes separated by commas\n&quot;;<br>    echo &quot;  3. Path to the dictionary file\n&quot;;<br>    exit(1);<br>}<br><br>// Creates a new instance of the class<br>$fuzzer = new FuzzEngine($domain, $validResponseCodes, $dictionaryPath, $logfile, $logPath);<br><br>$fuzzer-&gt;scan();</pre><p>Now that we have all the components, we can run our fuzzer.</p><p>Start a command console, enter the directory where your files are located and execute the following command:</p><h4>Execution</h4><pre>/my/folder/&gt;php fuzzer.php http://mysite.com 200 /path/to/my/dictionary/subdomains-top1million-5000.txt</pre><p>Keep in mind that you need to change the paths shown in the example to the specific paths on your PC.</p><p>The execution should show something similar to this if it finds active URLs:</p><pre>2024-08-22 21:01:07 Response code for URL http://localhost/www: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/mail: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/ftp: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/localhost: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/webmail: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/smtp: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/webdisk: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/pop: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/cpanel: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/whm: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/ns1: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/ns2: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/autodiscover: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/autoconfig: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/ns: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/test: 200 ACTIVE<br>2024-08-22 21:01:07 Response code for URL http://localhost/m: 200 ACTIVE</pre><p>If you did not specify the name of the log file, or the directory where it should be saved, you will find a file created with the result of the scan in the root directory alongside the other files we created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*zS81mhSgYDJSg9WOA1w2-A.png" /></figure><p>And with this we end our story, now that you know how a web fuzzer works, use it wisely.</p><p>Remember that at <a href="https://winkhosting.com/"><strong>Winkhosting.com</strong></a> we are much more than hosting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5876b9826396" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulando peticiones Web con User-Agent personalizado usando PHP]]></title>
            <link>https://medium.com/winkhostinglatam/simulando-peticiones-web-con-user-agent-personalizado-usando-php-daf8e1cefdb3?source=rss-d00dafbb1ae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/daf8e1cefdb3</guid>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[sysadmin]]></category>
            <dc:creator><![CDATA[Camilo Herrera]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 20:39:43 GMT</pubDate>
            <atom:updated>2024-06-04T20:39:43.814Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ymXFQPcd99lbQClJ" /><figcaption>Photo by <a href="https://unsplash.com/@fantasyflip?utm_source=medium&amp;utm_medium=referral">Philipp Katzenberger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Bienvenidos de nuevo a esta nueva entrega de contenido interesante para todo público! (Para todo público con anteojos y alergias)</p><p>Hoy vamos a crear una herramienta para simular peticiones web usando un User-Agent personalizado. Nos servirá para los siguientes casos (los que consideré al crearla):</p><ul><li>Verificar el comportamiento de un sitio web al recibir una petición de cierto tipo de dispositivos, confirmar si realiza redirecciones, y el contenido HTML presentado.</li><li>Si tienes un WAF configurado en un sitio web, puedes confirmar si hay reglas de bloqueo o de restricción a cierto tipo de cadenas de User-Agent, esto puede ser de utilidad para mitigar algunos tipos de ataques o scan de vulnerabilidades conocidas.</li><li>También si aplicaste reglas en un archivo .htaccess asociados a la cadena de User-Agent en un sitio web, puedes probarlas usando esta herramienta.</li></ul><p>Bueno ahora vamos a lo importante, nuestra solución. Si vienes leyendo mis publicaciones, notarás que sigo generalmente el mismo patrón y estructura para este tipo de pequeñas herramientas porque soy muy ecológico y me gusta reusar, reducir y reciclar código ;).</p><p>Ya con eso fuera del camino, vamos a proponer la estructura y requisitos de nuestra solución:</p><h4><strong>Requisitos</strong></h4><p>Como siempre vamos a usar un entorno de desarrollo con las siguientes herramientas:</p><ul><li><strong>Apache 2.4.x </strong>Nuestro viejo y conocido servidor web</li><li><strong>PHP 8.3</strong> (Puede funcionar sin problemas con PHP 8.2 y 8.1 solo es necesario hacer pruebas, yo lo hice con 8.3 y 8.2)</li><li><strong>Extensión cURL </strong>activa y configurada con soporte para conexiones SSL (Esto es muy importante para sitios <strong>https</strong>, de lo contrario tendrás errores)</li><li><strong>Bulma CSS</strong>, esta es la librería de GUI que utilizo normalmente, puedes visitarlos en <a href="https://bulma.io/">https://bulma.io</a></li><li>Tu editor de código favorito (<strong>VS Code</strong> en mi caso)</li><li><strong>Highlight.js</strong>, encontré esta librería al intentar aplicar resaltado de sintaxis al código HTML devuelto en la petición que realizaremos, bastante práctica, la usaremos para darle un toque de elegancia a la información mostrada, puedes visitarlos en <a href="https://highlightjs.org/"><strong>https://highlightjs.org/</strong></a></li><li>Paciencia, dedicación, ganas de aprender y <strong>50 flexiones de pecho diarias</strong>.</li></ul><p>Ya cubiertos los requisitos vamos a ver como será la estructura de nuestros archivos a usar:</p><h4>Estructura de archivos</h4><p>Los archivos que usaremos serán los siguientes:</p><ul><li><strong>Headersim.php:</strong> Archivo que contiene la clase encargada de la lógica y funciones para hacer las consultas con un User-Agent personalizado y procesar el contenido recibido desde un sitio web.</li><li><strong>index.html:</strong> Nuestra interfaz gráfica será mostrada en este archivo, también será el encargado de enviar la petición al backend con el nombre del host a consultar y el texto del User-Agent a usar.</li><li><strong>requestmananer.php:</strong> Un viejo conocido de otras publicaciones, este archivo recibirá la petición realizada desde <strong>index.html</strong>, instanciará la clase <strong>Headersim</strong> y retornará el resultado en formato JSON</li><li><strong>testbench.php: </strong>Este pequeño amigo será usado para hacer pruebas sin interfaz web, no es necesario, pero te puede servir en otras soluciones o para depurar rutinas sin un navegador.</li></ul><p>Crea un directorio que sea visible a través de tu servidor web y en él crea los archivos, en mi caso llamé el directorio “<strong>headersim</strong>” y su contenido quedará así:</p><pre>/headersim/<br>│   Headersim.php<br>│   index.html<br>│   requestmanager.php<br>│   testbench.php</pre><p>Ahora vamos a ir, uno a uno, recorriendo nuestros archivos para entender su contenido y utilidad.</p><h4>Headersim.php</h4><p>Nuestra alma, el motor de nuestra solución, el cantante principal, nuestro MVP… bueno esa es la idea, es el encargado de realizar las operaciones más importantes.</p><p>Esta clase cuenta con los siguientes atributos:</p><ul><li><strong>$result:</strong> es un arreglo encargado de almacenar los resultados de la consulta realizada, en este caso contendrá los elementos <strong>“headers”, “body”, “siteTitle”, “host”, “userAgent” y “httpCode”.</strong> Creo que los nombres son bastante claros, es decir que, después de realizar una petición, <strong>$result</strong> almacenará, las cabeceras, cuerpo, título, host, User-Agent y código HTTP devueltos por el sitio consultado.</li><li><strong>$headers:</strong> Es una cadena de texto que contendrá, como su nombre lo indica…, las cabeceras retornadas por el sitio consultado y tienen (generalmente) la siguiente estructura:</li></ul><pre>HTTP/1.1 200 OK<br>Date: Wed, 29 May 2024 16:21:30 GMT<br>Server: Apache<br>Vary: Accept-Encoding<br>Content-Length: 3483<br>Content-Type: text/html; charset=UTF-8</pre><ul><li><strong>$body:</strong> Esta cadena de texto contendrá la respuesta en HTML del sitio web, esto ayudará a determinar si al cambiar el User-Agent el HTML retornado cambia, por ejemplo.</li><li><strong>$httpCode:</strong> Esta cadena de texto contendrá el código HTTP devuelto, normalmente si todo sale bien será un 200 (OK) pero si ocurre algún error, se verá reflejado en el cambio en este código.</li><li><strong>$siteTitle:</strong> Contendrá el título del sitio (si lo tiene) extraído del <strong>$body</strong> y será la cadena entre los tags “<strong><em>&lt;title&gt;&lt;/title&gt;</em></strong>”</li><li><strong>$host:</strong> Guarda el host/IP al que se realiza la petición, viene del formulario en <strong>index.html</strong></li><li><strong>$userAgent:</strong> Guarda el User-Agent a usar en la petición y también viene del formulario en <strong>index.html</strong></li></ul><p>Ahora los métodos dentro de la clase:</p><ul><li><strong>__construct():</strong> El constructor de nuestra clase, aquí definimos los valores por defecto de nuestros atributos.</li><li><strong>sendRequest():</strong> Este método es el encargado de ejecutar la consulta a un sitio web, recibe dos parámetros <strong>$host</strong> y <strong>$userAgent</strong>. El <strong>$host</strong> es la dirección o IP del sitio a consultar y <strong>$userAgent</strong> es la cadena de User-Agent a usar.</li><li><strong>getHeaders():</strong> Esta función recibe los mismos parámetros que <strong>sendRequest()</strong> pero realiza la petición específica de los headers del sitio web consultado.</li><li><strong>getBody():</strong> También recibe los mismos parámetros que <strong>sendRequest()</strong> pero retorna el cuerpo de la respuesta, es decir el HTML devuelto por el sitio al ser consultado.</li><li><strong>extractSiteTitle():</strong> Esta función extrae el título del sitio web del HTML devuelto por <strong>getBody()</strong>, lo extrae usando una expresión regular para capturar el texto entre los tags “<strong><em>&lt;title&gt;&lt;/title&gt;</em></strong>”.</li></ul><p>Y es todo, ahora veamos como queda el archivo implementado en PHP</p><pre>&lt;?php<br><br>/**<br> * Clase Headersim<br> *<br> * Esta clase es responsable de enviar solicitudes HTTP a un host dado,<br> * recuperar encabezados y contenido del cuerpo, y extraer el título del sitio.<br> */<br>class Headersim<br>{<br>    /**<br>     * @var array $result Array para almacenar los resultados de la solicitud HTTP.<br>     */<br>    private array $result;<br><br>    /**<br>     * @var string $headers Cadena para almacenar los encabezados de la respuesta HTTP.<br>     */<br>    private string $headers;<br><br>    /**<br>     * @var string $body Cadena para almacenar el cuerpo de la respuesta HTTP.<br>     */<br>    private string $body;<br><br>    /**<br>     * @var string $httpCode Cadena para almacenar el código de respuesta HTTP.<br>     */<br>    private string $httpCode;<br><br>    /**<br>     * @var string $siteTitle Cadena para almacenar el título del sitio extraído.<br>     */<br>    private string $siteTitle;<br><br>    /**<br>     * @var string $host Cadena para almacenar el host de la solicitud HTTP.<br>     */<br>    private string $host;<br><br>    /**<br>     * @var string $userAgent Cadena para almacenar el User-Agent de la solicitud HTTP.<br>     */<br>    private string $userAgent;<br><br>    /**<br>     * Constructor de Headersim.<br>     * Inicializa las propiedades de la clase.<br>     */<br>    public function __construct()<br>    {<br>        $this-&gt;result = array();<br>        $this-&gt;headers = &quot;&quot;;<br>        $this-&gt;body = &quot;&quot;;<br>        $this-&gt;httpCode = &quot;&quot;;<br>        $this-&gt;siteTitle = &quot;&quot;;<br>        $this-&gt;host = &quot;&quot;;<br>        $this-&gt;userAgent = &quot;&quot;;<br>    }<br><br>    /**<br>     * Envía una solicitud HTTP al host especificado con el User-Agent dado.<br>     *<br>     * @param string $host El host al que enviar la solicitud.<br>     * @param string $userAgent La cadena User-Agent a usar para la solicitud.<br>     * @return array El resultado de la solicitud HTTP, incluyendo encabezados, cuerpo, título del sitio, host, User-Agent y código HTTP.<br>     */<br>    public function sendRequest(string $host, string $userAgent): array<br>    {<br>        $this-&gt;host = $host;<br>        $this-&gt;userAgent = $userAgent;<br><br>        $this-&gt;result[&quot;headers&quot;] = $this-&gt;getHeaders($host, $userAgent);<br>        $this-&gt;result[&quot;body&quot;] =  $this-&gt;getBody($host, $userAgent);<br>        $this-&gt;result[&quot;siteTitle&quot;] =   $this-&gt;extractSiteTitle($this-&gt;body);<br>        $this-&gt;result[&quot;host&quot;] = $this-&gt;host;<br>        $this-&gt;result[&quot;userAgent&quot;] = $this-&gt;userAgent;<br>        $this-&gt;result[&quot;httpCode&quot;] = $this-&gt;httpCode;<br><br>        return $this-&gt;result;<br>    }<br><br>    /**<br>     * Recupera los encabezados de la respuesta HTTP del host especificado.<br>     *<br>     * @param string $host El host al que enviar la solicitud.<br>     * @param string $userAgent La cadena User-Agent a usar para la solicitud.<br>     * @return string Los encabezados de la respuesta HTTP.<br>     */<br>    public function getHeaders(string $host, string $userAgent): string<br>    {<br>        $curl = curl_init();<br><br>        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);<br>        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);<br>        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);<br>        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);<br>        curl_setopt($curl, CURLOPT_HEADER, true);<br>        curl_setopt($curl, CURLOPT_NOBODY, true);<br>        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);<br>        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, &quot;GET&quot;);<br>        curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);<br>        curl_setopt($curl, CURLOPT_URL, $host);<br><br>        $this-&gt;headers = curl_exec($curl);<br>        $this-&gt;httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);<br>        curl_close($curl);<br><br>        return $this-&gt;headers;<br>    }<br><br>    /**<br>     * Recupera el cuerpo de la respuesta HTTP del host especificado.<br>     *<br>     * @param string $host El host al que enviar la solicitud.<br>     * @param string $userAgent La cadena User-Agent a usar para la solicitud.<br>     * @return string El cuerpo de la respuesta HTTP.<br>     */<br>    public function getBody(string $host, string $userAgent): string<br>    {<br>        $curl = curl_init();<br><br>        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);<br>        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);<br>        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);<br>        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);<br>        curl_setopt($curl, CURLOPT_HEADER, 0);<br>        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);<br>        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, &quot;GET&quot;);<br>        curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);<br>        curl_setopt($curl, CURLOPT_URL, $host);<br><br>        $this-&gt;body = curl_exec($curl);<br>        $this-&gt;httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);<br>        curl_close($curl);<br><br>        return $this-&gt;body;<br>    }<br><br>    /**<br>     * Extrae el título del sitio del cuerpo de la respuesta HTTP.<br>     *<br>     * @param string $body El cuerpo de la respuesta HTTP.<br>     * @return string El título del sitio extraído.<br>     */<br>    private function extractSiteTitle(string $body): string<br>    {<br>        $this-&gt;siteTitle = &quot;NOT FOUND&quot;;<br><br>        $arrMatches = array();<br>        preg_match(&quot;/\&lt;title\&gt;.*\&lt;\/title\&gt;/&quot;, $body, $arrMatches, PREG_OFFSET_CAPTURE);<br><br>        if (!empty($arrMatches)) {<br>            if (isset($arrMatches[0])) {<br>                if (isset($arrMatches[0][0])) {<br>                    $this-&gt;siteTitle = strip_tags($arrMatches[0][0]);<br>                }<br>            }<br>        }<br><br>        return $this-&gt;siteTitle;<br>    }<br>}</pre><h4>index.html</h4><p>Este archivo contiene nuestra interfaz de usuario, en resumen captura los parámetros de la consulta en dos campos de tipo texto, “<strong>host</strong>” y “<strong>userAgent</strong>”, este último es de tipo textarea. También le permite al usuario dar clic sobre el botón “<strong>Send Request</strong>” y este se encarga de enviar la información al archivo <strong>requestmanager.php</strong> a través de una petición POST.</p><p>El resultado de la consulta es retornado al archivo y mostrado en los controles dentro del código HTML, la interfaz lucirá así:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*IkN0BV3nSBLyhujA2A7-9w.png" /></figure><p>Ahora veamos el contenido del archivo. En él también notarás que incluimos la librería <strong>highlight.js </strong>para resaltar la sintaxis del código HTML retornado en la respuesta y nuestro querido <strong>Bulma CSS</strong>.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br><br>&lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>    &lt;title&gt;User-Agent Simulator&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css&quot;&gt;<br><br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css&quot;&gt;<br>    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js&quot;&gt;&lt;/script&gt;<br><br><br>    &lt;script type=&quot;module&quot;&gt;<br>        window.addEventListener(&#39;load&#39;, (event) =&gt; {<br><br>            document.querySelector(&quot;.sendRequest&quot;).addEventListener(&#39;click&#39;, (event) =&gt; {<br><br>                event.currentTarget.classList.add(&#39;is-loading&#39;);<br>                event.currentTarget.disabled = true;<br><br>                document.querySelector(&quot;.result&quot;).parentElement.classList.add(&quot;is-hidden&quot;);<br>                document.querySelector(&quot;.error&quot;).parentElement.classList.add(&quot;is-hidden&quot;);<br><br>                const payload = JSON.stringify({<br>                    &quot;host&quot;: document.querySelector(&quot;.host&quot;).value,<br>                    &quot;userAgent&quot;: document.querySelector(&quot;.userAgent&quot;).value<br>                });<br><br>                fetch(&#39;requestmanager.php&#39;, {<br>                    method: &#39;POST&#39;,<br>                    headers: {<br>                        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>                    },<br>                    body: payload,<br>                })<br>                    .then(response =&gt; response.json())<br>                    .then(data =&gt; {<br><br>                        document.querySelector(&quot;.result&quot;).parentElement.classList.remove(&quot;is-hidden&quot;);<br><br>                        console.log(data)<br>                        console.log(data.headers)<br>                        console.log(data.body)<br><br>                        document.querySelector(&quot;.headers&quot;).innerText = data.headers;<br>                        document.querySelector(&quot;.siteTitle&quot;).innerText = data.siteTitle;<br>                        document.querySelector(&quot;.resHost&quot;).innerText = data.host;<br>                        document.querySelector(&quot;.resUserAgent&quot;).innerText = data.userAgent;<br>                        document.querySelector(&quot;.httpCode&quot;).innerText = data.httpCode;<br>                        document.querySelector(&quot;.body&quot;).textContent = data.body;<br>                        document.querySelector(&quot;.body&quot;).removeAttribute(&quot;data-highlighted&quot;);<br><br>                        hljs.highlightAll();<br><br>                    })<br>                    .catch((error) =&gt; {<br>                        document.querySelector(&quot;.error&quot;).parentElement.classList.remove(&quot;is-hidden&quot;);<br>                        document.querySelector(&quot;.error&quot;).innerText = error;<br>                        console.error(&#39;Error:&#39;, error);<br>                    }).finally(() =&gt; {<br>                        document.querySelector(&quot;.sendRequest&quot;).classList.remove(&#39;is-loading&#39;);<br>                        document.querySelector(&quot;.sendRequest&quot;).disabled = false;<br>                    });<br>            });<br><br>        });<br>    &lt;/script&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>    &lt;section class=&quot;section&quot;&gt;<br>        &lt;div class=&quot;columns&quot;&gt;<br>            &lt;div class=&quot;column&quot;&gt;<br>                &lt;div class=&quot;field&quot;&gt;<br>                    &lt;label class=&quot;label&quot;&gt;Host&lt;/label&gt;<br>                    &lt;div class=&quot;control&quot;&gt;<br>                        &lt;input class=&quot;input host&quot; type=&quot;text&quot; placeholder=&quot;Hostname/IP&quot;&gt;<br>                    &lt;/div&gt;<br>                    &lt;p class=&quot;help&quot;&gt;Type the hostname/IP&lt;/p&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;field&quot;&gt;<br>                    &lt;label class=&quot;label&quot;&gt;User-Agent&lt;/label&gt;<br>                    &lt;div class=&quot;control&quot;&gt;<br>                        &lt;textarea class=&quot;textarea userAgent&quot; placeholder=&quot;User-Agent string&quot;&gt;&lt;/textarea&gt;<br>                    &lt;/div&gt;<br>                    &lt;p class=&quot;help&quot;&gt;Type the User-Agent string that you want to use for the request and click the Send<br>                        Request button&lt;/p&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;field&quot;&gt;<br>                    &lt;p class=&quot;control&quot;&gt;<br>                        &lt;button class=&quot;button is-black sendRequest&quot;&gt;<br>                            Send Request<br>                        &lt;/button&gt;<br>                    &lt;/p&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;columns  is-hidden&quot;&gt;<br>            &lt;div class=&quot;column result&quot;&gt;<br>                &lt;div class=&quot;columns&quot;&gt;<br>                    &lt;div class=&quot;column&quot;&gt;<br><br>                        &lt;article class=&quot;message&quot;&gt;<br>                            &lt;div class=&quot;message-header&quot;&gt;<br>                                &lt;p&gt;HTTP Response Code&lt;/p&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;message-body&quot;&gt;<br>                                &lt;div class=&quot;columns&quot;&gt;<br>                                    &lt;div class=&quot;column httpCode&quot;&gt;<br><br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/article&gt;<br><br>                        &lt;article class=&quot;message&quot;&gt;<br>                            &lt;div class=&quot;message-header&quot;&gt;<br>                                &lt;p&gt;Host&lt;/p&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;message-body&quot;&gt;<br>                                &lt;div class=&quot;columns&quot;&gt;<br>                                    &lt;div class=&quot;column resHost&quot;&gt;<br><br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/article&gt;<br><br>                        &lt;article class=&quot;message&quot;&gt;<br>                            &lt;div class=&quot;message-header&quot;&gt;<br>                                &lt;p&gt;Site Title&lt;/p&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;message-body&quot;&gt;<br>                                &lt;div class=&quot;columns&quot;&gt;<br>                                    &lt;div class=&quot;column siteTitle&quot;&gt;<br><br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/article&gt;<br><br>                        &lt;article class=&quot;message&quot;&gt;<br>                            &lt;div class=&quot;message-header&quot;&gt;<br>                                &lt;p&gt;User-Agent&lt;/p&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;message-body&quot;&gt;<br>                                &lt;div class=&quot;columns&quot;&gt;<br>                                    &lt;div class=&quot;column resUserAgent&quot;&gt;<br><br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/article&gt;<br><br>                        &lt;article class=&quot;message&quot;&gt;<br>                            &lt;div class=&quot;message-header&quot;&gt;<br>                                &lt;p&gt;Headers&lt;/p&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;message-body&quot;&gt;<br>                                &lt;div class=&quot;columns&quot;&gt;<br>                                    &lt;div class=&quot;column headers&quot;&gt;<br><br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/article&gt;<br><br>                        &lt;article class=&quot;message&quot;&gt;<br>                            &lt;div class=&quot;message-header&quot;&gt;<br>                                &lt;p&gt;Body HTML&lt;/p&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;message-body&quot;&gt;<br>                                &lt;div class=&quot;columns&quot;&gt;<br>                                    &lt;div class=&quot;column&quot;&gt;<br>                                        &lt;pre&gt;<br>                                            &lt;code style=&quot;min-width: 100%; width: 0px; overflow: auto;&quot; class=&quot;language-html body&quot;&gt;&lt;/code&gt;<br>                                        &lt;/pre&gt;<br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/article&gt;<br><br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br><br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;columns&quot;&gt;<br>            &lt;div class=&quot;column is-hidden&quot;&gt;<br>                &lt;div class=&quot;notification is-danger error has-text-centered&quot;&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/section&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><p>Continuemos con el siguiente archivo, requestmanager.php.</p><h4>requestmanager.php</h4><p>Este archivo es el intermediario entre nuestra clase <strong>Headersim </strong>y las peticiones que provienen de la interfaz en <strong>index.html</strong></p><p>Su funcionamiento es bastante simple, incluye el archivo <strong>Headersim.php</strong> decodifica los parámetros recibidos en la petición POST desde <strong>index.html</strong>, ejecuta la función <strong>sendRequest() </strong>del objeto y para finalizar captura la respuesta recibida y la retorna en formato <strong>JSON </strong>para ser mostrada en <strong>index.html</strong></p><p>El contenido del archivo a continuación:</p><pre>&lt;?php<br><br>//Se incluye la definición de la clase a usar para nuestra consulta.<br>require(&quot;Headersim.php&quot;);<br><br>//Decodificamos los parámetros recibidos desde el archivo index.html y los almacenamos en el arreglo $paramsFetch<br>$paramsFetch = json_decode(<br>    file_get_contents(&quot;php://input&quot;),<br>    true<br>);<br><br>//instanciamos nuestra clase<br>$headerSim = new Headersim();<br><br>//Enviamos el nombre del host y User-Agent a usar en la petición<br>$result = $headerSim-&gt;sendRequest($paramsFetch[&quot;host&quot;], $paramsFetch[&quot;userAgent&quot;]);<br><br>//A continuación retornamos la respuesta en formato JSON y finalizamos la ejecución.<br>$jsonResponse = json_encode($result);<br>echo $jsonResponse;<br>exit;</pre><p>Y para finalizar hablemos del archivo testbench.php.</p><p><strong>testbench.php</strong></p><p>Este archivo es de utilidad para hacer pruebas de tu código antes de tener una interfaz web lista o si quieres ejecutar código en un proceso de depuración usando solo la línea de comandos en tu PC.</p><p>Su contenido es similar al mostrado en <strong>requestmanager.php </strong>pero no recibimos parámetros a través de POST dado que es usado desde línea de comandos, simplemente se escriben los valores literales para los parámetros en las funciones ejecutadas así:</p><pre>&lt;?php<br><br>//Se incluye la definición de la clase a usar para nuestra consulta.<br>require(&quot;Headersim.php&quot;);<br><br>//instanciamos nuestra clase<br>$headerSim = new Headersim();<br><br>//Ejecutamos la consulta<br>$result = $headerSim-&gt;sendRequest(&quot;https://winkhosting.co&quot;, &quot;Googlebot/2.1 (+http://www.googlebot.com/bot.html)&quot;);<br><br>//Mostramos el contenido de la respuesta<br>print_r($result);</pre><p>Ahora, si todo sale bien y copiaste el código correctamente, puedes hacer consultas simulando un User-Agent ingresando al URL donde se encuentran tus archivos, en mi caso <a href="http://localhost/headersim/index.html"><strong>http://localhost/headersim/index.html</strong></a></p><p>Y es todo, no olvides que en<strong> </strong><a href="https://winkhosting.co/"><strong>winkhosting.co</strong></a> somos mucho más que Hosting!</p><p><strong>P.D.</strong> No olvides las 50 flexiones de pecho!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daf8e1cefdb3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/winkhostinglatam/simulando-peticiones-web-con-user-agent-personalizado-usando-php-daf8e1cefdb3">Simulando peticiones Web con User-Agent personalizado usando PHP</a> was originally published in <a href="https://medium.com/winkhostinglatam">winkhostingla</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulating Web requests with custom User-Agent using PHP]]></title>
            <link>https://medium.com/winkhosting/simulating-web-requests-with-custom-user-agent-using-php-11dc705bba4c?source=rss-d00dafbb1ae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/11dc705bba4c</guid>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[sysadmin]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[simulation]]></category>
            <dc:creator><![CDATA[Camilo Herrera]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 20:36:07 GMT</pubDate>
            <atom:updated>2024-06-04T20:36:07.489Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8arHDp3pjY64rtEI" /><figcaption>Photo by <a href="https://unsplash.com/@fantasyflip?utm_source=medium&amp;utm_medium=referral">Philipp Katzenberger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome back to this new installment of interesting content for everyone! (For everyone with glasses and allergies mainly).</p><p>Today we are going to create a tool to simulate web requests using a custom User-Agent. It will be useful for the following cases (the ones I considered when creating it):</p><ul><li>Verify the behavior of a website when receiving a request from certain types of devices, confirm if it performs redirects, and check the HTML content presented.</li><li>If you have a WAF configured on a website, you can confirm if there are blocking or restriction rules for certain types of User-Agent strings. This can be useful to mitigate some types of attacks or scans for known vulnerabilities.</li><li>Additionally, if you applied rules in a .htaccess file associated with the User-Agent string on a website, you can test them using this tool.</li></ul><p>Alright, now let’s get to the important part, our solution. If you’ve been reading my posts, you’ll notice that I generally follow the same pattern and structure for this type of small tools because I’m very eco-friendly and I like to reuse, reduce, and recycle code ;).</p><p>With that out of the way, let’s propose the structure and requirements for our solution:</p><h4>Requirements</h4><p>As always, we will use a development environment with the following tools:</p><ul><li><strong>Apache 2.4.x</strong>: Our old and well-known web server</li><li><strong>PHP 8.3</strong>: It can work without problems with PHP 8.2 and 8.1, you just need to test it. I tested it with 8.3 and 8.2</li><li><strong>cURL extension</strong>: Enabled and configured with support for SSL connections (This is very important for HTTPS sites, otherwise you will encounter errors)</li><li><strong>Bulma CSS</strong>: This is the GUI library I usually use, you can visit them at <a href="https://bulma.io/">Bulma CSS</a></li><li>Your favorite code editor: (<strong>VS Code</strong> in my case)</li><li><strong>Highlight.js</strong>: I found this library when trying to apply syntax highlighting to the HTML code returned in the request response. It’s quite handy and we will use it to give a touch of elegance to the displayed information. You can visit them at <a href="https://highlightjs.org/"><strong>Highlight.js</strong></a></li><li>Patience, dedication, willingness to learn,<strong> and 50 push-ups daily</strong></li></ul><p>Now that we have covered the requirements, let’s look at the structure of the files we will use:</p><h4>File Structure</h4><p>The files we will use are as follows:</p><ul><li><strong>Headersim.php</strong>: This file contains the class responsible for the logic and functions to make requests with a custom User-Agent and process the content received from a website.</li><li><strong>index.html</strong>: Our graphical interface will be displayed in this file. It will also be responsible for sending the request to the backend with the name of the host to query and the User-Agent text to use.</li><li><strong>requestmanager.php</strong>: An old acquaintance from other posts, this file will receive the request made from <strong>index.html</strong>, instantiate the <strong>Headersim </strong>class, and return the result in JSON format.</li><li><strong>testbench.php</strong>: This little friend will be used to perform tests without a web interface. It is not necessary, but it can be useful in other solutions or to debug and execute code without a browser.</li></ul><p>Create a directory that is visible through your web server, and in it create the files. In my case, I named the directory “<strong>headersim</strong>” and its content will be as follows:</p><pre>/headersim/<br>│   Headersim.php<br>│   index.html<br>│   requestmanager.php<br>│   testbench.php</pre><p>Now we’re moving, one by one, through our files to understand their content and utility.</p><h4>Headersim.php</h4><p>Our soul, the engine of our solution, the lead singer, our MVP… well, that’s the idea, it’s responsible for performing the most important operations.</p><p>This class has the following attributes:</p><ul><li><strong>$result</strong>: It is an array responsible for storing the results of the performed query. In this case, it will contain the elements <strong>“headers”, “body”, “siteTitle”, “host”, “userAgent”, and “httpCode”.</strong> I think the names are quite clear, meaning that after making a request, <strong>$result</strong> will store the headers, body, title, host, User-Agent, and HTTP code returned by the queried site.</li><li><strong>$headers</strong>: It is a string that will contain, as its name indicates, the headers returned by the queried site and generally have the following structure:</li></ul><pre>HTTP/1.1 200 OK<br>Date: Wed, 29 May 2024 16:21:30 GMT<br>Server: Apache<br>Vary: Accept-Encoding<br>Content-Length: 3483<br>Content-Type: text/html; charset=UTF-8</pre><ul><li><strong>$body:</strong> This string will contain the HTML response from the website. This will help determine if changing the User-Agent results in a different HTML response, for example.</li><li><strong>$httpCode:</strong> This string will contain the returned HTTP code. Typically, if everything goes well, it will be 200 (OK), but any errors will be reflected in this code.</li><li><strong>$siteTitle:</strong> It will contain the title of the website (if it has one), extracted from <strong>$body</strong>, and will be the string between the “<strong><em>&lt;title&gt;&lt;/title&gt;</em></strong>” tags.</li><li><strong>$host:</strong> Stores the host/IP to which the request is made, coming from the form in <strong>index.html</strong>.</li><li><strong>$userAgent:</strong> Stores the User-Agent to be used in the request, also coming from the form in <strong>index.html</strong>.</li></ul><p>Now, the methods within the class:</p><ul><li><strong>__construct()</strong>: The constructor of our class. Here we define the default values of our attributes.</li><li><strong>sendRequest()</strong>: This method is responsible for executing the request to a website. It receives two parameters: <strong>$host</strong> and <strong>$userAgent</strong>. <strong>$host</strong> is the address or IP of the site to be queried, and <strong>$userAgent</strong> is the User-Agent string to be used.</li><li><strong>getHeaders()</strong>: This function receives the same parameters as <strong>sendRequest() </strong>but specifically requests the headers of the queried website.</li><li><strong>getBody()</strong>: It also receives the same parameters as <strong>sendRequest()</strong> but returns the body of the response, i.e., the HTML returned by the site when queried.</li><li><strong>extractSiteTitle()</strong>: This function extracts the title of the website from the HTML returned by <strong>getBody()</strong>. It does this using a regular expression to capture the text between the “<strong><em>&lt;title&gt;&lt;/title&gt;</em></strong>” tags.</li></ul><p>And that’s it! Now let’s see how the PHP file looks when implemented.</p><pre>&lt;?php<br><br>/**<br> * Class Headersim<br> *<br> * This class is responsible for sending HTTP requests to a given host,<br> * retrieving headers and body content, and extracting the site title.<br> */<br>class Headersim<br>{<br>    /**<br>     * @var array $result Array to store the results of the HTTP request.<br>     */<br>    private array $result;<br><br>    /**<br>     * @var string $headers String to store the headers of the HTTP response.<br>     */<br>    private string $headers;<br><br>    /**<br>     * @var string $body String to store the body of the HTTP response.<br>     */<br>    private string $body;<br><br>    /**<br>     * @var string $httpCode String to store the HTTP response code.<br>     */<br>    private string $httpCode;<br><br>    /**<br>     * @var string $siteTitle String to store the extracted site title.<br>     */<br>    private string $siteTitle;<br><br>    /**<br>     * @var string $host String to store the host for the HTTP request.<br>     */<br>    private string $host;<br><br>    /**<br>     * @var string $userAgent String to store the User-Agent for the HTTP request.<br>     */<br>    private string $userAgent;<br><br>    /**<br>     * Headersim constructor.<br>     * Initializes the class properties.<br>     */<br>    public function __construct()<br>    {<br>        $this-&gt;result = array();<br>        $this-&gt;headers = &quot;&quot;;<br>        $this-&gt;body = &quot;&quot;;<br>        $this-&gt;httpCode = &quot;&quot;;<br>        $this-&gt;siteTitle = &quot;&quot;;<br>        $this-&gt;host = &quot;&quot;;<br>        $this-&gt;userAgent = &quot;&quot;;<br>    }<br><br>    /**<br>     * Sends an HTTP request to the specified host with the given User-Agent.<br>     *<br>     * @param string $host The host to send the request to.<br>     * @param string $userAgent The User-Agent string to use for the request.<br>     * @return array The result of the HTTP request, including headers, body, site title, host, User-Agent, and HTTP code.<br>     */<br>    public function sendRequest(string $host, string $userAgent): array<br>    {<br>        $this-&gt;host = $host;<br>        $this-&gt;userAgent = $userAgent;<br><br>        $this-&gt;result[&quot;headers&quot;] = $this-&gt;getHeaders($host, $userAgent);<br>        $this-&gt;result[&quot;body&quot;] =  $this-&gt;getBody($host, $userAgent);<br>        $this-&gt;result[&quot;siteTitle&quot;] =   $this-&gt;extractSiteTitle($this-&gt;body);<br>        $this-&gt;result[&quot;host&quot;] = $this-&gt;host;<br>        $this-&gt;result[&quot;userAgent&quot;] = $this-&gt;userAgent;<br>        $this-&gt;result[&quot;httpCode&quot;] = $this-&gt;httpCode;<br><br>        return $this-&gt;result;<br>    }<br><br>    /**<br>     * Retrieves the headers of the HTTP response from the specified host.<br>     *<br>     * @param string $host The host to send the request to.<br>     * @param string $userAgent The User-Agent string to use for the request.<br>     * @return string The headers of the HTTP response.<br>     */<br>    public function getHeaders(string $host, string $userAgent): string<br>    {<br>        $curl = curl_init();<br><br>        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);<br>        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);<br>        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);<br>        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);<br>        curl_setopt($curl, CURLOPT_HEADER, true);<br>        curl_setopt($curl, CURLOPT_NOBODY, true);<br>        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);<br>        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, &quot;GET&quot;);<br>        curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);<br>        curl_setopt($curl, CURLOPT_URL, $host);<br><br>        $this-&gt;headers = curl_exec($curl);<br>        $this-&gt;httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);<br>        curl_close($curl);<br><br>        return $this-&gt;headers;<br>    }<br><br>    /**<br>     * Retrieves the body of the HTTP response from the specified host.<br>     *<br>     * @param string $host The host to send the request to.<br>     * @param string $userAgent The User-Agent string to use for the request.<br>     * @return string The body of the HTTP response.<br>     */<br>    public function getBody(string $host, string $userAgent): string<br>    {<br>        $curl = curl_init();<br><br>        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);<br>        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);<br>        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);<br>        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);<br>        curl_setopt($curl, CURLOPT_HEADER, 0);<br>        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);<br>        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, &quot;GET&quot;);<br>        curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);<br>        curl_setopt($curl, CURLOPT_URL, $host);<br><br>        $this-&gt;body = curl_exec($curl);<br>        $this-&gt;httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);<br>        curl_close($curl);<br><br>        return $this-&gt;body;<br>    }<br><br>    /**<br>     * Extracts the site title from the body of the HTTP response.<br>     *<br>     * @param string $body The body of the HTTP response.<br>     * @return string The extracted site title.<br>     */<br>    private function extractSiteTitle(string $body): string<br>    {<br>        $this-&gt;siteTitle = &quot;NOT FOUND&quot;;<br><br>        $arrMatches = array();<br>        preg_match(&quot;/\&lt;title\&gt;.*\&lt;\/title\&gt;/&quot;, $body, $arrMatches, PREG_OFFSET_CAPTURE);<br><br>        if (!empty($arrMatches)) {<br>            if (isset($arrMatches[0])) {<br>                if (isset($arrMatches[0][0])) {<br>                    $this-&gt;siteTitle = strip_tags($arrMatches[0][0]);<br>                }<br>            }<br>        }<br><br>        return $this-&gt;siteTitle;<br>    }<br>}</pre><h4>index.html</h4><p>This file contains our user interface. In summary, it captures the parameters of the query in two text fields, “<strong>host</strong>” and “<strong>userAgent</strong>”, the latter being a textarea. It also allows the user to click on the “<strong>Send Request</strong>” button, which sends the information to the <strong>requestmanager.php</strong> file via a POST request.</p><p>The result of the query is returned to the file and displayed in the controls within the HTML code. The interface will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*Z89ujeH-Fa-ddOPQeEQuIw.png" /></figure><p>Now let’s see the content of the file. You’ll also notice that we included the highlight.js library to highlight the syntax of the HTML code returned in the response and our beloved <strong>bulma CSS</strong>.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br><br>&lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>    &lt;title&gt;User-Agent Simulator&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css&quot;&gt;<br><br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css&quot;&gt;<br>    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js&quot;&gt;&lt;/script&gt;<br><br><br>    &lt;script type=&quot;module&quot;&gt;<br>        window.addEventListener(&#39;load&#39;, (event) =&gt; {<br><br>            document.querySelector(&quot;.sendRequest&quot;).addEventListener(&#39;click&#39;, (event) =&gt; {<br><br>                event.currentTarget.classList.add(&#39;is-loading&#39;);<br>                event.currentTarget.disabled = true;<br><br>                document.querySelector(&quot;.result&quot;).parentElement.classList.add(&quot;is-hidden&quot;);<br>                document.querySelector(&quot;.error&quot;).parentElement.classList.add(&quot;is-hidden&quot;);<br><br>                const payload = JSON.stringify({<br>                    &quot;host&quot;: document.querySelector(&quot;.host&quot;).value,<br>                    &quot;userAgent&quot;: document.querySelector(&quot;.userAgent&quot;).value<br>                });<br><br>                fetch(&#39;requestmanager.php&#39;, {<br>                    method: &#39;POST&#39;,<br>                    headers: {<br>                        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>                    },<br>                    body: payload,<br>                })<br>                    .then(response =&gt; response.json())<br>                    .then(data =&gt; {<br><br>                        document.querySelector(&quot;.result&quot;).parentElement.classList.remove(&quot;is-hidden&quot;);<br><br>                        console.log(data)<br>                        console.log(data.headers)<br>                        console.log(data.body)<br><br>                        document.querySelector(&quot;.headers&quot;).innerText = data.headers;<br>                        document.querySelector(&quot;.siteTitle&quot;).innerText = data.siteTitle;<br>                        document.querySelector(&quot;.resHost&quot;).innerText = data.host;<br>                        document.querySelector(&quot;.resUserAgent&quot;).innerText = data.userAgent;<br>                        document.querySelector(&quot;.httpCode&quot;).innerText = data.httpCode;<br>                        document.querySelector(&quot;.body&quot;).textContent = data.body;<br>                        document.querySelector(&quot;.body&quot;).removeAttribute(&quot;data-highlighted&quot;);<br><br>                        hljs.highlightAll();<br><br>                    })<br>                    .catch((error) =&gt; {<br>                        document.querySelector(&quot;.error&quot;).parentElement.classList.remove(&quot;is-hidden&quot;);<br>                        document.querySelector(&quot;.error&quot;).innerText = error;<br>                        console.error(&#39;Error:&#39;, error);<br>                    }).finally(() =&gt; {<br>                        document.querySelector(&quot;.sendRequest&quot;).classList.remove(&#39;is-loading&#39;);<br>                        document.querySelector(&quot;.sendRequest&quot;).disabled = false;<br>                    });<br>            });<br><br>        });<br>    &lt;/script&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>    &lt;section class=&quot;section&quot;&gt;<br>        &lt;div class=&quot;columns&quot;&gt;<br>            &lt;div class=&quot;column&quot;&gt;<br>                &lt;div class=&quot;field&quot;&gt;<br>                    &lt;label class=&quot;label&quot;&gt;Host&lt;/label&gt;<br>                    &lt;div class=&quot;control&quot;&gt;<br>                        &lt;input class=&quot;input host&quot; type=&quot;text&quot; placeholder=&quot;Hostname/IP&quot;&gt;<br>                    &lt;/div&gt;<br>                    &lt;p class=&quot;help&quot;&gt;Type the hostname/IP&lt;/p&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;field&quot;&gt;<br>                    &lt;label class=&quot;label&quot;&gt;User-Agent&lt;/label&gt;<br>                    &lt;div class=&quot;control&quot;&gt;<br>                        &lt;textarea class=&quot;textarea userAgent&quot; placeholder=&quot;User-Agent string&quot;&gt;&lt;/textarea&gt;<br>                    &lt;/div&gt;<br>                    &lt;p class=&quot;help&quot;&gt;Type the User-Agent string that you want to use for the request and click the Send<br>                        Request button&lt;/p&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;field&quot;&gt;<br>                    &lt;p class=&quot;control&quot;&gt;<br>                        &lt;button class=&quot;button is-black sendRequest&quot;&gt;<br>                            Send Request<br>                        &lt;/button&gt;<br>                    &lt;/p&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;columns  is-hidden&quot;&gt;<br>            &lt;div class=&quot;column result&quot;&gt;<br>                &lt;div class=&quot;columns&quot;&gt;<br>                    &lt;div class=&quot;column&quot;&gt;<br><br>                        &lt;article class=&quot;message&quot;&gt;<br>                            &lt;div class=&quot;message-header&quot;&gt;<br>                                &lt;p&gt;HTTP Response Code&lt;/p&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;message-body&quot;&gt;<br>                                &lt;div class=&quot;columns&quot;&gt;<br>                                    &lt;div class=&quot;column httpCode&quot;&gt;<br><br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/article&gt;<br><br>                        &lt;article class=&quot;message&quot;&gt;<br>                            &lt;div class=&quot;message-header&quot;&gt;<br>                                &lt;p&gt;Host&lt;/p&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;message-body&quot;&gt;<br>                                &lt;div class=&quot;columns&quot;&gt;<br>                                    &lt;div class=&quot;column resHost&quot;&gt;<br><br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/article&gt;<br><br>                        &lt;article class=&quot;message&quot;&gt;<br>                            &lt;div class=&quot;message-header&quot;&gt;<br>                                &lt;p&gt;Site Title&lt;/p&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;message-body&quot;&gt;<br>                                &lt;div class=&quot;columns&quot;&gt;<br>                                    &lt;div class=&quot;column siteTitle&quot;&gt;<br><br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/article&gt;<br><br>                        &lt;article class=&quot;message&quot;&gt;<br>                            &lt;div class=&quot;message-header&quot;&gt;<br>                                &lt;p&gt;User-Agent&lt;/p&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;message-body&quot;&gt;<br>                                &lt;div class=&quot;columns&quot;&gt;<br>                                    &lt;div class=&quot;column resUserAgent&quot;&gt;<br><br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/article&gt;<br><br>                        &lt;article class=&quot;message&quot;&gt;<br>                            &lt;div class=&quot;message-header&quot;&gt;<br>                                &lt;p&gt;Headers&lt;/p&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;message-body&quot;&gt;<br>                                &lt;div class=&quot;columns&quot;&gt;<br>                                    &lt;div class=&quot;column headers&quot;&gt;<br><br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/article&gt;<br><br>                        &lt;article class=&quot;message&quot;&gt;<br>                            &lt;div class=&quot;message-header&quot;&gt;<br>                                &lt;p&gt;Body HTML&lt;/p&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;message-body&quot;&gt;<br>                                &lt;div class=&quot;columns&quot;&gt;<br>                                    &lt;div class=&quot;column&quot;&gt;<br>                                        &lt;pre&gt;<br>                                            &lt;code style=&quot;min-width: 100%; width: 0px; overflow: auto;&quot; class=&quot;language-html body&quot;&gt;&lt;/code&gt;<br>                                        &lt;/pre&gt;<br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/article&gt;<br><br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br><br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;columns&quot;&gt;<br>            &lt;div class=&quot;column is-hidden&quot;&gt;<br>                &lt;div class=&quot;notification is-danger error has-text-centered&quot;&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/section&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><p>Let’s continue with the next file, requestmanager.php.</p><h4>requestmanager.php</h4><p>This file serves as the intermediary between our <strong>Headersim </strong>class and the requests coming from the interface in <strong>index.html</strong>.</p><p>Its operation is quite simple: it includes the <strong>Headersim.php</strong> file, decodes the parameters received in the POST request from<strong> index.html</strong>, executes the <strong>sendRequest()</strong> function of the object, and finally captures the received response and returns it in JSON format to be displayed in <strong>index.html</strong>.</p><p>Here’s the content of the file:</p><pre>&lt;?php<br><br>// Includes the class definition to be used for our request.<br>require(&quot;Headersim.php&quot;);<br><br>// Decodes the parameters received from the index.html file and stores them in the $paramsFetch array.<br>$paramsFetch = json_decode(<br>    file_get_contents(&quot;php://input&quot;),<br>    true<br>);<br><br>// Instantiates our class.<br>$headerSim = new Headersim();<br><br>// Sends the host name and User-Agent to be used in the request.<br>$result = $headerSim-&gt;sendRequest($paramsFetch[&quot;host&quot;], $paramsFetch[&quot;userAgent&quot;]);<br><br>// Returns the response in JSON format and ends the execution.<br>$jsonResponse = json_encode($result);<br>echo $jsonResponse;<br>exit;</pre><p>And finally, let’s talk about the file testbench.php.</p><h4>testbench.php</h4><p>This file is useful for testing your code before having a fully functional web interface, or if you want to execute code during a debugging process using only the command line on your PC.</p><p>Its content is similar to that shown in <strong>requestmanager.php</strong>, but we do not receive parameters via POST since it is used from the command line. Instead, literal values for the parameters are simply written like this:</p><pre>&lt;?php<br><br>// Includes the class definition to be used for our request.<br>require(&quot;Headersim.php&quot;);<br><br>// Instantiates our class.<br>$headerSim = new Headersim();<br><br>// Executes the request.<br>$result = $headerSim-&gt;sendRequest(&quot;https://winkhosting.co&quot;, &quot;Googlebot/2.1 (+http://www.googlebot.com/bot.html)&quot;);<br><br>// Displays the response content.<br>print_r($result);</pre><p>Now, if everything goes well and you copied the code correctly, you can perform queries simulating a User-Agent by accessing the URL where your files are located, in my case <a href="http://localhost/headersim/index.html"><strong>http://localhost/headersim/index.html</strong></a><strong>.</strong></p><p>And that’s it! Don’t forget that at <a href="https://winkhosting.com/"><strong>winkhosting.com</strong></a> we are much more than Hosting!</p><p><strong>P.S. Don’t forget the 50 push-ups!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11dc705bba4c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/winkhosting/simulating-web-requests-with-custom-user-agent-using-php-11dc705bba4c">Simulating Web requests with custom User-Agent using PHP</a> was originally published in <a href="https://medium.com/winkhosting">winkhosting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detección de escaneo de vulnerabilidades web con PHP y Apache mod_status]]></title>
            <link>https://medium.com/winkhostinglatam/detecci%C3%B3n-de-escaneo-de-vulnerabilidades-web-con-php-y-apache-mod-status-83d28aeeb4ab?source=rss-d00dafbb1ae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/83d28aeeb4ab</guid>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Camilo Herrera]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 21:17:17 GMT</pubDate>
            <atom:updated>2024-04-25T21:17:17.485Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K73BCEl5w_rZUNLF" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hola!, ha pasado algún tiempo, pero estamos de vuelta. Hoy hablaremos sobre un tópico asociado a la mitigación de ataques a tus sitios web, si eres un administrador de servidores ó administras tu propio servidor para alojar tu página web, espero que sea de ayuda.</p><p>Durante los últimos meses he venido notando algunos picos de carga en nuestros servidores, al investigar la causa encontré un patrón en ellos, los infames y muy usados escáneres de vulnerabilidades web.</p><blockquote>Si no estás familiarizado con el concepto, este tipo de herramientas cuentan con diccionarios de URLs o nombres de scripts con vulnerabilidades conocidas o archivos que un administrador descuidado puede dejar visibles desde Internet a un atacante y, al ser encontrados, son reportados para futuros ataques a través de vectores ya conocidos.</blockquote><p>Ahora, puedes contar con un WAF y Firewall que son de mucha ayuda pero no llegan a ser muy efectivos para peticiones sencillas en las que se intenta descubrir si existe o no una URL o un script en un sitio web (con fines maliciosos) y allí es donde se requiere algo adicional.</p><h4><strong>La solución</strong></h4><p>Dado que no contaba con un mecanismo para detener este tipo de comportamiento en el que son realizadas grandes cantidades de peticiones a múltiples sitios web desde diferentes IPs tratando de “adivinar” URLs vulnerables, empecé a plantearme algún tipo de script que me ayudara monitorear, bloquear y dejar registro de este tipo de actividades mitigando posibles picos de carga en mis amados servidores.</p><p>Lo que necesito es lo siguiente:</p><ul><li>Consultar las peticiones realizadas al servidor web de forma constante</li><li>Analizar cada URL en las peticiones a partir de reglas asociadas al contenido (texto) en el URL o cantidad de peticiones realizadas por una misma IP.</li><li>Realizar una o más acciones a partir de la información encontrada, en este caso bloquear la IP en nuestro firewall.</li></ul><p>Vamos a explorar los requisitos a continuación.</p><h4>Requisitos</h4><ul><li>Apache HTTP Server</li><li>mod_status activado en Apache HTTP Server</li><li>PHP 8.3 cli. Si, vamos a usar PHP en modo consola para esta guía.</li><li>Firewall (opcional), en este caso usaremos ufw en Linux Mint 21.2</li></ul><h4>Apache HTTP Server</h4><p>Verifica si tienes instalado Apache en tu PC o en el entorno en el que vas a realizar tus pruebas. En mi caso estoy usando Linux Mint 21.2, si no lo tienes instalado, puedes hacerlo usando el siguiente comando (en mi versión de Linux, consulta tu versión de sistema operativo para ejecutar el comando correcto):</p><pre>sudo apt install apache2</pre><p>Puedes consultar la guía de instalación para versiones basadas en Ubuntu en el siguiente enlace:</p><p><a href="https://ubuntu.com/server/docs/how-to-install-apache2">How to install Apache2 | Ubuntu</a></p><p>Una vez instalado verifica que se encuentre en ejecución, puedes ingresar con tu navegador a <a href="http://localhost/">http://localhost/</a> y debería ser mostrado un mensaje de bienvenida de Apache HTTP Server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fEDVdXRZSBZjg601TyCI_g.png" /><figcaption>Apache localhost</figcaption></figure><blockquote>Si no se encuentra en ejecución no olvides iniciar el servicio. Generalmente puedes hacerlo ejecutando <strong>sudo systemctl start apache2</strong></blockquote><h4>mod_status</h4><p>El segundo paso para avanzar es tener una fuente de información en la que pueda consultar constantemente las peticiones realizadas a mi servidor web, y allí es donde <a href="https://httpd.apache.org/docs/2.4/mod/mod_status.html"><strong>mod_status</strong> </a>se vuelve útil.</p><p><strong>mod_status </strong>es un módulo de Apache HTTP Server que le permite a un administrador consultar en cualquier momento su estado y las peticiones siendo atendidas en ese instante.</p><p>Puedes consultar la información sobre <strong>mod_status </strong>en el siguiente enlace:</p><p><a href="https://httpd.apache.org/docs/2.4/mod/mod_status.html">mod_status - Apache HTTP Server Version 2.4</a></p><p>Vamos a verificar si está activo el módulo en nuestro servidor web, esto puedes hacerlo ejecutando el siguiente comando:</p><pre>apachectl -M</pre><p>Una vez ejecutado será mostrada la lista de módulos cargados en el servidor web, allí puedes confirmar si se encuentra “<strong>status_module (shared)</strong>”, si es así, se encuentra activo. También puedes confirmarlo ingresando a <a href="http://localhost/server-status"><strong>http://localhost/server-status</strong></a></p><p>Deberías visualizar algo similar a esto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlTjLV83o3QPFs5kpiyezA.png" /></figure><p>En caso tal que no encuentres el módulo, puedes cargarlo usando el comando a2enmod así:</p><pre>sudo a2enmod status</pre><blockquote><strong>IMPORTANTE:</strong> Si vas a activar mod_status en un entorno de producción, asegura que solo sea visible desde las IPs y Dominios autorizados, normalmente se permite el acceso únicamente a peticiones que provengan de localhost, pero es algo que recomiendo tener presente.</blockquote><h4>PHP 8.3 cli</h4><p>Verifica que tengas instalado PHP en tu PC, el código fuente de los scripts es compatible con PHP 8.x si tienes una versión previa puede que no requieras cambios y funcione normalmente.</p><p>Puedes verificar la versión y si tienes <strong>PHP </strong>en modo <strong>cli </strong>ejecutando el comando a continuación:</p><pre>php -v</pre><h4>Firewall</h4><p>El firewall en tu PC es opcional, pero la idea general del script es ejecutar un comando para enviar al firewall la IP de origen de la petición y bloquear el acceso. En este caso usaremos <strong>ufw</strong>, puedes conocer más sobre este firewall para Ubuntu en el siguiente enlace:</p><p><a href="https://ubuntu.com/server/docs/firewalls">Firewalls | Ubuntu</a></p><p>Y estos son los requisitos, vamos a la solución!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U0yuxpnH51_Yq4I3" /><figcaption>Photo by <a href="https://unsplash.com/@flysi3000?utm_source=medium&amp;utm_medium=referral">Simon Abrams</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Crea un directorio para guardar los archivos que vamos a usar, la estructura será la siguiente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*lEDxn-m-Vh0v26H4SecdAw.png" /><figcaption>Archivos</figcaption></figure><p>Ahora veamos la función de cada archivo, vamos a empezar con nuestro motor de detección.</p><h4>Scanengine.php</h4><p>Este archivo contiene dos funciones, la primera “<strong><em>getApacheStatus()</em></strong>”permite consultar y procesar la respuesta de <strong>mod_status </strong>usando <strong>cURL </strong>y la librería de procesamiento de HTML <strong>DomDocument</strong>. Aquí hacemos un poco de scraping buscamos un tag que identifique la tabla en la que se encuentran las peticiones y extraemos los registros en texto plano dentro de un arreglo.</p><blockquote><strong>IMPORTANTE:</strong> no olvides activar estos módulos en caso tal que tu instalación de PHP no los tenga por defecto.</blockquote><p>La segunda función es “<strong><em>checkRequests()</em></strong>” y es la encargada de tomar las peticiones encontradas y procesarlas usando las reglas y acciones predefinidas en el constructor de la clase “<strong>$scanRules</strong>” y “<strong>$scanActions</strong>”</p><p>A continuación el código fuente:</p><pre>&lt;?php<br><br>/**<br> * Clase Scanengine<br> * <br> * Una clase para escanear el estado del servidor Apache y aplicar reglas.<br> */<br>class Scanengine<br>{<br>    /** @var array $currApacheRequests Un array para almacenar las solicitudes actuales al servidor Apache. */<br>    private array $currApacheRequests;<br><br>    /** @var string $apacheURL La URL de la página de estado del servidor Apache. */<br>    private string $apacheURL;<br><br>    /** @var array $scanRules Un array que contiene las reglas de escaneo. */<br>    private array $scanRules;<br><br>    /** @var array $scanActions Un array que contiene las acciones a tomar basadas en los resultados del escaneo. */<br>    private array $scanActions;<br><br>    /**<br>     * Constructor de Scanengine.<br>     * Inicializa las propiedades de la clase y establece los valores predeterminados.<br>     */<br>    public function __construct()<br>    {<br>        $this-&gt;currApacheRequests = array();<br>        $this-&gt;apacheURL = &quot;http://localhost/server-status&quot;;<br><br>        $this-&gt;scanRules = array(<br>            &quot;scripts&quot; =&gt; function (array $currApacheRequests): void {<br>                echo PHP_EOL . &quot;-- Análisis usando diccionario de cadenas de texto --&quot; . PHP_EOL;<br><br>                // Carga la lista de términos y palabras a buscar en las URLs para el escaneo de peticiones sospechosas<br>                $scriptDictionary = file(&quot;scripts.txt&quot;, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);<br><br>                if (!is_array($scriptDictionary)) {<br>                    echo &quot;Hubo un error al leer scripts.txt, verifica si el archivo existe dentro de la carpeta raíz.&quot; . PHP_EOL;<br>                    return;<br>                }<br><br>                $hits = 0;<br><br>                foreach ($scriptDictionary as $id =&gt; $script) {<br>                    foreach ($currApacheRequests as $reqId =&gt; $request) {<br>                        if (str_contains($request[&quot;Request&quot;], $script)) {<br>                            echo PHP_EOL . &quot;Coincidencia encontrada para el script sospechoso &#39;{$script}&#39; en la solicitud &#39;{$request[&quot;Request&quot;]}&#39; desde la IP {$request[&quot;Client&quot;]}&quot; . PHP_EOL;<br><br>                            $this-&gt;scanActions[&quot;firewallBlock&quot;]($request[&quot;Client&quot;]);<br>                            $hits++;<br>                        }<br>                    }<br>                }<br><br>                echo PHP_EOL . &quot;Encontré {$hits} hit(s) en las peticiones analizadas.&quot; . PHP_EOL;<br>            },<br>            &quot;IPHits&quot; =&gt; function (array $currApacheRequests): void {<br><br>                // Escaneo de hits de IP<br>                $maxHits = 3;<br>                $IPHits = array();<br><br>                echo PHP_EOL . &quot;-- Análisis de cantidad de hits por IP, Máximo {$maxHits} hit(s) --&quot; . PHP_EOL;<br><br>                foreach ($currApacheRequests as $reqId =&gt; $request) {<br>                    if (!isset($IPHits[$request[&quot;Client&quot;]])) {<br>                        $IPHits[$request[&quot;Client&quot;]] = 1;<br>                    } else {<br>                        $IPHits[$request[&quot;Client&quot;]]++;<br>                    }<br>                }<br><br>                $hits = 0;<br><br>                foreach ($IPHits as $ip =&gt; $hitsCount) {<br>                    if ($hitsCount &gt; $maxHits) {<br>                        echo PHP_EOL . &quot;Número de hits permitidos superado ({$maxHits}) desde la IP {$ip}&quot; . PHP_EOL;<br>                        $this-&gt;scanActions[&quot;firewallBlock&quot;]($ip);<br>                        $hits++;<br>                    }<br>                }<br><br>                echo PHP_EOL . &quot;Encontré {$hits} hit(s) en las peticiones analizadas.&quot; . PHP_EOL;<br>            }<br>        );<br><br>        $this-&gt;scanActions = array(<br>            &quot;firewallBlock&quot; =&gt; function (string $clientIP): void {<br>                //No te golpees en la cara tu mismo.<br>                $arrIgnoreIps = array(&quot;127.0.0.1&quot;, &quot;::1&quot;);<br><br>                if (!in_array($clientIP, $arrIgnoreIps)) {<br>                    echo &quot;¡IP {$clientIP} agregada a la lista negra del firewall!&quot; . PHP_EOL;<br>                }<br>            }<br>        );<br>    }<br><br>    /**<br>     * Establece la URL del estado del servidor Apache.<br>     * <br>     * @param string $apacheURL La URL de la página de estado del servidor Apache.<br>     */<br>    public function setApacheURL(string $apacheURL): void<br>    {<br>        $this-&gt;apacheURL = $apacheURL;<br>    }<br><br>    /**<br>     * Recupera el estado del servidor Apache y analiza las solicitudes.<br>     * <br>     * @return void<br>     */<br>    public function getApacheStatus(): void<br>    {<br>        $url = $this-&gt;apacheURL;<br><br>        $curl = curl_init($url);<br>        curl_setopt($curl, CURLOPT_URL, $url);<br>        curl_setopt($curl, CURLOPT_HEADER, false);<br>        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);<br><br>        $response = curl_exec($curl);<br><br>        if ($response === false) {<br>            echo &#39;Error de Curl: &#39; . curl_error($curl) . PHP_EOL;<br>            exit;<br>        }<br><br>        curl_close($curl);<br><br>        $dom = new DomDocument();<br>        @$dom-&gt;loadHTML($response);<br><br>        $tables = $dom-&gt;getElementsByTagName(&#39;table&#39;);<br>        $foundRequests = false;<br><br>        foreach ($tables as $table) {<br>            foreach ($table-&gt;attributes as $attr) {<br>                if ($attr-&gt;name == &quot;border&quot; &amp;&amp; $attr-&gt;value == 0) {<br><br>                    echo &quot;Lista de solicitudes encontrada en {$this-&gt;apacheURL}&quot; . PHP_EOL;<br><br>                    $foundRequests = true;<br><br>                    $fieldHeaders = $table-&gt;getElementsByTagName(&#39;th&#39;);<br>                    $arrFieldKeys = array();<br><br>                    foreach ($fieldHeaders as $fieldHeader) {<br>                        $arrFieldKeys[] = $fieldHeader-&gt;nodeValue;<br>                    }<br><br>                    $requests = $table-&gt;getElementsByTagName(&#39;tr&#39;);<br><br>                    foreach ($requests as $req) {<br>                        $arrFields = array();<br>                        $fields = $req-&gt;getElementsByTagName(&#39;td&#39;);<br><br>                        if (count($fields) == 0) {<br>                            continue;<br>                        }<br><br>                        foreach ($arrFieldKeys as $key =&gt; $tag) {<br>                            $arrFields[$tag] = str_replace(&quot;\n&quot;, &quot;&quot;, $fields-&gt;item($key)-&gt;nodeValue);<br>                        }<br><br>                        if (!empty($arrFields)) {<br>                            $this-&gt;currApacheRequests[] = $arrFields;<br>                        }<br>                    }<br>                }<br>            }<br><br>            if ($foundRequests) {<br>                break;<br>            }<br>        }<br><br>        if (!$foundRequests) {<br>            echo &quot;Lista de solicitudes en {$this-&gt;apacheURL} no encontrada, ¿quizás una URL incorrecta?&quot; . PHP_EOL;<br>        }<br>    }<br><br>    /**<br>     * Ejecuta controles basados en reglas en las solicitudes del servidor Apache.<br>     * <br>     * @return void<br>     */<br>    public function checkRequests(): void<br>    {<br>        $this-&gt;scanRules[&quot;scripts&quot;]($this-&gt;currApacheRequests);<br>        $this-&gt;scanRules[&quot;IPHits&quot;]($this-&gt;currApacheRequests);<br>    }<br>}</pre><p>Como puedes ver en el arreglo de reglas de escaneo “<strong><em>$scanRules</em></strong>”, la finalidad de este arreglo es almacenar las rutinas que analizan las peticiones detectadas en el URL<strong> /server-status</strong>, puedes crear tantas como requieras. Para este artículo implementamos la regla de detección usando un diccionario de nombres de scripts/texto dentro de una URL y cantidad de hits simultáneos por IP de origen, que también puede indicar un escaneo malicioso a tu servidor.</p><p>En el arreglo de acciones “<strong><em>$scanActions</em></strong>” implementamos una acción que simula la ejecución de un bloqueo en el firewall del servidor a partir de lo encontrado por nuestras reglas de escaneo.</p><blockquote><strong>IMPORTANTE:</strong> Para realizar este tipo de acciones, como agregar una IP en la lista negra del servidor, tu script php generalmente debe ejecutarse como root o con un usuario que tenga permisos para esta operación, recuerda que ejecutar scripts o procesos con permisos root puede implicar riesgos.</blockquote><p>Si quieres agregar un llamado al firewall para bloquear la IP puedes hacerlo incluyendo una línea como esta en el cuerpo de la función “<strong><em>firewallBlock</em></strong>” en “<strong><em>$scanActions</em></strong>”:</p><pre>$this-&gt;scanActions = array(<br>    &quot;firewallBlock&quot; =&gt; function (string $clientIP): void {<br>        $result = shell_exec(&quot;ufw deny from {$clientIP} to any&quot;);<br>        echo $result.PHP_EOL;<br>        echo &quot;¡IP {$clientIP} agregada a la lista negra del firewall!&quot; . PHP_EOL;<br>    }<br>);</pre><p>Este es el corazón de nuestra solución, ahora que ya lo analizamos vamos a pasar a los dos archivos restantes, scripts.txt y apache-scan.php</p><h4>scripts.txt</h4><p>Este archivo almacena la lista de cadenas de texto usadas en ataques con diccionarios a nuestros sitios web, para este caso usaremos algunos términos como se muestran a continuación:</p><pre>admin.php<br>Exchange.asmx<br>phpMyAdmin<br>backup<br>phpmyadmin3<br>xx.php<br>backup.zip<br>dump.sql<br>config.php<br>.env.production<br>web.config<br>config.xml<br>config.yml<br>sql.sql.xz<br>backups.sql.zip<br>web.sql.zip<br>website.sql.zip<br>backup_4.sql.zip<br>fm1.php?x=zourt<br>www.sqlitedb<br>.git/HEADE</pre><p>Estas cadenas son cargadas al inicio de la ejecución de la regla “scripts” y cada término es buscado en el listado de peticiones para encontrar coincidencias.</p><blockquote><strong>IMPORTANTE:</strong> para gran cantidad de términos en un diccionario se debería considerar una estrategia de búsqueda más eficiente que la presentada aquí.</blockquote><h4>apache-scan.php</h4><p>Finalmente analicemos este archivo, en él se encuentra el punto de entrada de nuestra solución y es el encargado de crear una instancia de Scanengine y hacer el llamado a las funciones de nuestro motor de detección.</p><pre>&lt;?php<br>require(&quot;Scanengine.php&quot;);<br><br>$scan = new Scanengine();<br>$scanInterval = 5;<br><br>do {<br><br>    $scan-&gt;getApacheStatus();<br>    $scan-&gt;checkRequests();<br>    sleep($scanInterval);<br>} while (true);</pre><p>Como puedes ver, también cuenta con un ciclo que realiza la verificación y espera cierta cantidad de segundos, de esta forma se puede realizar continuamente la consulta de peticiones.</p><blockquote><strong>IMPORTANTE:</strong> esta solución no tiene una opción para verificar si ya aplicó un bloqueo a una IP y pueden presentarse escenarios donde intente realizar un bloqueo ya ejecutado si la petición a Apache sigue visible en mod_status.</blockquote><p>Ahora con nuestra solución lista, solo es necesario ejecutar apache-scan.php así:</p><pre>php &lt;ruta de tu script&gt;/apache-scan.php</pre><p>Si todo sale bien, debes visualizar mensajes como estos:</p><pre>Lista de solicitudes encontrada en http://localhost/server-status<br><br>-- Análisis usando diccionario de cadenas de texto --<br><br>Coincidencia encontrada para el script sospechoso &#39;gifLogo1.gif&#39; en la solicitud &#39;GET /classic/img/gifLogo1.gif HTTP/1.1&#39; desde la IP x.x.x.x<br>¡IP x.x.x.x agregada a la lista negra del firewall!<br><br>Encontré 1 hit(s) en las peticiones analizadas.<br><br>-- Análisis de cantidad de hits por IP, Máximo 3 hit(s) --<br><br>Número de hits permitidos superado (3) desde la IP x.x.x.x<br>¡IP x.x.x.x agregada a la lista negra del firewall!<br><br>Número de hits permitidos superado (3) desde la IP y.y.y.y<br>¡IP y.y.y.y agregada a la lista negra del firewall!<br><br>Encontré 2 hit(s) en las peticiones analizadas.<br></pre><p>Y es todo, recuerda que en <a href="https://winkhosting.co/"><strong>Winkhosting.co</strong></a> somos mucho más que hosting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83d28aeeb4ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/winkhostinglatam/detecci%C3%B3n-de-escaneo-de-vulnerabilidades-web-con-php-y-apache-mod-status-83d28aeeb4ab">Detección de escaneo de vulnerabilidades web con PHP y Apache mod_status</a> was originally published in <a href="https://medium.com/winkhostinglatam">winkhostingla</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detection of web vulnerability scanning with PHP and Apache mod_status.]]></title>
            <link>https://medium.com/winkhosting/detection-of-web-vulnerability-scanning-with-php-and-apache-mod-status-01aeb1395548?source=rss-d00dafbb1ae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/01aeb1395548</guid>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Camilo Herrera]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 21:14:08 GMT</pubDate>
            <atom:updated>2024-04-25T21:14:08.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MPy_GD9BH8_x_U8X" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello! It’s been a while, but we’re back. Today we will talk about a topic associated with mitigating attacks on your websites. If you are a server administrator or manage your own server to host your website, I hope it is helpful.</p><p>During the last few months I have been noticing some load spikes on our servers, when investigating the cause I found a pattern in them, the infamous and widely used web vulnerability scanners.</p><blockquote>If you are not familiar with the concept, these types of tools have dictionaries of URLs or names of scripts with known vulnerabilities or files that a careless administrator can leave visible from the Internet to an attacker and, when found, are reported for future attacks to through already known vectors.</blockquote><p>Now, you can have a WAF and Firewall that are very helpful but are not very effective for simple requests in which you try to discover whether or not a URL or script exists on a website (for malicious purposes) and there This is where something additional is required.</p><h4>The solution</h4><p>Since I did not have a mechanism to stop this type of behavior in which large amounts of requests are made to multiple websites from different IPs trying to “guess” vulnerable URLs, I began to consider some type of script that would help me monitor, block and leave a record of this type of activity, mitigating possible load peaks on my beloved servers.</p><p><strong>Functional requirements:</strong></p><ul><li>Query the requests made to the web server on a constant basis.</li><li>Analyze each URL in the requests from rules associated with the content (text) in the URL or number of requests made by the same IP.</li><li>Perform one or more actions from the information found, in this case block the IP in our firewall</li></ul><p>Let’s explore the technical requirements below.</p><h4><strong>Technical Requirements</strong></h4><ul><li>Apache HTTP Server</li><li>mod_status enabled on Apache HTTP Server</li><li>PHP 8.3 cli. Yes, we are going to use PHP in console mode for this guide.</li><li>Firewall (optional), in this case we will use ufw on Linux Mint 21.2</li></ul><h4>Apache HTTP Server</h4><p>Check if you have Apache installed on your PC or on the environment where you are going to perform your tests. In my case I am using Linux Mint 21.2, if you don’t have it installed, you can do it using the following command (in my version of Linux, check your OS version to run the correct command):</p><pre>sudo apt install apache2</pre><p>You can check the installation guide for Ubuntu based versions at the following link:</p><p><a href="https://ubuntu.com/server/docs/how-to-install-apache2">How to install Apache2 | Ubuntu</a></p><p>Once installed verify that it is running, you can access with your browser <a href="http://localhost/">http://localhost/</a> and you should be shown a welcome message from Apache HTTP Server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*hJeuWVJvLNPNSdO4mjJmWg.png" /><figcaption>Apache localhost</figcaption></figure><blockquote>If it is not running don’t forget to start the service. Generally you can do this by running<strong> sudo systemctl start apache2</strong></blockquote><h4>mod_status</h4><p>The second step to move forward is to have a source of information where I can constantly query the requests made to my web server, and that’s where <strong>mod_status </strong>comes in handy.</p><p>mod_status is an Apache HTTP Server module that allows an administrator to query at any time its status and the requests being served at that instant.</p><p>Information about mod_status can be found at the following link:</p><p><a href="https://httpd.apache.org/docs/2.4/mod/mod_status.html">mod_status - Apache HTTP Server Version 2.4</a></p><p>Let’s check if the module is active in our web server, this can be done by executing the following command:</p><pre>apachectl -M</pre><p>Once executed, the list of modules loaded in the web server will be shown, there you can confirm if “<strong>status_module (shared)</strong>” is found, if so, it is active. You can also confirm it by going to <a href="http://localhost/server-status"><strong>http://localhost/server-status</strong></a></p><p>You should see something similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*C68f7zTLbv-WUOCmLJMHxg.png" /></figure><p>In case you cannot find the module, you can load it using the a2enmod command like this:</p><pre>sudo a2enmod status</pre><blockquote><strong>IMPORTANT:</strong> If you are going to enable mod_status in a production environment, make sure that it is only visible from authorized IPs and domains, normally access is allowed only to requests coming from localhost, but it is something I advice to keep in mind.</blockquote><h4>PHP 8.3 cli</h4><p>Verify that you have PHP installed on your PC, the source code of the scripts is compatible with PHP 8.x. If you have a previous version you may not require changes and it will work as expected.</p><p>You can check if you have PHP in cli mode by running the command below:</p><pre>php -v</pre><h4>Firewall</h4><p>The firewall on your PC is optional, but the general idea of the script is to run a command to send to the firewall the source IP of the request and block it. In this case we will use ufw, you can learn more about this firewall for Ubuntu at the following link:</p><p><a href="https://ubuntu.com/server/docs/firewalls">Firewalls | Ubuntu</a></p><p>And these are the requirements, let’s get to the solution!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p2C55buTgTOC-NlS" /><figcaption>Photo by <a href="https://unsplash.com/@avirichards?utm_source=medium&amp;utm_medium=referral">Avi Richards</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Create a directory to store the files we are going to use, the structure will be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*to482ZGk9wInqu_DwxKxGA.png" /><figcaption>Files</figcaption></figure><p>Now let’s look at the function of each file, let’s start with our detection engine.</p><h4>Scanengine.php</h4><p>This file contains two functions, the first one “<strong><em>getApacheStatus</em></strong>()” allows to query and process the <strong>mod_status </strong>response using <strong>cURL </strong>and the HTML processing library <strong>DomDocument</strong>. Here we do some scraping, we look for a tag that identifies the table in which the requests are found and extract the records in plain text into an array.</p><blockquote><strong>IMPORTANT:</strong> do not forget to activate these modules in case your PHP installation does not have them by default.</blockquote><p>The second function is “<strong><em>checkRequests</em></strong>()” and is responsible for taking the requests found and processing them using the rules and actions predefined in the constructor of the class “$<strong>scanRules</strong>” and “$<strong>scanActions</strong>”.</p><p>Here is the source code:</p><pre>&lt;?php<br><br>/**<br> * Scanengine Class<br> * <br> * A class for scanning the state of the Apache server and applying rules.<br> */<br>class Scanengine<br>{<br>    /** @var array $currApacheRequests An array to store the current requests to the Apache server. */<br>    private array $currApacheRequests;<br><br>    /** @var string $apacheURL The URL of the Apache server status page. */<br>    private string $apacheURL;<br><br>    /** @var array $scanRules An array containing the scanning rules. */<br>    private array $scanRules;<br><br>    /** @var array $scanActions An array containing actions to take based on scan results. */<br>    private array $scanActions;<br><br>    /**<br>     * Scanengine constructor.<br>     * Initializes class properties and sets default values.<br>     */<br>    public function __construct()<br>    {<br>        $this-&gt;currApacheRequests = array();<br>        $this-&gt;apacheURL = &quot;http://localhost/server-status&quot;;<br><br>        $this-&gt;scanRules = array(<br>            &quot;scripts&quot; =&gt; function (array $currApacheRequests): void {<br>                echo PHP_EOL . &quot;-- Analysis using text string dictionary --&quot; . PHP_EOL;<br><br>                // Load the list of terms and words to search in URLs for scanning suspicious requests<br>                $scriptDictionary = file(&quot;scripts.txt&quot;, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);<br><br>                if (!is_array($scriptDictionary)) {<br>                    echo &quot;There was an error reading scripts.txt, please verify if the file exists in the root folder.&quot; . PHP_EOL;<br>                    return;<br>                }<br><br>                $hits = 0;<br><br>                foreach ($scriptDictionary as $id =&gt; $script) {<br>                    foreach ($currApacheRequests as $reqId =&gt; $request) {<br>                        if (str_contains($request[&quot;Request&quot;], $script)) {<br>                            echo PHP_EOL . &quot;Match found for suspicious script &#39;{$script}&#39; in request &#39;{$request[&quot;Request&quot;]}&#39; from IP {$request[&quot;Client&quot;]}&quot; . PHP_EOL;<br><br>                            $this-&gt;scanActions[&quot;firewallBlock&quot;]($request[&quot;Client&quot;]);<br>                            $hits++;<br>                        }<br>                    }<br>                }<br><br>                echo PHP_EOL . &quot;Found {$hits} hit(s) in the analyzed requests.&quot; . PHP_EOL;<br>            },<br>            &quot;IPHits&quot; =&gt; function (array $currApacheRequests): void {<br><br>                // IP hits scanning<br>                $maxHits = 3;<br>                $IPHits = array();<br><br>                echo PHP_EOL . &quot;-- Analysis of hit count per IP, Maximum {$maxHits} hit(s) --&quot; . PHP_EOL;<br><br>                foreach ($currApacheRequests as $reqId =&gt; $request) {<br>                    if (!isset($IPHits[$request[&quot;Client&quot;]])) {<br>                        $IPHits[$request[&quot;Client&quot;]] = 1;<br>                    } else {<br>                        $IPHits[$request[&quot;Client&quot;]]++;<br>                    }<br>                }<br><br>                $hits = 0;<br><br>                foreach ($IPHits as $ip =&gt; $hitsCount) {<br>                    if ($hitsCount &gt; $maxHits) {<br>                        echo PHP_EOL . &quot;Allowed hit count exceeded ({$maxHits}) from IP {$ip}&quot; . PHP_EOL;<br>                        $this-&gt;scanActions[&quot;firewallBlock&quot;]($ip);<br>                        $hits++;<br>                    }<br>                }<br><br>                echo PHP_EOL . &quot;Found {$hits} hit(s) in the analyzed requests.&quot; . PHP_EOL;<br>            }<br>        );<br><br>        $this-&gt;scanActions = array(<br>            &quot;firewallBlock&quot; =&gt; function (string $clientIP): void {<br>                // Don&#39;t shoot yourself in the foot.<br>                $arrIgnoreIps = array(&quot;127.0.0.1&quot;, &quot;::1&quot;);<br><br>                if (!in_array($clientIP, $arrIgnoreIps)) {<br>                    echo &quot;IP {$clientIP} added to firewall blacklist!&quot; . PHP_EOL;<br>                }<br>            }<br>        );<br>    }<br><br>    /**<br>     * Sets the URL of the Apache server status page.<br>     * <br>     * @param string $apacheURL The URL of the Apache server status page.<br>     */<br>    public function setApacheURL(string $apacheURL): void<br>    {<br>        $this-&gt;apacheURL = $apacheURL;<br>    }<br><br>    /**<br>     * Retrieves the state of the Apache server and analyzes requests.<br>     * <br>     * @return void<br>     */<br>    public function getApacheStatus(): void<br>    {<br>        $url = $this-&gt;apacheURL;<br><br>        $curl = curl_init($url);<br>        curl_setopt($curl, CURLOPT_URL, $url);<br>        curl_setopt($curl, CURLOPT_HEADER, false);<br>        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);<br><br>        $response = curl_exec($curl);<br><br>        if ($response === false) {<br>            echo &#39;Curl Error: &#39; . curl_error($curl) . PHP_EOL;<br>            exit;<br>        }<br><br>        curl_close($curl);<br><br>        $dom = new DomDocument();<br>        @$dom-&gt;loadHTML($response);<br><br>        $tables = $dom-&gt;getElementsByTagName(&#39;table&#39;);<br>        $foundRequests = false;<br><br>        foreach ($tables as $table) {<br>            foreach ($table-&gt;attributes as $attr) {<br>                if ($attr-&gt;name == &quot;border&quot; &amp;&amp; $attr-&gt;value == 0) {<br><br>                    echo &quot;List of requests found at {$this-&gt;apacheURL}&quot; . PHP_EOL;<br><br>                    $foundRequests = true;<br><br>                    $fieldHeaders = $table-&gt;getElementsByTagName(&#39;th&#39;);<br>                    $arrFieldKeys = array();<br><br>                    foreach ($fieldHeaders as $fieldHeader) {<br>                        $arrFieldKeys[] = $fieldHeader-&gt;nodeValue;<br>                    }<br><br>                    $requests = $table-&gt;getElementsByTagName(&#39;tr&#39;);<br><br>                    foreach ($requests as $req) {<br>                        $arrFields = array();<br>                        $fields = $req-&gt;getElementsByTagName(&#39;td&#39;);<br><br>                        if (count($fields) == 0) {<br>                            continue;<br>                        }<br><br>                        foreach ($arrFieldKeys as $key =&gt; $tag) {<br>                            $arrFields[$tag] = str_replace(&quot;\n&quot;, &quot;&quot;, $fields-&gt;item($key)-&gt;nodeValue);<br>                        }<br><br>                        if (!empty($arrFields)) {<br>                            $this-&gt;currApacheRequests[] = $arrFields;<br>                        }<br>                    }<br>                }<br>            }<br><br>            if ($foundRequests) {<br>                break;<br>            }<br>        }<br><br>        if (!$foundRequests) {<br>            echo &quot;List of requests at {$this-&gt;apacheURL} not found, perhaps an incorrect URL?&quot; . PHP_EOL;<br>        }<br>    }<br><br>    /**<br>     * Executes rule-based checks on Apache server requests.<br>     * <br>     * @return void<br>     */<br>    public function checkRequests(): void<br>    {<br>        $this-&gt;scanRules[&quot;scripts&quot;]($this-&gt;currApacheRequests);<br>        $this-&gt;scanRules[&quot;IPHits&quot;]($this-&gt;currApacheRequests);<br>    }<br>}</pre><p>As you can see in the scan rules array “$<strong>scanRules</strong>”, the purpose of this array is to store the routines that analyze the detected requests in the URL <strong>/server-status</strong>, you can create as many as you need. For this article we implemented the detection rule using a dictionary of script/text names within a URL and number of simultaneous hits per source IP, which can also indicate a malicious scan to your server.</p><p>In the “$<strong>scanActions</strong>” array we implement an action that simulates the execution of a block on the server’s firewall based on what is found by our scanning rules.</p><blockquote><strong>IMPORTANT: </strong>To perform this type of actions, such as adding an IP in the server blacklist, your php script generally must be executed as root or with a user that has permissions for this operation, remember that executing scripts or processes with root permissions can be risky.</blockquote><p>If you want to add a call to the firewall to block the IP you can do it by including a line like this in the body of the “<strong>firewallBlock</strong>” function in “$<strong>scanActions</strong>”:</p><pre>$this-&gt;scanActions = array(<br>    &quot;firewallBlock&quot; =&gt; function (string $clientIP): void {<br>        $result = shell_exec(&quot;ufw deny from {$clientIP} to any&quot;);<br>        echo $result.PHP_EOL;<br>        echo &quot;IP {$clientIP} added to the firewall blacklist!&quot; . PHP_EOL;<br>    }<br>);</pre><p>This is the heart of our solution, now that we have analyzed it let’s move on to the two remaining files, scripts.txt and apache-scan.php</p><h4>scripts.txt</h4><p>This file stores the list of text strings used in dictionary attacks to our web sites, for this case we will use some terms as shown below:</p><pre>admin.php<br>Exchange.asmx<br>phpMyAdmin<br>backup<br>phpmyadmin3<br>xx.php<br>backup.zip<br>dump.sql<br>config.php<br>.env.production<br>web.config<br>config.xml<br>config.yml<br>sql.sql.xz<br>backups.sql.zip<br>web.sql.zip<br>website.sql.zip<br>backup_4.sql.zip<br>fm1.php?x=zourt<br>www.sqlitedb<br>.git/HEADE</pre><p>These strings are loaded at the beginning of the execution of the “scripts” rule and each term is searched in the request list for matches.</p><blockquote><strong>IMPORTANT:</strong> for a large number of terms in a dictionary, a more efficient search strategy than the one presented here should be considered.</blockquote><h4>apache-scan.php</h4><p>Finally, let’s analyze this file, which is the entry point of our solution and is responsible for creating an instance of <strong>Scanengine </strong>and calling the functions of our detection engine.</p><pre>&lt;?php<br>require(&quot;Scanengine.php&quot;);<br><br>$scan = new Scanengine();<br>$scanInterval = 5;<br><br>do {<br><br>    $scan-&gt;getApacheStatus();<br>    $scan-&gt;checkRequests();<br>    sleep($scanInterval);<br>} while (true);</pre><p>As you can see, it also has a cycle and waits for a certain number of seconds, so that the request scan can be performed continuously.</p><blockquote><strong>IMPORTANT:</strong> this solution does not have an option to check if you have already applied a block to an IP and there may be scenarios where you try to perform a block already executed if the request to Apache is still visible in mod_status.</blockquote><p>Now with our solution ready, we just need to run apache-scan.php like this:</p><pre>php &lt;script route&gt;/apache-scan.php</pre><p>If all goes well, you should see messages like these:</p><pre>List of requests found at http://localhost/server-status<br><br>-- Analysis using text string dictionary --<br><br>Match found for suspicious script &#39;gifLogo1.gif&#39; in request &#39;GET /classic/img/gifLogo1.gif HTTP/1.1&#39; from IP x.x.x.x<br>IP x.x.x.x added to the firewall blacklist!<br><br>Found 1 hit(s) in the analyzed requests.<br><br>-- Analysis of hit count per IP, Maximum 3 hit(s) --<br><br>Allowed hit count exceeded (3) from IP x.x.x.x<br>IP x.x.x.x added to the firewall blacklist!<br><br>Allowed hit count exceeded (3) from IP y.y.y.y<br>IP y.y.y.y added to the firewall blacklist!<br><br>Found 2 hit(s) in the analyzed requests.</pre><p>And that’s all, remember that in <a href="https://winkhosting.com/"><strong>Winkhosting.co</strong></a><strong>m </strong>we are much more than hosting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01aeb1395548" width="1" height="1" alt=""><hr><p><a href="https://medium.com/winkhosting/detection-of-web-vulnerability-scanning-with-php-and-apache-mod-status-01aeb1395548">Detection of web vulnerability scanning with PHP and Apache mod_status.</a> was originally published in <a href="https://medium.com/winkhosting">winkhosting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic route management with PHP and Apache httpd]]></title>
            <link>https://medium.com/winkhosting/basic-route-managament-with-php-and-apache-httpd-98f9126b1384?source=rss-d00dafbb1ae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/98f9126b1384</guid>
            <category><![CDATA[route-management]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[router]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Camilo Herrera]]></dc:creator>
            <pubDate>Thu, 08 Feb 2024 16:13:54 GMT</pubDate>
            <atom:updated>2024-02-24T12:58:52.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sBkV1neLGj0pJfOe" /><figcaption>Photo by <a href="https://unsplash.com/@martinirc?utm_source=medium&amp;utm_medium=referral">José Martín Ramírez Carrasco</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello! I hope you’re starting the year with lots of plans and tranquility. Remember that every day we exist is a blessing and we should make the most of it in the best possible way.</p><p>Today we are going to study a basic concept for managing a website or web software, which is handling routes. In this article, we will focus on managing routes using <a href="https://php.net/"><strong>PHP</strong></a><strong>, </strong><a href="https://httpd.apache.org/"><strong>Apache</strong></a><strong>, and </strong><a href="https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html"><strong>mod_rewrite</strong></a>.</p><p>Let’s explore how we do it in our company. Generally, our requirements are quite basic, and we don’t need frameworks or libraries with advanced functionalities for this type of tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lzc8-qYuNdeU7xlSUEbJ2g.png" /><figcaption>R.I.P my meme friend, you will always be remembered.</figcaption></figure><p>Let’s start as always with our requirements, and then we’ll begin the implementation and explanation of concepts applied to our solution.</p><h4><strong>Requirements</strong></h4><p>As in most of our publications, the following elements will be necessary:</p><ol><li>A local/remote development environment that includes PHP 8.2, Apache 2.4, and the active mod_rewrite module in Apache.</li><li>Coffee, lots of coffee.</li><li>Steel will, courage, and eagerness to learn.</li></ol><h4>The Solution</h4><p>Everything starts with something small, one short step after another. In this particular case, we’ll begin by creating a directory in our web server’s root directory.</p><p>Let’s give it a superhero movie name, “<strong>routeman</strong>”. If handling routes in web applications were a mutant superpower, this would be part of the X-men team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*MiIZhmXhCBoGrXoQRL3DJg.gif" /></figure><p>Once created, within the folder, create the following files and directories:</p><ul><li><strong>.htaccess:</strong> This file is responsible for configuring redirection and route rewriting on the web server using <strong>mod_rewrite</strong>. We’ll also add some options in it to control access to PHP files in the directory.</li><li><strong>index.php:</strong> This file will receive all requests made to the URL and will be responsible for defining routes and their configuration.</li><li><strong>RouteMan.php:</strong> The heart of our solution, this class will handle all route management logic and site behavior.</li><li><strong>/routes:</strong> This will be our directory containing PHP files associated with each “<strong>file</strong>” type route. Later on, we’ll see the two types of routes we can create (“<strong>file</strong>” and “<strong>function</strong>”). For the “<strong>file</strong>” type, our route handler will invoke the corresponding file stored in the <strong>/routes</strong> folder, as configured in <strong>index.php.</strong></li><li><strong>/routes/default.php:</strong> It will show default content when accessing the home URL. This includes a list of available routes and an error (missing) route to demonstrate the behavior when this happens.</li><li><strong>/routes/about.php:</strong> It will display content at the <strong>/about</strong> route.</li><li><strong>/routes/testjson.php:</strong> It will return content at the <strong>/json</strong> route with a custom Content-Type “<strong>application/json</strong>”.</li></ul><p>The general structure of our solution regarding directories and files will be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*_UqKaWYUE0lObmdn8Pxfww.png" /><figcaption>Files and directories structure</figcaption></figure><blockquote>Ignore the .vscode directory; it’s part of the project when you create debugging profiles in VS Code.</blockquote><p>Now let’s move on to the Apache HTTP Server configuration in our .<strong>htaccess </strong>file.</p><pre># Restrict direct access to .php files from sources other than localhost.<br>&lt;Files &quot;*.php&quot;&gt;<br>  Require ip 127.0.0.1<br>&lt;/Files&gt;<br><br># Authorize the only entry point for requests coming from external IPs, our index.php file.<br>&lt;Files &quot;index.php&quot;&gt;<br>  Require all granted<br>&lt;/Files&gt;<br><br># Activate the route rewriting engine.<br>RewriteEngine On<br><br># Uncomment the following lines if you want to enforce access through HTTPS<br>#RewriteCond %{HTTPS} off<br>#RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]<br><br># Activate the authorization header if you&#39;re using PHP in CGI mode.<br>RewriteCond %{HTTP:Authorization} ^(.)<br>RewriteRule . - [e=HTTP_AUTHORIZATION:%1]<br><br># Set the mod_rewrite relative path where our files are located.<br># If you are going to use a directory at the end of the URL, e.g., http://yourdomain.com/routeman,<br># you should set this.<br>RewriteBase /routeman/<br><br># And now our redirection control. These lines instruct the server<br># that any file or directory name in a URL should redirect it<br># to the index.php file.<br>RewriteCond %{REQUEST_FILENAME} !-d<br>RewriteCond %{REQUEST_FILENAME} !-f<br>RewriteRule ^(.+)$ index.php [QSA,L]</pre><p>With this configuration, we redirect all traffic to index.php, and from there, we can manage the routes using the <strong>RouteMan </strong>class that we will implement next.</p><h4>RouteMan.php</h4><pre>&lt;?php<br><br>/**<br> * RouteMan class provides routing functionality for all mankind.<br> */<br>class RouteMan<br>{<br>    /** @var string The path to the directory of &quot;file&quot; type routes. */<br>    private string $routePath;<br><br>    /** @var string The default content type. */<br>    private string $defaultContentType;<br><br>    /** @var array The array of configured routes. */<br>    private array $arrRoutes;<br><br>    /** @var string The protocol used to access the HTTP/HTTPS route. */<br>    private string $requestURL;<br><br>    /** @var string The current managed route. */<br>    private string $currentRoute;<br><br>    /** @var string The rewrite base for routes. */<br>    private string $rewriteBase;<br><br>    /**<br>     * RouteMan constructor.<br>     */<br>    public function __construct()<br>    {<br>        // Initialize properties<br>        $this-&gt;requestURL = (isset($_SERVER[&quot;HTTPS&quot;]) ? &quot;https://&quot; : &quot;http://&quot;) <br>                            . $_SERVER[&quot;HTTP_HOST&quot;] . $_SERVER[&quot;REQUEST_URI&quot;];<br>        $this-&gt;routePath = &#39;routes/&#39;;<br>        $this-&gt;defaultContentType = &#39;text/html&#39;;<br>        $this-&gt;currentRoute = &#39;&#39;;<br>        $this-&gt;rewriteBase = &#39;/routeman&#39;;<br><br>        // Default message when a route is not found.<br>        $this-&gt;addRoute(&#39;error&#39;, [<br>            &#39;function&#39; =&gt; function ($route) {<br>                echo &quot;Route &quot; . $route . &quot; not found!&quot;;<br>            }<br>        ]);<br>    }<br><br>    /**<br>     * Adds a route to the RouteMan instance.<br>     *<br>     * @param string $url The URL of the route, e.g., &quot;about&quot;.<br>     * @param array $routeAttr The file attribute of the route. This parameter<br>     * has the following structure:<br>     *<br>     * array(&quot;file&quot; =&gt; &quot;name of the php file to use&quot;, <br>     *       &quot;content&quot; =&gt; &quot;text/html&quot;)<br>     *<br>     * array(&quot;function&quot; =&gt; function(){<br>     *         echo &quot;hello&quot;;<br>     *       }, <br>     *       &quot;content&quot; =&gt; &quot;text/html&quot;)<br>     *<br>     * @return void<br>     */<br>    public function addRoute(string $url, array $routeAttr): void<br>    {<br>        $arrURLs = explode(&quot;,&quot;, $url);<br><br>        foreach ($arrURLs as $urlItem) {<br>            $this-&gt;arrRoutes[$urlItem] = $routeAttr;<br>        }<br>    }<br><br>    /**<br>     * Manages actions and access to configured routes based on the URL provided.<br>     *<br>     * @return void<br>     */<br>    public function manageRoutes(): void<br>    {<br>        $this-&gt;requestURL = (isset($_SERVER[&quot;HTTPS&quot;]) ? &quot;https://&quot; : &quot;http://&quot;) . $_SERVER[&quot;HTTP_HOST&quot;] . $_SERVER[&quot;REQUEST_URI&quot;];<br><br>        $arrURL = parse_url(https://medium.com/$this-&gt;requestURL);<br>        $arrURLParams = array();<br><br>        if (isset($arrURL[&#39;query&#39;])) {<br>            parse_str($arrURL[&#39;query&#39;], $arrURLParams);<br>        }<br><br>        // Convert parameters sent through JavaScript using .fetch() to a &quot;global&quot; array like $_POST or $_GET<br>        $_RMFETCH = json_decode(file_get_contents(&quot;php://input&quot;), true);<br><br>        if (is_null($_RMFETCH)) {<br>            $_RMFETCH = array();<br>        }<br><br>        $arrURL[&quot;path&quot;] = str_replace($this-&gt;rewriteBase, &quot;&quot;, $arrURL[&quot;path&quot;]);<br>        $this-&gt;currentRoute = trim($arrURL[&#39;path&#39;], &quot;/&quot;);<br><br>        if (array_key_exists($this-&gt;currentRoute, $this-&gt;arrRoutes)) {<br>            if (array_key_exists(&#39;content&#39;, $this-&gt;arrRoutes[$this-&gt;currentRoute])) {<br>                $this-&gt;setHeaderType($this-&gt;arrRoutes[$this-&gt;currentRoute][&#39;content&#39;]);<br>            } else {<br>                $this-&gt;setHeaderType();<br>            }<br><br>            if (isset($this-&gt;arrRoutes[$this-&gt;currentRoute][&#39;file&#39;])) {<br>                $filePath = $this-&gt;routePath . $this-&gt;arrRoutes[$this-&gt;currentRoute][&#39;file&#39;];<br><br>                if (file_exists($filePath)) {<br>                    require $filePath;<br>                    exit;<br>                }<br>            }<br><br>            if (isset($this-&gt;arrRoutes[$this-&gt;currentRoute][&#39;function&#39;])) {<br>                $this-&gt;arrRoutes[$this-&gt;currentRoute][&#39;function&#39;]();<br>                exit;<br>            }<br>        } else {<br>            $this-&gt;arrRoutes[&quot;error&quot;][&#39;function&#39;]($this-&gt;currentRoute);<br>            exit;<br>        }<br>    }<br><br>    /**<br>     * Sets the Content-Type to use for each invoked route.<br>     *<br>     * @param string|null $type The content type.<br>     * @return void<br>     */<br>    public function setHeaderType($type = null): void<br>    {<br>        if (is_null($type)) {<br>            $type = $this-&gt;defaultContentType;<br>        }<br><br>        header(&quot;Content-Type: &quot; . $type . &quot;; charset=UTF-8&quot;);<br>    }<br>}<br></pre><p>Let’s analyze the source code. In the constructor, we’ll define some default values necessary for the operation of <strong>RouteMan</strong>. The first of these will be <strong>requestURL</strong>, where we’ll store the type of protocol used to access our routes (HTTP/HTTPS). This is necessary to create the complete final route.</p><p>Next, we’ll set <strong>routePath</strong>, which contains the directory where files associated with “<strong>file</strong>” type routes will be searched. Routes of this type will look for the file in the directory <strong>/routes</strong>, inject it into the script, and then terminate execution.</p><p>We also define the default Content-Type to use in our routes in the <strong>defaultContentType </strong>property, which in this case is “<strong>text/html</strong>”.</p><p>We have an attribute that allows us to save the currently processed route within the instance, which we will call <strong>currentRoute</strong>, and by default, it will be empty at the start of execution.</p><p>Finally, we will have the attribute associated with the base route for rewriting called <strong>rewriteBase</strong>. This should match the one set in the .<strong>htaccess </strong>file, for our particular case, “<strong>/routeman</strong>”.</p><p>Now let’s move on to the functions included in the class.</p><p>The <strong><em>addRoute()</em></strong> method allows adding the defined routes that the instantiated object will handle. It takes two parameters of type string, <strong>$url</strong> and <strong>$routeAttr</strong>, which allow adding routes like this:</p><pre>&lt;?php<br>require_once(&quot;RouteMan.php&quot;);<br><br>$objRouteMan = new RouteMan();<br><br>// Routes of type &quot;file&quot;<br>$objRouteMan-&gt;addRoute(&#39;about&#39;, [&#39;file&#39; =&gt; &#39;about.php&#39;]);<br><br>// Route with custom Content-Type<br>$objRouteMan-&gt;addRoute(&#39;json&#39;, [<br>    &#39;file&#39; =&gt; &#39;testjson.php&#39;,<br>    &#39;content&#39; =&gt; &#39;application/json&#39;<br>]);<br><br>// Route of type &quot;function&quot; <br>// (anonymous function or you can pass a reference to an existing function)<br>$objRouteMan-&gt;addRoute(&#39;testfunct&#39;, [<br>    &#39;function&#39; =&gt; function () {<br>        echo &quot;&lt;!DOCTYPE html&gt;<br>        &lt;html&gt;<br>        <br>        &lt;head&gt;<br>            &lt;title&gt;About&lt;/title&gt;<br>        &lt;/head&gt;<br>        <br>        &lt;body&gt;<br>        <br>            &lt;h1&gt;This is a function-generated content&lt;/h1&gt;<br>            &lt;p&gt;Great!.&lt;/p&gt;<br>        <br>        &lt;/body&gt;<br>        <br>        &lt;/html&gt;&quot;;<br>    }<br>]);</pre><p>As you can see, there are two types of routes available: “<strong>file</strong>” and “<strong>function</strong>”. The first one invokes a .php file in the <strong>/routes </strong>directory and executes the code within it.</p><p>The “<strong>function</strong>” type allows managing routes using anonymous functions or a reference to an existing function in your code.</p><p>You can also set the Content-Type per route if you need the server to respond in a particular way to a request.</p><p>Finally, we have the function responsible for setting the Content-Type of the server response when making a request to a route, <strong><em>setHeaderType()</em></strong>. This function takes an optional string parameter <strong>$type</strong> to set the Content-Type to use and modifies the corresponding response header of the server. If you want to set a custom Content-Type per route, you just need to add it in the route configuration by including it in the “<strong>content</strong>” entry of the <strong>$routeAttr</strong> array when adding the route.</p><p>Next, let’s review the content of the route files. In most cases, it will be a message within a basic HTML structure.</p><h4>default.php</h4><p>This file will be displayed by default when accessing <a href="http://localhost/routeman">http://localhost/routeman</a>. It will show the list of available routes and an example of an unknown route to test the error message if such an event occurs.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br><br>&lt;head&gt;<br>    &lt;title&gt;Default!&lt;/title&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br><br>    &lt;h1&gt;Route list:&lt;/h1&gt;<br>    &lt;ul&gt;<br>        &lt;li&gt;&lt;a href=&quot;about&quot;&gt;About&lt;/a&gt;&lt;/li&gt;<br>        &lt;li&gt;&lt;a href=&quot;json&quot;&gt;Json&lt;/a&gt;&lt;/li&gt;<br>        &lt;li&gt;&lt;a href=&quot;anotherroute&quot;&gt;Route&lt;/a&gt;&lt;/li&gt;<br>    &lt;/ul&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><h4>about.php</h4><p>This file will be included and displayed by the site once a visitor enters the URL <a href="http://localhost/about">http://localhost/about</a>.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br><br>&lt;head&gt;<br>    &lt;title&gt;About&lt;/title&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br><br>    &lt;h1&gt;This is about&lt;/h1&gt;<br>    &lt;p&gt;This is a paragraph.&lt;/p&gt;<br><br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><h4>testjson.php</h4><p>This route file will display a message encoded in JSON format. To serve the content, the Content-Type is changed to “<strong>application/json</strong>”.</p><pre>&lt;?php<br>echo json_encode(array(&quot;this is&quot; =&gt; &quot;json content&quot;));</pre><p>Now that we have our route files, our <strong>RouteMan </strong>class, and .<strong>htaccess</strong>, let’s move on to the <strong>index.php</strong> file responsible for making the magic happen.</p><h4>index.php</h4><pre>&lt;?php<br><br>// Include our class file<br>require_once(&quot;RouteMan.php&quot;);<br><br>// Create an instance of RouteMan<br>$objRouteMan = new RouteMan();<br><br>// Configure our file routes<br>$objRouteMan-&gt;addRoute(&#39;&#39;, [&#39;file&#39; =&gt; &#39;default.php&#39;]);<br>$objRouteMan-&gt;addRoute(&#39;about&#39;, [&#39;file&#39; =&gt; &#39;about.php&#39;]);<br><br>// Configure a sample route, changing the Content-Type to JSON<br>$objRouteMan-&gt;addRoute(&#39;json&#39;, [<br>    &#39;file&#39; =&gt; &#39;testjson.php&#39;,<br>    &#39;content&#39; =&gt; &#39;application/json&#39;<br>]);<br><br>// Configure a route using anonymous functions (if that&#39;s your thing)<br>$objRouteMan-&gt;addRoute(&#39;testfunct&#39;, [<br>    &#39;function&#39; =&gt; function () {<br>        echo &quot;&lt;!DOCTYPE html&gt;<br>        &lt;html&gt;<br>        <br>        &lt;head&gt;<br>            &lt;title&gt;About&lt;/title&gt;<br>        &lt;/head&gt;<br>        <br>        &lt;body&gt;<br>        <br>            &lt;h1&gt;This is a function-generated content&lt;/h1&gt;<br>            &lt;p&gt;Great!.&lt;/p&gt;<br>        <br>        &lt;/body&gt;<br>        <br>        &lt;/html&gt;&quot;;<br>    }<br>]);<br><br>// Finally, ask our RoutMan to manage our routes.<br>$objRouteMan-&gt;manageRoutes();</pre><p>Our <strong>index.php</strong> file includes the <strong>RouteMan </strong>class file, creates an instance, and configures the routes to be managed. Once configured, the <strong><em>manageRoutes()</em></strong> function is called to execute the instructions based on visitor requests.</p><p>And there we have it, our route handler is ready. Elegant, isn’t it?</p><p>Now let’s test it. Open your browser and go to <a href="http://localhost/routeman"><strong>http://localhost/routeman</strong></a> (or the URL configured in your development environment, assuming you have one, right?). Then, you can start accessing the routes configured in your <strong>index.php</strong>, like this:</p><pre>http://localhost/routeman<br>http://localhost/routeman/about<br>http://localhost/routeman/json<br>http://localhost/routeman/testfunct</pre><p>You should see results like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*c4WXKQHgekzGkQYYJW9Mww.png" /><figcaption>Default route</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*-_6LomJCWW-dAJQhzhmkcA.png" /><figcaption>About route</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*ry047ogCxp7B7KltPYInWA.png" /><figcaption>Json route</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*2Hurjy933IeztVsPjJoxBQ.png" /><figcaption>Missing route error message</figcaption></figure><p>As you can see, the concept and implementation are quite straightforward. Certain knowledge of web server configuration is required, but overall, managing routes in this way allows for greater control over traffic and the responses you want to give to visitors’ requests.</p><p>Remember, at <a href="https://winkhosting.co/"><strong>winkhosting.co</strong></a>, <strong>we are much more than hosting!</strong> Work on your goals for this year, tell your loved ones that you care about them, and we’ll see you in our next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98f9126b1384" width="1" height="1" alt=""><hr><p><a href="https://medium.com/winkhosting/basic-route-managament-with-php-and-apache-httpd-98f9126b1384">Basic route management with PHP and Apache httpd</a> was originally published in <a href="https://medium.com/winkhosting">winkhosting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gestión básica de rutas con PHP y Apache]]></title>
            <link>https://medium.com/winkhostinglatam/gesti%C3%B3n-b%C3%A1sica-de-rutas-con-php-y-apache-44e05cdb3727?source=rss-d00dafbb1ae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/44e05cdb3727</guid>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[route-management]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[router]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Camilo Herrera]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 20:10:59 GMT</pubDate>
            <atom:updated>2024-02-05T20:10:59.985Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qYbXYtSpXFa1Q4p4" /><figcaption>Photo by <a href="https://unsplash.com/@martinirc?utm_source=medium&amp;utm_medium=referral">José Martín Ramírez Carrasco</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hola!, espero que estés iniciando el año con muchos planes y tranquilidad, recuerda que cada día que existimos es una bendición y debemos aprovecharlo de la mejor forma posible.</p><p>Hoy vamos a estudiar un concepto básico para la gestión de un sitio o software web, el manejo de rutas. En este artículo nos enfocaremos en la gestión de las rutas usando<strong> </strong><a href="https://php.net/"><strong>PHP</strong></a>, <a href="https://httpd.apache.org/"><strong>Apache </strong></a>y <a href="https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html"><strong>mod_rewrite</strong></a>.</p><p>Exploremos como lo hacemos en nuestra compañía, generalmente nuestros requerimientos son bastante básicos y no necesitamos frameworks o librerías con funcionalidades avanzadas para este tipo de tareas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*57qCMEhhXNEAzhCnWkXuQA.jpeg" /><figcaption>R.I.P my meme friend, you will always be remembered.</figcaption></figure><p>Vamos a iniciar como siempre con nuestros requisitos y luego iniciaremos la implementación y explicación de conceptos aplicados para nuestra solución.</p><h4>Requisitos</h4><p>Como en la mayoría de nuestras publicaciones, serán necesarios los siguientes elementos:</p><ol><li>Un entorno local/remoto de desarrollo que incluya PHP 8.2, Apache 2.4 y el módulo mod_rewrite activo Apache</li><li>Café, mucho café</li><li>Voluntad de acero, coraje y ganas de aprender.</li></ol><h4>La solución</h4><p>Todo inicia con algo pequeño, un paso corto tras otro, en nuestro caso, vamos a iniciar creando un directorio en nuestro directorio raíz del servidor web, vamos a darle un nombre de super héroe de película “routeman”, si manejar rutas en aplicaciones web fuera un super poder mutante, este sería parte del equipo X-men.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*MiIZhmXhCBoGrXoQRL3DJg.gif" /></figure><p>Una vez creado, dentro de él crea los siguientes archivos y directorios:</p><ul><li><strong>.htaccess: </strong>Este archivo es el encargado de la configuración de redirección y sobreescritura de rutas en el servidor web usando mod_rewrite, también agregaremos en él algunas opciones para controlar el acceso a archivos php en el directorio.</li><li><strong>index.php: </strong>Este archivo recibirá todas las peticiones realizadas al directorio y será el encargado de la definición de las rutas y sus características.</li><li><strong>RouteMan.php: </strong>El corazón de nuestra solución, esta clase será la encargada de toda la lógica de gestión de rutas y comportamiento del sitio.</li><li><strong>/routes</strong>: Este será nuestro directorio que contendrá los archivos php asociados a cada ruta de tipo “<strong>file</strong>”. Más adelante veremos los dos tipos de rutas que podemos crear (“<strong>file</strong>” y “<strong>function</strong>”), para el tipo “<strong>file</strong>”, nuestro manejador de rutas invocará el archivo correspondiente según sean configuradas en el <strong>index.php</strong>.</li><li><strong>/routes/default.php: </strong>Mostrará contenido por defecto al ingresar al URL del home, este incluye una lista de las rutas disponibles y una ruta con errores para mostrar el comportamiento cuando esto ocurra.</li><li><strong>/routes/about.php: </strong>Mostrará contenido en la ruta /about.</li><li><strong>/routes/testjson.php</strong> Retornará contenido en la ruta /json con un ContentType personalizado “application/json”.</li></ul><p>La estructura general de nuestra solución con respecto a directorios y archivos será la siguiente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*AVdrAtX9SuO7Dwgwwq-BzA.png" /><figcaption>Estructura de archivos y directorios</figcaption></figure><blockquote>Ignora el directorio .vscode es parte del proyecto cuando creas perfiles de depuración en VS Code.</blockquote><p>Ahora vamos a la configuración de Apache HTTP Server en nuestro archivo .htaccess</p><h4>.htaccess</h4><pre># Restringimos el acceso directo a archivos .php desde orígenes diferentes a<br># localhost.<br>&lt;Files &quot;*.php&quot;&gt;<br>    Require ip 127.0.0.1<br>&lt;/Files&gt;<br><br># Ahora autorizamos el único punto de acceso para peticiones que provienen<br># de IPs externas, nuestro archivo index.php<br>&lt;Files &quot;index.php&quot;&gt;<br>    Require all granted<br>&lt;/Files&gt;<br><br># Activamos el motor de reescritura de rutas.<br>RewriteEngine On<br><br># Quita el comentario si quieres forzar el acceso a través de HTTPS<br>#RewriteCond %{HTTPS} off<br>#RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]<br><br># Activamos el header de autorización si usas php en modo cgi. <br>RewriteCond %{HTTP:Authorization} ^(.*)<br>RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]<br><br># Le indicamos a mod_rewrite la ruta relativa dentro de la cual están nuestros<br># archivos, si vas a usar un directorio al final de la URL ej.<br># http://midominio.com/routeman<br># debes escribir el RewriteBase<br>RewriteBase /routeman/<br><br># y ahora nuestro control de redirección, estas líneas le indican al servidor<br># que cualquier nombre de archivo o directorio en una URL debe redireccionarlo<br># al archivo index.php.<br>RewriteCond %{REQUEST_FILENAME} !-d<br>RewriteCond %{REQUEST_FILENAME} !-f<br>RewriteRule ^(.+)$ index.php [QSA,L]</pre><p>Con esta configuración logramos que todo el tráfico sea dirigido a <strong>index.php</strong> y desde allí podemos hacer la gestión de las rutas usando la clase <strong>RouteMan </strong>que implementaremos a continuación.</p><h4>RouteMan.php</h4><pre>&lt;?php<br><br>/**<br> * Clase RouteMan que proporciona funcionalidad de enrutamiento.<br> */<br>class RouteMan<br>{<br>    /** @var string La ruta al directorio de archivos para rutas tipo &quot;file&quot;. */<br>    private string $routePath;<br><br>    /** @var string El tipo de contenido predeterminado. */<br>    private string $defaultContentType;<br><br>    /** @var array El arreglo de rutas configuradas. */<br>    private array $arrRoutes;<br><br>    /** @var string El protocolo usado para acceder la ruta HTTP/HTTPS. */<br>    private string $requestURL;<br><br>    /** @var string La ruta actual gestionada. */<br>    private string $currentRoute;<br><br>    /** @var string La base de reescritura para las rutas. */<br>    private string $rewriteBase;<br><br>    /**<br>     * Constructor de RouteMan.<br>     */<br>    public function __construct()<br>    {<br>        // Inicializar propiedades<br>        $this-&gt;requestURL = (isset($_SERVER[&quot;HTTPS&quot;]) ? &quot;https://&quot; : &quot;http://&quot;) <br>                            . $_SERVER[&quot;HTTP_HOST&quot;] . $_SERVER[&quot;REQUEST_URI&quot;];<br>        $this-&gt;routePath = &#39;routes/&#39;;<br>        $this-&gt;defaultContentType = &#39;text/html&#39;;<br>        $this-&gt;currentRoute = &#39;&#39;;<br>        $this-&gt;rewriteBase = &#39;/routeman&#39;;<br><br>        //mensaje por defecto cuando no se encuentra una ruta.<br>        $this-&gt;addRoute(&#39;error&#39;, [<br>            &#39;function&#39; =&gt; function ($route) {<br>                echo &quot;Route &quot; . $route . &quot; not found!&quot;;<br>            }<br>        ]);<br>    }<br><br>    /**<br>     * Agrega una ruta a la instancia de RouteMan.<br>     *<br>     * @param string $url La URL de la ruta, ejemplo &quot;about&quot;.<br>     * @param array $routeAttr El atributo de archivo de la ruta. Este parámetro<br>     * tiene la siguiente estructura:<br>     *<br>     * array(&quot;file&quot; =&gt; &quot;nombre del archivo php a usar&quot;, <br>     *       &quot;content&quot; =&gt; &quot;text/html&quot;)<br>     *<br>     * array(&quot;function&quot; =&gt; function(){<br>     *         echo &quot;hello&quot;;<br>     *       }, <br>     *       &quot;content&quot; =&gt; &quot;text/html&quot;)<br>     *<br>     * @return void<br>     */<br>    public function addRoute(string $url, array $routeAttr): void<br>    {<br>        $arrURLs = explode(&quot;,&quot;, $url);<br><br>        foreach ($arrURLs as $urlItem) {<br>            $this-&gt;arrRoutes[$urlItem] = $routeAttr;<br>        }<br>    }<br><br>    /**<br>     * Gestiona las acciones y acceso a las rutas configuradas a partir del URL<br>     *<br>     * @return void<br>     */<br>    public function manageRoutes(): void<br>    {<br><br>        $this-&gt;requestURL = (isset($_SERVER[&quot;HTTPS&quot;]) ? &quot;https://&quot; : &quot;http://&quot;) . $_SERVER[&quot;HTTP_HOST&quot;] . $_SERVER[&quot;REQUEST_URI&quot;];<br><br>        $arrURL = parse_url(https://medium.com/$this-&gt;requestURL);<br>        $arrURLParams = array();<br><br>        if (isset($arrURL[&#39;query&#39;])) {<br><br>            parse_str($arrURL[&#39;query&#39;], $arrURLParams);<br>        }<br><br>        // Convertimos los parámetros enviados a través de javascript usando <br>        // .fetch() a un arreglo &quot;global&quot; como $_POST o $_GET<br>        $_RMFETCH = json_decode(file_get_contents(&quot;php://input&quot;), true);<br><br>        if (is_null($_RMFETCH)) {<br><br>            $_RMFETCH = array();<br>        }<br><br>        $arrURL[&quot;path&quot;] = str_replace($this-&gt;rewriteBase, &quot;&quot;, $arrURL[&quot;path&quot;]);<br>        $this-&gt;currentRoute = trim($arrURL[&#39;path&#39;], &quot;/&quot;);<br><br>        if (array_key_exists($this-&gt;currentRoute, $this-&gt;arrRoutes)) {<br><br>            if (array_key_exists(&#39;content&#39;, $this-&gt;arrRoutes[$this-&gt;currentRoute])) {<br><br>                $this-&gt;setHeaderType($this-&gt;arrRoutes[$this-&gt;currentRoute][&#39;content&#39;]);<br>            } else {<br><br>                $this-&gt;setHeaderType();<br>            }<br><br>            if (isset($this-&gt;arrRoutes[$this-&gt;currentRoute][&#39;file&#39;])) {<br><br>                $filePath = $this-&gt;routePath . $this-&gt;arrRoutes[$this-&gt;currentRoute][&#39;file&#39;];<br><br>                if (file_exists($filePath)) {<br><br>                    require $filePath;<br>                    exit;<br>                }<br>            }<br><br>            if (isset($this-&gt;arrRoutes[$this-&gt;currentRoute][&#39;function&#39;])) {<br><br>                $this-&gt;arrRoutes[$this-&gt;currentRoute][&#39;function&#39;]();<br>                exit;<br>            }<br>        } else {<br>            $this-&gt;arrRoutes[&quot;error&quot;][&#39;function&#39;]($this-&gt;currentRoute);<br>            exit;<br>        }<br>    }<br><br>    /**<br>     * Fija el Content-Type a usar para cada ruta invocada.<br>     *<br>     * @param string|null $type The content type<br>     * @return void<br>     */<br>    public function setHeaderType($type = null): void<br>    {<br>        if (is_null($type)) {<br><br>            $type = $this-&gt;defaultContentType;<br>        }<br><br>        header(&quot;Content-Type: &quot; . $type . &quot;; charset=UTF-8&quot;);<br>    }<br>}</pre><p>Analicemos el código fuente. En el constructor vamos a definir algunos valores por defecto necesarios para la operación de RoutMan, el primero de ellos será <strong>requestURL</strong> en él se guardará el tipo de protocolo usado para acceder a nuestras rutas (HTTP/HTTPS), este es necesario para construir la ruta final completa.</p><p>A continuación fijaremos <strong>routePath, </strong>que contiene el directorio donde se buscarán los archivos asociados a rutas de tipo “<strong>file</strong>”, las rutas de este tipo buscarán el archivo en el directorio, lo inyectarán en el script y finalizarán la ejecución.</p><p>También definimos el Content-Type por defecto a usar en nuestras rutas en la propiedad <strong>defaultContentType</strong>, en este caso “<strong>text/html</strong>”.</p><p>Contamos con un atributo que nos permite guardar dentro de la instancia, la ruta actual procesada, lo llamaremos <strong>currentRoute </strong>y por defecto estará vacío al inicio de la ejecución.</p><p>Y para terminar tendremos el atributo asociado a la ruta base para la sobreescritura llamado<strong> rewriteBase</strong>, este debe corresponder con el fijado en el archivo <strong>.htaccess</strong>, (será el mismo), para nuestro caso particular “<strong>/routeman</strong>”.</p><p>Ahora vamos a las funciones incluídas en la clase.</p><p>El método <strong><em>addRoute()</em></strong> permite agregar, al objeto instanciado, las rutas definidas que manejará, este cuenta con dos parámetros de tipo string <strong>$url</strong> y <strong>$routeAttr</strong> que permiten agregar rutas así:</p><pre>&lt;?php<br>require_once(&quot;RouteMan.php&quot;);<br><br>$objRouteMan = new RouteMan();<br><br>//rutas de tipo file (archivo)<br>$objRouteMan-&gt;addRoute(&#39;about&#39;, [&#39;file&#39; =&gt; &#39;about.php&#39;]);<br><br>//ruta con Content-Type personalizado<br>$objRouteMan-&gt;addRoute(&#39;json&#39;, [<br>    &#39;file&#39; =&gt; &#39;testjson.php&#39;,<br>    &#39;content&#39; =&gt; &#39;application/json&#39;<br>]);<br><br>//ruta de tipo function <br>//(funcion anónima o puedes pasar una referencia a una función existente)<br>$objRouteMan-&gt;addRoute(&#39;testfunct&#39;, [<br>    &#39;function&#39; =&gt; function () {<br>        echo &quot;&lt;!DOCTYPE html&gt;<br>        &lt;html&gt;<br>        <br>        &lt;head&gt;<br>            &lt;title&gt;About&lt;/title&gt;<br>        &lt;/head&gt;<br>        <br>        &lt;body&gt;<br>        <br>            &lt;h1&gt;This is a function generated content&lt;/h1&gt;<br>            &lt;p&gt;Great!.&lt;/p&gt;<br>        <br>        &lt;/body&gt;<br>        <br>        &lt;/html&gt;&quot;;<br>    }<br>]);</pre><p>Como puedes ver, dispones de dos tipos de ruta “<strong>file</strong>” y “<strong>function</strong>”, el primero invoca un archivo .php en el directorio <strong>/routes</strong> y ejecuta el código en él.</p><p>El tipo “<strong>function</strong>” permite gestionar rutas usando funciones anónimas o una referencia a una función existente en tu código.</p><p>También puedes establecer el Content-Type por ruta si necesitas que el servidor responda de forma particular a una petición.</p><p>Por último tenemos la función encargada de fijar el Content-Type de la respuesta del servidor al hacer una petición a una ruta <strong><em>setHeaderType()</em></strong>, esta recibe un parámetro opcional <strong>$type </strong>que indica el Content-Type a usar y modifica el header de respuesta correspondiente del servidor, si quieres fijar un Content-Type personalizado por ruta solo es necesario agregarlo en la configuración de la ruta al agregarla en la entrada “<strong>content</strong>” del arreglo <strong>$routeAttr.</strong></p><p>A continuación revisemos el contenido de los archivos de rutas, en su mayoría será un mensaje dentro de una estructura básica de HTML.</p><h4>default.php</h4><p>Este archivo será mostrado por defecto al ingresar a <a href="http://localhost/routeman">http://localhost/routeman</a> en él se mostrará la lista de rutas disponibles y un ejemplo de una ruta desconocida para probar el mensaje de error si se presenta un evento de este tipo.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br><br>&lt;head&gt;<br>    &lt;title&gt;Default!&lt;/title&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br><br>    &lt;h1&gt;Route list:&lt;/h1&gt;<br>    &lt;ul&gt;<br>        &lt;li&gt;&lt;a href=&quot;about&quot;&gt;About&lt;/a&gt;&lt;/li&gt;<br>        &lt;li&gt;&lt;a href=&quot;json&quot;&gt;Json&lt;/a&gt;&lt;/li&gt;<br>        &lt;li&gt;&lt;a href=&quot;anotherroute&quot;&gt;Route&lt;/a&gt;&lt;/li&gt;<br>    &lt;/ul&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><h4>about.php</h4><p>Este archivo será incluído y mostrado por el sitio una vez un visitante ingrese a la URL http://localhost/about</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br><br>&lt;head&gt;<br>    &lt;title&gt;About&lt;/title&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br><br>    &lt;h1&gt;This is about&lt;/h1&gt;<br>    &lt;p&gt;This is a paragraph.&lt;/p&gt;<br><br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><h4>testjson.php</h4><p>Este archivo de ruta mostrará un mensaje codificado en formato JSON, para presentar el contenido se cambia el Content-Type por “application/json”</p><pre>&lt;?php<br>echo json_encode(array(&quot;this is&quot; =&gt; &quot;json content&quot;));</pre><p>Ahora teniendo nuestros archivos de ruta, nuestra clase RouteMan y .<strong>htaccess </strong>vamos al archivo <strong>index.php</strong> encargado de hacer la magia.</p><h4>index.php</h4><pre>&lt;?php<br><br>//incluimos nuestra clase<br>require_once(&quot;RouteMan.php&quot;);<br><br>//creamos una instancia de RouteMan<br>$objRouteMan = new RouteMan();<br><br>//configuramos nuestras rutas de archivo<br>$objRouteMan-&gt;addRoute(&#39;&#39;, [&#39;file&#39; =&gt; &#39;default.php&#39;]);<br>$objRouteMan-&gt;addRoute(&#39;about&#39;, [&#39;file&#39; =&gt; &#39;about.php&#39;]);<br><br>//configuramos una ruta de muestra cambiando el Content-Type a JSON<br>$objRouteMan-&gt;addRoute(&#39;json&#39;, [<br>    &#39;file&#39; =&gt; &#39;testjson.php&#39;,<br>    &#39;content&#39; =&gt; &#39;application/json&#39;<br>]);<br><br>//configuramos una ruta usando funciones anónimas (si eso es lo tuyo)<br>$objRouteMan-&gt;addRoute(&#39;testfunct&#39;, [<br>    &#39;function&#39; =&gt; function () {<br>        echo &quot;&lt;!DOCTYPE html&gt;<br>        &lt;html&gt;<br>        <br>        &lt;head&gt;<br>            &lt;title&gt;About&lt;/title&gt;<br>        &lt;/head&gt;<br>        <br>        &lt;body&gt;<br>        <br>            &lt;h1&gt;This is a function generated content&lt;/h1&gt;<br>            &lt;p&gt;Great!.&lt;/p&gt;<br>        <br>        &lt;/body&gt;<br>        <br>        &lt;/html&gt;&quot;;<br>    }<br>]);<br><br>//y finalmente pedimos a nuestro RoutMan que gestione nuestras rutas.<br>$objRouteMan-&gt;manageRoutes();</pre><p>Nuestro archivo <strong>index.php</strong> incluye el archivo de la clase <strong>RouteMan</strong>, crea una instancia y configura las rutas a gestionar, una vez configuradas se hace el llamado a la función <strong><em>manageRoutes()</em></strong> para ejecutar las instrucciones a partir de las peticiones de los visitantes.</p><p>Y tenemos listo nuestro manejador de rutas, elegante verdad?</p><p>Ahora vamos a probarlo, abre tu navegador e ingresa a <a href="http://localhost/routeman"><strong>http://localhost/routeman</strong></a> (o la URL que tengas configurada en tu entorno de desarrollo, tienes un entorno de desarrollo verdad?). Y puedes empezar a ingresar a las rutas configuradas en tu index.php, por ejemplo:</p><pre>http://localhost/routeman<br>http://localhost/routeman/about<br>http://localhost/routeman/json<br>http://localhost/routeman/testfunct</pre><p>Debes ver resultados como este:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*5JOfONMlbSjoAUGA44g1JA.png" /><figcaption>Ruta por defecto</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*xLhUjsqBqnu4MHS8XKvcWg.png" /><figcaption>Ruta /about</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*63AKJEk-p9E7M5CfcyLQDw.png" /><figcaption>Ruta /json</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*suXslZwI-bfRfic-LFTcyQ.png" /><figcaption>Mensaje de ruta no encontrada</figcaption></figure><p>Como puedes ver, el concepto e implementación son bastante sencillos, se requieren ciertos conocimientos en configuración del servidor web, pero en general gestionar las rutas de esta forma permite un mayor control del tráfico y respuesta que quieras dar a las peticiones de los visitantes.</p><p>Recuerda que en <a href="https://winkhosting.co/"><strong>winkhosting.co</strong></a> somos mucho más que hosting!, trabaja en tus propósitos para este año, diles a tus seres queridos que los amas y nos veremos en nuestra próxima publicación.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44e05cdb3727" width="1" height="1" alt=""><hr><p><a href="https://medium.com/winkhostinglatam/gesti%C3%B3n-b%C3%A1sica-de-rutas-con-php-y-apache-44e05cdb3727">Gestión básica de rutas con PHP y Apache</a> was originally published in <a href="https://medium.com/winkhostinglatam">winkhostingla</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>