<?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[winkhosting - Medium]]></title>
        <description><![CDATA[Our weekly adventures in the world of web hosting, programming, UX/UI, branding, graphic design, business management and all the new things you have to do in a startup company! - Medium]]></description>
        <link>https://medium.com/winkhosting?source=rss----c578fc6c854f---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>winkhosting - Medium</title>
            <link>https://medium.com/winkhosting?source=rss----c578fc6c854f---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:53:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/winkhosting" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <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----c578fc6c854f---4</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[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----c578fc6c854f---4</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[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----c578fc6c854f---4</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----c578fc6c854f---4</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[Exploring DNS records using PHP]]></title>
            <link>https://medium.com/winkhosting/exploring-dns-records-using-php-a475e9d2dd66?source=rss----c578fc6c854f---4</link>
            <guid isPermaLink="false">https://medium.com/p/a475e9d2dd66</guid>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[servers]]></category>
            <dc:creator><![CDATA[Camilo Herrera]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 16:28:09 GMT</pubDate>
            <atom:updated>2023-12-04T16:28:09.117Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aOqbHa8StGECsaV6" /><figcaption>Photo by <a href="https://unsplash.com/@alessandroerbetta?utm_source=medium&amp;utm_medium=referral">Alessandro Erbetta</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello! The year is almost over, how are you doing with those goals you set? If you haven’t achieved them, be patient, rest, but don’t stop.</p><p>This will be one of the last posts of the year, and I want to propose to you this adventure of enlightenment and personal growth to analyze DNS records of a domain using PHP. This is something we do very often in our company, and we decided it would be very useful to have our own tool for these queries.</p><p>On the Internet, there are many tools to check all kinds of DNS zone records, with advanced functions and several years of operation. Our proposed solution will be inspired by a service that, apparently, has been abandoned but is still functional, <a href="https://intodns.com/"><strong>intodns</strong></a>.</p><p>You can also visit the following sites which have very complete tools:</p><p><a href="https://dnschecker.org/"><strong>https://dnschecker.org/</strong></a> This tool is very useful for determining the propagation status of a change in DNS records.</p><p><a href="https://mxtoolbox.com/SuperTool.aspx"><strong>https://mxtoolbox.com/SuperTool.aspx</strong></a> This tool allows you to query all kinds of zone records and provides suggestions in case it finds errors.</p><h4>Records to be queried</h4><p>For our guide, we will query the following types of DNS records for a domain:</p><ol><li><strong>A Records:</strong> This is the fundamental type of DNS record and it maps the domain address to a physical IP (IPv4), the equivalent for IPv6 is the <strong>AAAA </strong>record.</li><li><strong>MX Records:</strong> This record is used for mail exchange, meaning it indicates to mail servers where to deliver messages directed to mailboxes associated with the domain.</li><li><strong>NS (Nameserver) Records:</strong> This type of record is essential, containing the address of the server or servers authorized to manage the DNS zone records (MX, A, CNAME, PTR, SOA, etc.)</li><li><strong>PTR Records (Reverse DNS lookups): </strong>This record allows resolving a domain name from an IP, i.e., handling reverse IP to name resolution requests, usually used for email validation and to determine if a message’s originating server really is who it claims to be.</li><li><strong>SOA Records:</strong> “Start of Authority”, it contains basic information about the domain or associated DNS zone, including the administrator’s email address, last update, and refresh times between changes.</li><li><strong>CNAME Records: </strong>“Canonical Name”, it acts as an “alias” for a real domain name (A record) or a canonical domain (another CNAME record), for example, it’s common for a domain’s <a href="http://www/">www</a>. address to be a CNAME and point to the domain’s A record.</li></ol><p>To query these records, we will use PHP’s integrated functionalities, which include the <a href="https://www.php.net/manual/en/function.dns-get-record.php"><strong>dns_get_record</strong></a> function that allows querying the listed record types.</p><blockquote><strong>Warning:</strong> dns_get_records allows for basic DNS queries. Keep in mind that if you require more advanced operations, such as querying a specific DNS server or debugging information, this would not be the best option and you are going to feel the pain!</blockquote><p>Now, let’s implement our solution.</p><h4>Requirements</h4><p>The requirements for this project are as follows:</p><ol><li>A development environment for PHP 8.2+ with its respective web server</li><li>Your favorite code editor</li><li>A cup of coffee</li><li>And that’s all. If you were expecting something more complex, go study about K8s (Kubernetes)</li></ol><h4>Our Scripts</h4><p>In the root of our public directory of the web server, we will create a directory named “<strong>dns-scout</strong>”. Inside this directory, we will create the following files:</p><ol><li><strong>index.html</strong>: Responsible for the GUI of our project</li><li><strong>requestmanager.php</strong>: This script will handle receiving the domain query request and returning the results in JSON format</li><li><strong>Scout.php</strong>: Our file that will contain the definition of the class responsible for DNS query operations.</li></ol><p>The structure of the directory and files will be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*RnsGI4hSMpmVQGNiBfnjlQ.png" /><figcaption>Files</figcaption></figure><p>Now let’s go through each of the scripts to understand their source code and functions.</p><h4>Scout.php</h4><p>This class has eight methods, six of which are responsible for querying the types of DNS records listed in the initial part of this article (A, MX, NS, PTR, CNAME, and SOA), and two more functions, one which will be our starting point of execution “scoutDomain()”, and “invertIPv4()”, which is responsible for inverting an IP to perform PTR record queries.</p><p>The content of the file is as follows:</p><pre>&lt;?php<br><br>/**<br> * Class Scout<br> */<br>class Scout<br>{<br>    /**<br>     * @var array For storing result.<br>     */<br>    private array $result;<br><br>    /**<br>     * @var string PTR suffix.<br>     */<br>    private string $PTRsuffix;<br><br>    /**<br>     * @var string CNAME Prefix.<br>     */<br>    private string $CNAMEPreffix;<br><br>    /**<br>     * Constructing initial settings.<br>     */<br>    public function __construct()<br>    {<br>        $this-&gt;result = array(&quot;dnsinfo&quot; =&gt; array());<br>        $this-&gt;PTRsuffix = &quot;.in-addr.arpa&quot;;<br>        $this-&gt;CNAMEPreffix = &quot;www.&quot;;<br>    }<br><br>    /**<br>     * Scout domain to get DNS details.<br>     *<br>     * @param string $domain<br>     * @return array result<br>     */<br>    public function scoutDomain(string $domain): array<br>    {<br><br>        $this-&gt;result[&quot;dnsinfo&quot;][&quot;NS&quot;] = $this-&gt;getNameservers($domain);<br>        $this-&gt;result[&quot;dnsinfo&quot;][&quot;SOA&quot;] = $this-&gt;getSoaRecord($domain);<br>        $this-&gt;result[&quot;dnsinfo&quot;][&quot;MX&quot;] = $this-&gt;getMxRecords($domain);<br>        $this-&gt;result[&quot;dnsinfo&quot;][&quot;A&quot;] = $this-&gt;getARecord($domain);<br>        $this-&gt;result[&quot;dnsinfo&quot;][&quot;WWW&quot;] = $this-&gt;getCnameRecord($this-&gt;CNAMEPreffix . $domain);<br><br>        foreach ($this-&gt;result[&quot;dnsinfo&quot;][&quot;MX&quot;] as $mxReg) {<br><br>            $aRecords = $this-&gt;getARecord($mxReg[&quot;target&quot;]);<br><br>            foreach ($aRecords as $aRec) {<br>                $invertedIP = $this-&gt;invertIPv4($aRec[&quot;ip&quot;]);<br>                $this-&gt;result[&quot;dnsinfo&quot;][&quot;PTR&quot;][] = $this-&gt;getPtrRecord($invertedIP . $this-&gt;PTRsuffix);<br>            }<br>        }<br><br>        return $this-&gt;result;<br>    }<br><br>    /**<br>     * Get Nameservers of a domain.<br>     *<br>     * @param string $domain<br>     * @return array $nameservers<br>     */<br>    private function getNameservers(string $domain)<br>    {<br>        $nameservers = array();<br>        try {<br><br>            $ns_records = dns_get_record($domain, DNS_NS);<br><br>            if ($ns_records === false || count($ns_records) == 0) {<br>                $this-&gt;result[&quot;errors&quot;][] = &quot;Failed to retrieve nameservers for the domain $domain.&quot;;<br>            }<br><br>            $nameservers = [];<br><br>            foreach ($ns_records as $record) {<br><br>                $ip_records = dns_get_record($record[&#39;target&#39;], DNS_A);<br><br>                if ($ip_records !== false &amp;&amp; count($ip_records) &gt; 0) {<br>                    $nameservers[] = [<br>                        &#39;nameserver&#39; =&gt; $record[&#39;target&#39;],<br>                        &#39;ipv4&#39; =&gt; $ip_records[0][&#39;ip&#39;]<br>                    ];<br>                } else {<br>                    $nameservers[] = [<br>                        &#39;nameserver&#39; =&gt; $record[&#39;target&#39;],<br>                        &#39;ipv4&#39; =&gt; null<br>                    ];<br>                }<br>            }<br>        } catch (Exception $e) {<br>            $this-&gt;result[&quot;errors&quot;][] = &quot;An error occurred: {$e-&gt;getMessage()}&quot;;<br>        } finally {<br>            return $nameservers;<br>        }<br>    }<br><br>    /**<br>     * Get the SOA record of a domain.<br>     *<br>     * @param string $domain<br>     * @return array SOA record data<br>     */<br>    private function getSoaRecord(string $domain): array<br>    {<br>        $result = array();<br><br>        try {<br>            $result = dns_get_record($domain, DNS_SOA);<br>            if (!$result) {<br>                $this-&gt;result[&quot;errors&quot;][] = &quot;Failed to retrieve SOA record for the domain $domain.&quot;;<br>            }<br>        } catch (Throwable $e) {<br>            $this-&gt;result[&quot;errors&quot;][] = &quot;An error occurred: {$e-&gt;getMessage()}&quot;;<br>        } finally {<br>            return $result;<br>        }<br>    }<br><br>    /**<br>     * Get the MX records of a domain.<br>     *<br>     * @param string $domain<br>     * @return array $records<br>     */<br>    private function getMxRecords(string $domain): array<br>    {<br>        $records = array();<br><br>        try {<br>            $records = dns_get_record($domain, DNS_MX);<br>            if (!$records) {<br>                $this-&gt;result[&quot;errors&quot;][] = &quot;Failed to retrieve MX records for: $domain. If you see this message PTR records won&#39;t be shown.&quot;;<br>            }<br>        } catch (Throwable $e) {<br>            $this-&gt;result[&quot;errors&quot;][] = &quot;An error occurred: {$e-&gt;getMessage()}&quot;;<br>        } finally {<br>            return $records;<br>        }<br>    }<br><br>    /**<br>     * Get PTR record of an IP.<br>     *<br>     * @param string $ip<br>     * @return array $result<br>     */<br>    private function getPtrRecord(string $ip): array<br>    {<br>        $result = array();<br>        try {<br>            $result = dns_get_record($ip, DNS_PTR);<br>            if (!$result) {<br>                $this-&gt;result[&quot;errors&quot;][] = &quot;Failed to retrieve PTR record for the IP $ip.&quot;;<br>            }<br>        } catch (Throwable $e) {<br>            $this-&gt;result[&quot;errors&quot;][] = &quot;An error occurred: {$e-&gt;getMessage()}&quot;;<br>        } finally {<br>            return $result[0];<br>        }<br>    }<br><br>    /**<br>     * Get A record of a domain.<br>     *<br>     * @param string $domain<br>     * @return array $result<br>     */<br>    private function getARecord(string $domain): array<br>    {<br>        $result = array();<br>        try {<br>            $result = dns_get_record($domain, DNS_A);<br>            if (!$result) {<br>                $this-&gt;result[&quot;errors&quot;][] = &quot;Failed to retrieve A record for the domain $domain.&quot;;<br>            }<br>        } catch (Throwable $e) {<br>            $this-&gt;result[&quot;errors&quot;][] = &quot;An error occurred: {$e-&gt;getMessage()}&quot;;<br>        } finally {<br>            return $result;<br>        }<br>    }<br><br>    /**<br>     * Get CNAME record of a domain.<br>     *<br>     * @param string $domain<br>     * @return array $result<br>     */<br>    private function getCnameRecord(string $domain): array<br>    {<br>        try {<br>            $result = dns_get_record($domain, DNS_CNAME);<br><br>            if (!$result) {<br>                $this-&gt;result[&quot;errors&quot;][] = &quot;Failed to retrieve CNAME record for the domain $domain.&quot;;<br>            }<br>        } catch (Throwable $e) {<br>            $this-&gt;result[&quot;errors&quot;][] = &quot;An error occurred: {$e-&gt;getMessage()}&quot;;<br>        } finally {<br>            return $result;<br>        }<br>    }<br><br>    /**<br>     * Reverse given IP address.<br>     *<br>     * @param string $ip<br>     * @return string $result<br>     */<br>    function invertIPv4(string $ip): string<br>    {<br>        $parts = explode(&quot;.&quot;, $ip);<br><br>        // reverse the array<br>        $parts = array_reverse($parts);<br><br>        $result = implode(&quot;.&quot;, $parts);<br><br>        return $result;<br>    }<br>}</pre><h4>requestmanager.php</h4><p>The “requestmanager.php” file will be responsible for executing DNS queries and returning their results.</p><p>Let&#39;s explore how it is structured:</p><pre>// The class to be used in our query is included.<br>require(&quot;Scout.php&quot;);<br><br>// We decode the parameters received from the index.html file and store them in the $paramsFetch array<br>$paramsFetch = json_decode(<br>    file_get_contents(&quot;php://input&quot;),<br>    true<br>);<br><br>// We create an instance of our class<br>$scout = new Scout();<br>// We send the domain name to retrieve its DNS records<br>$result = $scout-&gt;scoutDomain($paramsFetch[&quot;domain&quot;]);<br><br>// Here we return the response in JSON format and end the execution.<br>$jsonResponse = json_encode($result);<br>echo $jsonResponse;<br>exit;</pre><p>In it, we include the Scout class, also receive the query parameters through a fetch request from JavaScript in index.html, then create an instance of the class and make a call to the “scoutDomain()” method, sending the received domain name as a parameter.</p><p>Once the request is processed, we return the result in JSON format.</p><p>Now let’s go to the GUI file, index.html.</p><h4>index.html</h4><p>Our HTML interface will look like the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjmT255n6uXB6I9VHWrDWw.png" /><figcaption>DNS Scout GUI</figcaption></figure><p>The file content is as follows:</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;DNS Scout&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>    &lt;script type=&quot;module&quot;&gt;<br>        window.addEventListener(&#39;load&#39;, (event) =&gt; {<br><br>            document.querySelector(&quot;.search&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;domain&quot;: document.querySelector(&quot;.domain&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>                        console.log(data.errors);<br>                        if (data.errors != undefined) {<br>                            document.querySelector(&quot;.error&quot;).parentElement.classList.remove(&quot;is-hidden&quot;);<br>                            document.querySelector(&quot;.error&quot;).innerText = &quot;&quot;;<br><br>                            for (const item in data.errors) {<br>                                document.querySelector(&quot;.error&quot;).innerText += data.errors[item] + &quot;\n&quot;;<br>                            }<br><br>                        }<br><br>                        document.querySelector(&quot;.result&quot;).parentElement.classList.remove(&quot;is-hidden&quot;);<br>                        //document.querySelector(&quot;.result&quot;).innerText = data.dnsinfo;<br><br>                        document.querySelector(&quot;.a-records&quot;).innerHTML = &quot;&quot;;<br>                        document.querySelector(&quot;.mx-records&quot;).innerHTML = &quot;&quot;;<br>                        document.querySelector(&quot;.ns-records&quot;).innerHTML = &quot;&quot;;<br>                        document.querySelector(&quot;.ptr-records&quot;).innerHTML = &quot;&quot;;<br>                        document.querySelector(&quot;.soa-records&quot;).innerHTML = &quot;&quot;;<br>                        document.querySelector(&quot;.www-records&quot;).innerHTML = &quot;&quot;;<br><br>                        for (const record in data.dnsinfo.A) {<br><br>                            document.querySelector(&quot;.a-records&quot;).innerHTML += `<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;host:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0&quot;&gt;<br>                                    ${data.dnsinfo.A[record].host} <br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;class:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.A[record].class} <br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;ttl:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.A[record].ttl}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;type:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.A[record].type}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;ip:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pt-1&quot;&gt;<br>                                    ${data.dnsinfo.A[record].ip}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;`;<br>                        }<br><br>                        for (const record in data.dnsinfo.MX) {<br><br>                            document.querySelector(&quot;.mx-records&quot;).innerHTML += `<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;host:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0&quot;&gt;<br>                                    ${data.dnsinfo.MX[record].host}<br>                                &lt;/div&gt;<br>                                <br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;priority:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.MX[record].pri} <br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;target:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.MX[record].target}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;ttl:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.MX[record].ttl}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;type:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pt-1&quot;&gt;<br>                                    ${data.dnsinfo.MX[record].type}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;`;<br>                        }<br><br>                        for (const record in data.dnsinfo.NS) {<br><br>                            document.querySelector(&quot;.ns-records&quot;).innerHTML += `<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;nameserver:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0&quot;&gt;<br>                                    ${data.dnsinfo.NS[record].nameserver}<br>                                &lt;/div&gt;<br>                                <br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;ipv4:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pt-1&quot;&gt;<br>                                    ${data.dnsinfo.NS[record].ipv4} <br>                                &lt;/div&gt;<br>                            &lt;/div&gt;`;<br>                        }<br><br><br>                        for (const record in data.dnsinfo.PTR) {<br><br>                            document.querySelector(&quot;.ptr-records&quot;).innerHTML += `<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column is-one-fifth pb-0&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;host:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0&quot;&gt;<br>                                    ${data.dnsinfo.PTR[record].host}<br>                                &lt;/div&gt;<br>                                <br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column is-one-fifth pb-0 pt-1&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;class:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.PTR[record].class} <br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column is-one-fifth pb-0 pt-1&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;target:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.PTR[record].target}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column is-one-fifth pb-0 pt-1&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;ttl:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.PTR[record].ttl}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column is-one-fifth pt-1&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;type:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pt-1&quot;&gt;<br>                                    ${data.dnsinfo.PTR[record].type}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;`;<br>                        }<br><br><br>                        for (const record in data.dnsinfo.SOA) {<br><br>                            document.querySelector(&quot;.soa-records&quot;).innerHTML += `<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;host:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0&quot;&gt;<br>                                    ${data.dnsinfo.SOA[record].host}<br>                                &lt;/div&gt;<br>                                <br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;class:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.SOA[record].class} <br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;expire:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.SOA[record].expire}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;minimum-ttl:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.SOA[record][&quot;minimum-ttl&quot;]}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;mname:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.SOA[record].mname}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;refresh:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.SOA[record].refresh}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;retry:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.SOA[record].retry}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;rname:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.SOA[record].rname}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;serial:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.SOA[record].serial}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;ttl:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.SOA[record].ttl}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;type:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pt-1&quot;&gt;<br>                                    ${data.dnsinfo.SOA[record].type}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;`;<br>                        }<br><br><br>                        for (const record in data.dnsinfo.WWW) {<br><br>                            document.querySelector(&quot;.www-records&quot;).innerHTML += `<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;host:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0&quot;&gt;<br>                                    ${data.dnsinfo.WWW[record].host}<br>                                &lt;/div&gt;<br>                                <br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;class:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.WWW[record].class} <br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;target:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.WWW[record].target}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;ttl:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pb-0 pt-1&quot;&gt;<br>                                    ${data.dnsinfo.WWW[record][&quot;ttl&quot;]}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;columns is-mobile&quot;&gt;<br>                                &lt;div class=&quot;column pt-1 is-one-fifth&quot;&gt;<br>                                    &lt;h5 class=&quot;title is-6&quot;&gt;type:&lt;/h5&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;column pt-1&quot;&gt;<br>                                    ${data.dnsinfo.WWW[record].type}<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;`;<br>                        }<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;.search&quot;).classList.remove(&#39;is-loading&#39;);<br>                        document.querySelector(&quot;.search&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;container&quot;&gt;<br>            &lt;div class=&quot;columns&quot;&gt;<br>                &lt;div class=&quot;column&quot;&gt;<br>                    &lt;div class=&quot;columns&quot;&gt;<br>                        &lt;div class=&quot;column&quot;&gt;&lt;/div&gt;<br>                        &lt;div class=&quot;column has-text-centered&quot;&gt;<br>                            &lt;h1 class=&quot;title&quot;&gt;<br>                                DNS Scout<br>                            &lt;/h1&gt;<br>                        &lt;/div&gt;<br>                        &lt;div class=&quot;column&quot;&gt;&lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;columns&quot;&gt;<br>                        &lt;div class=&quot;column has-text-centered&quot;&gt;<br>                            &lt;div class=&quot;field is-grouped is-grouped-centered&quot;&gt;<br>                                &lt;div class=&quot;control&quot;&gt;<br>                                    &lt;input class=&quot;input domain&quot; type=&quot;text&quot; placeholder=&quot;Domain&quot;&gt;<br>                                &lt;/div&gt;<br>                                &lt;div class=&quot;control&quot;&gt;<br>                                    &lt;button class=&quot;button is-info search&quot;&gt;<br>                                        Go!<br>                                    &lt;/button&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&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><br>                    &lt;div class=&quot;columns&quot;&gt;<br>                        &lt;div class=&quot;column&quot;&gt;<br><br>                            &lt;article class=&quot;message&quot; style=&quot;height: 100%;&quot;&gt;<br>                                &lt;div class=&quot;message-header&quot;&gt;<br>                                    &lt;p&gt;A Records&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 a-records&quot;&gt;<br><br>                                        &lt;/div&gt;<br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/article&gt;<br><br>                        &lt;/div&gt;<br>                        &lt;div class=&quot;column&quot;&gt;<br><br>                            &lt;article class=&quot;message&quot; style=&quot;height: 100%;&quot;&gt;<br>                                &lt;div class=&quot;message-header&quot;&gt;<br>                                    &lt;p&gt;MX Records&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 mx-records&quot;&gt;<br><br>                                        &lt;/div&gt;<br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/article&gt;<br><br>                        &lt;/div&gt;<br><br>                    &lt;/div&gt;<br><br>                    &lt;div class=&quot;columns&quot;&gt;<br>                        &lt;div class=&quot;column&quot;&gt;<br><br>                            &lt;article class=&quot;message&quot; style=&quot;height: 100%;&quot;&gt;<br>                                &lt;div class=&quot;message-header&quot;&gt;<br>                                    &lt;p&gt;NS Records&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 ns-records&quot;&gt;<br><br>                                        &lt;/div&gt;<br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/article&gt;<br><br>                        &lt;/div&gt;<br>                        &lt;div class=&quot;column&quot;&gt;<br><br>                            &lt;article class=&quot;message&quot; style=&quot;height: 100%;&quot;&gt;<br>                                &lt;div class=&quot;message-header&quot;&gt;<br>                                    &lt;p&gt;PTR Records&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 ptr-records&quot;&gt;<br><br>                                        &lt;/div&gt;<br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/article&gt;<br><br>                        &lt;/div&gt;<br><br>                    &lt;/div&gt;<br><br>                    &lt;div class=&quot;columns&quot;&gt;<br>                        &lt;div class=&quot;column&quot;&gt;<br><br>                            &lt;article class=&quot;message&quot; style=&quot;height: 100%;&quot;&gt;<br>                                &lt;div class=&quot;message-header&quot;&gt;<br>                                    &lt;p&gt;SOA Records&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 soa-records&quot;&gt;<br><br>                                        &lt;/div&gt;<br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/article&gt;<br><br>                        &lt;/div&gt;<br>                        &lt;div class=&quot;column&quot;&gt;<br><br>                            &lt;article class=&quot;message&quot; style=&quot;height: 100%;&quot;&gt;<br>                                &lt;div class=&quot;message-header&quot;&gt;<br>                                    &lt;p&gt;WWW Records&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 www-records&quot;&gt;<br><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 box is-hidden&quot;&gt;<br>                &lt;div class=&quot;column 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>As you can see, we make a fetch request via <strong>POST </strong>to the “requestmanager.php” file when clicking the “<strong>Go!</strong>” button on the form.</p><p>The returned response contains an associative array in the “<strong>data.dnsinfo</strong>” entry with the DNS records, using the following JSON structure:</p><pre>{<br>  &quot;NS&quot;: [<br>    {<br>      &quot;nameserver&quot;: &quot;c.ns.instagram.com&quot;,<br>      &quot;ipv4&quot;: &quot;185.89.218.12&quot;<br>    },<br>    {<br>      &quot;nameserver&quot;: &quot;d.ns.instagram.com&quot;,<br>      &quot;ipv4&quot;: &quot;185.89.219.12&quot;<br>    },<br>    {<br>      &quot;nameserver&quot;: &quot;b.ns.instagram.com&quot;,<br>      &quot;ipv4&quot;: &quot;129.134.31.12&quot;<br>    },<br>    {<br>      &quot;nameserver&quot;: &quot;a.ns.instagram.com&quot;,<br>      &quot;ipv4&quot;: &quot;129.134.30.12&quot;<br>    }<br>  ],<br>  &quot;SOA&quot;: [<br>    {<br>      &quot;host&quot;: &quot;instagram.com&quot;,<br>      &quot;class&quot;: &quot;IN&quot;,<br>      &quot;ttl&quot;: 1234,<br>      &quot;type&quot;: &quot;SOA&quot;,<br>      &quot;mname&quot;: &quot;a.ns.instagram.com&quot;,<br>      &quot;rname&quot;: &quot;dns.facebook.com&quot;,<br>      &quot;serial&quot;: 1678373413,<br>      &quot;refresh&quot;: 14400,<br>      &quot;retry&quot;: 1800,<br>      &quot;expire&quot;: 604800,<br>      &quot;minimum-ttl&quot;: 3600<br>    }<br>  ],<br>  &quot;MX&quot;: [<br>    {<br>      &quot;host&quot;: &quot;instagram.com&quot;,<br>      &quot;class&quot;: &quot;IN&quot;,<br>      &quot;ttl&quot;: 1265,<br>      &quot;type&quot;: &quot;MX&quot;,<br>      &quot;pri&quot;: 10,<br>      &quot;target&quot;: &quot;mxb-00082601.gslb.pphosted.com&quot;<br>    },<br>    {<br>      &quot;host&quot;: &quot;instagram.com&quot;,<br>      &quot;class&quot;: &quot;IN&quot;,<br>      &quot;ttl&quot;: 1265,<br>      &quot;type&quot;: &quot;MX&quot;,<br>      &quot;pri&quot;: 10,<br>      &quot;target&quot;: &quot;mxa-00082601.gslb.pphosted.com&quot;<br>    }<br>  ],<br>  &quot;A&quot;: [<br>    {<br>      &quot;host&quot;: &quot;instagram.com&quot;,<br>      &quot;class&quot;: &quot;IN&quot;,<br>      &quot;ttl&quot;: 298,<br>      &quot;type&quot;: &quot;A&quot;,<br>      &quot;ip&quot;: &quot;157.240.6.174&quot;<br>    }<br>  ],<br>  &quot;WWW&quot;: [<br>    {<br>      &quot;host&quot;: &quot;www.instagram.com&quot;,<br>      &quot;class&quot;: &quot;IN&quot;,<br>      &quot;ttl&quot;: 1916,<br>      &quot;type&quot;: &quot;CNAME&quot;,<br>      &quot;target&quot;: &quot;geo-p42.instagram.com&quot;<br>    }<br>  ],<br>  &quot;PTR&quot;: [<br>    {<br>      &quot;host&quot;: &quot;42.145.231.67.in-addr.arpa&quot;,<br>      &quot;class&quot;: &quot;IN&quot;,<br>      &quot;ttl&quot;: 1297,<br>      &quot;type&quot;: &quot;PTR&quot;,<br>      &quot;target&quot;: &quot;mx0a-00082601.pphosted.com&quot;<br>    },<br>    {<br>      &quot;host&quot;: &quot;42.145.231.67.in-addr.arpa&quot;,<br>      &quot;class&quot;: &quot;IN&quot;,<br>      &quot;ttl&quot;: 1297,<br>      &quot;type&quot;: &quot;PTR&quot;,<br>      &quot;target&quot;: &quot;mx0a-00082601.pphosted.com&quot;<br>    }<br>  ]<br>}</pre><p>Additionally, an array is included in the position “<strong>data.errors</strong>” that contains error messages presented during the execution of the queries.</p><p>This response is processed by DNS record type and the elements are added to each section in the interface using template literals. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals"><strong>Template literals</strong> </a>are quite useful for injecting information into HTML elements from JavaScript. I recommend using them if you haven’t already.</p><p>And that’s all, remember that at <a href="https://winkhosting.co/"><strong>Winkhosting.co</strong></a> we are much more than hosting.</p><p>I wish you a Merry Christmas, don’t forget to share your time with your loved ones and be thankful for every achievement you had this year. Live a life worth living!.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a475e9d2dd66" width="1" height="1" alt=""><hr><p><a href="https://medium.com/winkhosting/exploring-dns-records-using-php-a475e9d2dd66">Exploring DNS records 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[Create a ChatBot using AI, ChatGPT and PHP]]></title>
            <link>https://medium.com/winkhosting/create-a-chatbot-using-ai-chatgpt-and-php-41bb752f6403?source=rss----c578fc6c854f---4</link>
            <guid isPermaLink="false">https://medium.com/p/41bb752f6403</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Camilo Herrera]]></dc:creator>
            <pubDate>Thu, 12 Oct 2023 21:05:49 GMT</pubDate>
            <atom:updated>2023-10-12T21:05:49.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_P9gxV0VJG3PSQ8n" /><figcaption>Photo by <a href="https://unsplash.com/@phillipglickman?utm_source=medium&amp;utm_medium=referral">Phillip Glickman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello, welcome to this new guide with fresh and diverse content for our elegant, friendly, and always well-dressed audience. Due to all the noise caused by AI in recent months, we decided to explore the possibility of implementing a customer support and service bot using this new tool, particularly <strong>ChatGPT </strong>created by <a href="https://openai.com/"><strong>OpenAI</strong></a>.</p><p>In this post, we will create a proof of concept to determine how far we can go. Below are the requirements for this project:</p><h4><strong>Requirements</strong></h4><ul><li>Open an account at <strong>openai.com</strong>. By default, they will provide you with $5 USD in credit for testing. After this, I recommend preparing your credit card or your parents’ credit card… (it will be a nice surprise to discover that your child is investing their credit in the future of artificial intelligence).</li><li>Create an API Key from your <strong>OpenAI </strong>account.</li><li>Have a PHP development environment on your PC. We will use PHP 8.2, including a web server.</li><li>Maintain good posture while sitting in your desk chair. This is very important!</li></ul><h4>Opening our OpenAI account and creating an API Key</h4><p>Go to <a href="https://openai.com/"><strong><em>https://openai.com</em></strong></a> and follow the steps on the portal to open your account. An additional step of authentication (by sending a text message to your phone) will be necessary. Keep this in mind.</p><p>Once you complete the account opening process, go to the option in the top menu and click on your account name in the top right corner. Then, click on the “<strong><em>View API Keys</em></strong>” option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*I6KpL5MCv_KZ3lg11SsRmw.png" /><figcaption>OpenAI API Keys option</figcaption></figure><p>The section with the title “<strong><em>API Keys</em></strong>” will be displayed. There, click on the “<strong><em>+ Create new secret key</em></strong>” button, assign an optional name to the new secret key, and click “<strong><em>Create secret key</em></strong>.” The new key will be displayed on the screen.</p><p>Copy the text (starting with sk-…) and save it in a secure place. You will need this key to authenticate your requests and use the OpenAI API. Finally, click the “<strong><em>Done</em></strong>” button.</p><h4>Preparing our development environment and files</h4><p>In our PHP development environment, we will create a directory, in this case, we’ll call it “<strong>ai-chatbot</strong>,” and inside it, we will create the following files:</p><ul><li><strong>index.html</strong>: This will be the entry point to our chat and will handle the GUI (Graphical User Interface).</li><li><strong>ChatBot.php</strong>: Our class responsible for the interaction routines with the ChatGPT API.</li><li><strong>requestmanager.php</strong>: This file will receive requests from index.html and return the results of the interaction with ChatGPT.</li><li><strong>test-data.json</strong>: This file will contain simulated information related to the service our ChatBot will provide. It can be anything; in this case, we will use information about computer components.</li></ul><p>The file structure would be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0UlHyWb8f2PO4g_-UlgMvw.png" /><figcaption>Our project files</figcaption></figure><p>We will start by creating our GUI, which will be a basic chat form with a section to view the conversation and a text box with its respective button to send messages. We will build the interface using my beloved <a href="https://bulma.io/"><strong>Bulma CSS</strong></a>, and it will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*AhoAEIqwPAbsfxjtWIgcJg.png" /><figcaption>Our chat GUI</figcaption></figure><p>The content of the <strong>index.html</strong> file is as follows:</p><p><strong>index.html</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;Hello A.I. Bot!&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>    &lt;script type=&quot;module&quot;&gt;<br>        window.addEventListener(&#39;load&#39;, (event) =&gt; {<br><br>            document.querySelector(&quot;.sendMessage&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>                let currHour = new Date();<br><br>                const userMsgTemplate = `&lt;div class=&quot;columns&quot;&gt;<br>                                        &lt;div class=&quot;column is-one-third&quot;&gt;&lt;/div&gt;<br>                                        &lt;div class=&quot;column&quot;&gt;<br>                                            &lt;div class=&quot;notification is-success&quot;&gt;<br>                                                &lt;h6 class=&quot;subtitle is-6&quot;&gt;${currHour.getHours() + &quot;:&quot; + currHour.getMinutes()}&lt;/h6&gt;<br>                                                ${document.querySelector(&quot;.message&quot;).value}<br>                                            &lt;/div&gt;<br>                                        &lt;/div&gt;<br>                                    &lt;/div&gt;`<br><br><br>                let chatBox = document.querySelector(&quot;.messageHistory&quot;);<br><br>                chatBox.innerHTML += userMsgTemplate;<br>                chatBox.scrollIntoView(false);<br><br>                const payload = JSON.stringify({<br>                    &quot;message&quot;: document.querySelector(&quot;.message&quot;).value<br>                });<br><br>                document.querySelector(&quot;.message&quot;).value = &quot;&quot;;<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>                }).then(response =&gt; response.json())<br>                    .then(data =&gt; {<br><br>                        let currHour = new Date();<br><br>                        data.responseMessage = data.responseMessage.replace(&quot;\n&quot;, &quot;&lt;br&gt;&quot;);<br><br>                        let aiMsgTemplate = `&lt;div class=&quot;columns&quot;&gt;<br>                                                &lt;div class=&quot;column&quot;&gt;<br>                                                    &lt;div class=&quot;notification is-info&quot;&gt;<br>                                                        &lt;h6 class=&quot;subtitle is-6&quot;&gt;${currHour.getHours() + &quot;:&quot; + currHour.getMinutes()}&lt;/h6&gt;<br>                                                        ${data.responseMessage}<br>                                                    &lt;/div&gt;<br>                                                &lt;/div&gt;<br>                                                &lt;div class=&quot;column is-one-third&quot;&gt;&lt;/div&gt;<br>                                            &lt;/div&gt;`<br><br>                        chatBox.innerHTML += aiMsgTemplate;<br>                        chatBox.scrollIntoView(false);<br><br>                    })<br>                    .catch((error) =&gt; {<br>                        console.error(&#39;Error:&#39;, error);<br>                    }).finally(() =&gt; {<br>                        document.querySelector(&quot;.sendMessage&quot;).classList.remove(&#39;is-loading&#39;);<br>                        document.querySelector(&quot;.sendMessage&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;container&quot;&gt;<br>            &lt;div class=&quot;columns  box&quot;&gt;<br>                &lt;div class=&quot;column&quot;&gt;<br>                    &lt;div class=&quot;columns&quot;&gt;<br>                        &lt;div class=&quot;column has-text-centered&quot;&gt;<br>                            &lt;h1 class=&quot;title&quot;&gt;<br>                                Hello A.I. Bot!<br>                            &lt;/h1&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;columns&quot;&gt;<br>                        &lt;div class=&quot;column&quot;&gt;<br>                            &lt;div class=&quot;card-content&quot; style=&quot;height:600px;overflow:auto;flex-grow: 1;flex-shrink: 1;&quot;&gt;<br>                                &lt;div class=&quot;content messageHistory&quot;&gt;<br><br><br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br><br><br>                    &lt;div class=&quot;columns&quot;&gt;<br>                        &lt;div class=&quot;column&quot;&gt;<br>                            &lt;input class=&quot;input message&quot; type=&quot;text&quot; placeholder=&quot;Type your message&quot;&gt;<br>                        &lt;/div&gt;<br>                        &lt;div class=&quot;column is-narrow&quot;&gt;<br>                            &lt;button class=&quot;button is-info sendMessage&quot;&gt;<br>                                Send<br>                            &lt;/button&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br><br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;columns box is-hidden&quot;&gt;<br>                &lt;div class=&quot;column result&quot;&gt;&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;columns box is-hidden&quot;&gt;<br>                &lt;div class=&quot;column 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>With JavaScript, we will create an event handler for the send button identified with the class “<strong>sendMessage</strong>.” Inside it, we will create the routine to send the message using <strong>POST </strong>through the Fetch API to our <strong>requestmanager.php</strong> file. We will await the response and use it to display the received message in the chat box identified with the class “<strong>messageHistory</strong>.”</p><p>Now, let’s create our <strong>JSON </strong>file that will simulate a custom data source to be used in case the visitor asks a question related to the products our bot sells.</p><p>The content of the file will be as follows:</p><p><strong>test-data.json</strong></p><pre>{<br>    &quot;cpu&quot;: [<br>        {<br>            &quot;brand&quot;: &quot;AMD&quot;,<br>            &quot;model&quot;: &quot;AMD Ryzen 5 5600X&quot;,<br>            &quot;price&quot;: &quot;USD 158&quot;<br>        },<br>        {<br>            &quot;brand&quot;: &quot;AMD&quot;,<br>            &quot;model&quot;: &quot;AMD Ryzen 9 5950X&quot;,<br>            &quot;price&quot;: &quot;USD 799&quot;<br>        },<br>        {<br>            &quot;brand&quot;: &quot;Intel&quot;,<br>            &quot;model&quot;: &quot;Core i5-12600K&quot;,<br>            &quot;price&quot;: &quot;USD 179&quot;<br>        }<br>    ],<br>    &quot;memory&quot;: [<br>        {<br>            &quot;brand&quot;: &quot;Corsair&quot;,<br>            &quot;model&quot;: &quot;VENGEANCE DDR5 1x32GB&quot;,<br>            &quot;price&quot;: &quot;USD 159&quot;<br>        },<br>        {<br>            &quot;brand&quot;: &quot;G.SKILL&quot;,<br>            &quot;model&quot;: &quot;Trident Z5 RGB Series DDR5 1x16GB&quot;,<br>            &quot;price&quot;: &quot;USD 104&quot;<br>        }<br>    ]<br>}</pre><p>We will use some CPU and RAM models for testing.</p><p>Now, let’s move on to the class responsible for interacting with the <strong>OpenAI</strong> API; this is where the fun begins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNkiSXCQ-CsFhhk12L4vYQ.png" /><figcaption>You should look like this by now.</figcaption></figure><p><strong>ChatBot.php</strong></p><pre>&lt;?php<br><br>/**<br> * ChatBot Class<br> */<br>class ChatBot<br>{<br>    /**<br>     * @var string The authorization token for the API<br>     */<br>    private $authorization;<br><br>    /**<br>     * @var string The endpoint URL for the OpenAI.com API<br>     */<br>    private $endpoint;<br><br>    /**<br>     * ChatBot constructor.<br>     */<br>    public function __construct()<br>    {<br>        // This token is not real, in case you were thinking what I&#39;m thinking...<br>        $this-&gt;authorization = &#39;sk-bkd04ADr2TXXDGugb2NEWuH3BlbkFJFavL1XJbMZcFIegY5qY&#39;;<br>        $this-&gt;endpoint = &#39;https://api.openai.com/v1/chat/completions&#39;;<br>    }<br><br>    /**<br>     * Send a message to the API and return the response.<br>     *<br>     * @param string $message The message to send<br>     * @return string The response message<br>     * @throws Exception If there is an error in sending the message via cURL<br>     */<br>    public function sendMessage(string $message): string<br>    {<br>        // Read sample data from our JSON file<br>        $jsonSampleData = file_get_contents(&quot;test-data.json&quot;);<br><br>        // Prepare data for sending<br>        $data = [<br>            &#39;messages&#39; =&gt; [<br>                [<br>                    &#39;role&#39; =&gt; &#39;system&#39;,<br>                    &#39;content&#39; =&gt; &#39;You are a kind and helpful customer service member at a PC components store. <br>                    If the user asks how to buy, refer them to our website at https://medium.com/winkhosting.<br>                    If the user asks anything about CPUs or RAM, use exclusively the cpu or ram input in the following JSON string to suggest options:&#39; . $jsonSampleData<br>                ],<br>                [<br>                    &#39;role&#39; =&gt; &#39;user&#39;,<br>                    &#39;content&#39; =&gt; $message<br>                ],<br>            ],<br>            &#39;model&#39; =&gt; &#39;gpt-3.5-turbo&#39;<br>        ];<br><br>        // Set headers for the API request<br>        $headers = [<br>            &#39;Content-Type: application/json&#39;,<br>            &#39;Authorization: Bearer &#39; . $this-&gt;authorization,<br>        ];<br><br>        // Send the request to the API using cURL<br>        $ch = curl_init();<br>        curl_setopt($ch, CURLOPT_URL, $this-&gt;endpoint);<br>        curl_setopt($ch, CURLOPT_POST, 1);<br>        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));<br>        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);<br>        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);<br>        $response = curl_exec($ch);<br><br>        // Check for errors in the API response<br>        if (curl_errno($ch)) {<br>            $error = curl_error($ch);<br>            curl_close($ch);<br>            throw new Exception(&#39;Error sending the message: &#39; . $error);<br>        }<br><br>        curl_close($ch);<br><br>        // Parse the API response<br>        $arrResult = json_decode($response, true);<br>        $resultMessage = $arrResult[&quot;choices&quot;][0][&quot;message&quot;][&quot;content&quot;];<br><br>        // Return the response message<br>        return $resultMessage;<br>    }<br>}</pre><p>As you can see, our class has only one method that receives a statement/question and takes care of sending the information to the corresponding endpoint on <strong>openai.com</strong> to receive a response (<a href="https://api.openai.com/v1/chat/completions"><strong>https://api.openai.com/v1/chat/completions</strong></a>).</p><p>In the configuration of our API request (<strong>the $data array</strong>), we will use the “<strong>gpt-3.5-turbo</strong>” model. This is recommended in terms of cost-effectiveness, but if you have enough funds and courage, you can use the gpt-4 model, which is the latest one with better performance and responsiveness.</p><blockquote>To learn more about the available models, you can visit this link: <a href="https://platform.openai.com/docs/models"><strong>https://platform.openai.com/docs/models</strong></a></blockquote><p>Also, in the same configuration, we will instruct our AI about the role (“<strong>system</strong>” role) it should play, which is to be a “<strong>kind and helpful customer service member</strong>,” and provide other instructions regarding the information it should provide when asked about components like RAM and CPU.</p><blockquote><strong>Important: </strong>Providing clear instructions will result in fewer errors while interacting with a visitor.</blockquote><p>If you’re paying attention, you’ll also notice that we load the content of our dummy file into a variable called <strong>$jsonSampleData</strong> and add it to the content of the role our AI will have. This is done so that it has access to the information and can deliver responses based on the list of products within it.</p><p><strong>System Role</strong></p><pre>[<br>    &#39;role&#39; =&gt; &#39;system&#39;,<br>    &#39;content&#39; =&gt; &#39;You are a kind and helpful customer service member at a PC components store. <br>    If the user asks how to buy, refer them to our website at https://medium.com/winkhosting.<br>    If the user asks anything about CPUs or RAM, use exclusively the cpu or ram input in the following JSON string to suggest options:&#39; . $jsonSampleData<br>]</pre><p>The user message will be added to the $data array associated with the “<strong>user</strong>” role like this:</p><p><strong>User Role</strong></p><pre>[<br>    &#39;role&#39; =&gt; &#39;user&#39;,<br>    &#39;content&#39; =&gt; $message<br>]</pre><p>Once we have our request payload ready to send, we will execute it using <strong>cURL</strong>. If everything goes well, we will receive the response from our AI in <strong>JSON </strong>format. We will transform it into an associative array (thanks to PHP’s magic), and our response will be in the <strong>$arrResult[“choices”][0][“message”][“content”]</strong> entry. Then we extract the text and return it.</p><p>With our class ready, let’s move on to the file responsible for receiving requests from our interface and returning the response to the user.</p><p>The responsibility of this file will be to receive a text string (the message) via a <strong>POST </strong>request from<strong> index.html</strong>, deliver the message to our AI, and return the response as follows:</p><p><strong>requestmanager.php</strong></p><pre>&lt;?php<br><br>// Include the definition of the ChatBot class to be used for our query.<br>require(&quot;ChatBot.php&quot;);<br><br>// Decode the parameters received from the index.html file and store them in the $paramsFetch array.<br>$paramsFetch = json_decode(<br>    file_get_contents(&quot;php://input&quot;),<br>    true<br>);<br><br>$ChatBot = new ChatBot();<br><br>// Send the message to our AI.<br>$resMessage = $ChatBot-&gt;sendMessage($paramsFetch[&quot;message&quot;]);<br><br>// Next, we return the response in JSON format and exit the execution.<br>$jsonResponse = json_encode(array(&quot;responseMessage&quot; =&gt; $resMessage));<br>echo $jsonResponse;<br>exit;</pre><p>This script includes the <strong>ChatBot </strong>class, receives the message, and calls <strong><em>sendMessage()</em></strong>. The returned response is converted to <strong>JSON </strong>and printed to be returned to<strong> index.html</strong>.</p><p>And that’s it! If everything works as it should, and there are no errors, you can start interacting with your AI:</p><p><strong>Our bot!</strong></p><p>Access the URL of your project in your development environment, in my case <a href="http://localhost/ai-chatbot/">http://localhost/ai-chatbot/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-dTeVk3ebh5C4AWRoWpsw.png" /><figcaption>Our bot working</figcaption></figure><p>Write a question or message for the AI and start interacting with it.</p><p>Thank you for reaching this point, and remember that at <a href="https://winkhosting.co/"><strong>Winkhosting.co</strong></a>, we are much more than just hosting!</p><blockquote><strong>P.S.</strong> The PHP code used for this guide was created with the help of AI. 😉</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41bb752f6403" width="1" height="1" alt=""><hr><p><a href="https://medium.com/winkhosting/create-a-chatbot-using-ai-chatgpt-and-php-41bb752f6403">Create a ChatBot using AI, ChatGPT and 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[Creating a desktop app with JavaScript, HTML, CSS and the old faithful Electron]]></title>
            <link>https://medium.com/winkhosting/creating-a-desktop-app-with-javascript-html-css-and-the-old-faithful-electron-55280682e96?source=rss----c578fc6c854f---4</link>
            <guid isPermaLink="false">https://medium.com/p/55280682e96</guid>
            <category><![CDATA[desktop]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[electron]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Camilo Herrera]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 19:54:21 GMT</pubDate>
            <atom:updated>2023-08-31T19:54:21.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*FmwcBsKePBFTTl98bUpQZA.png" /></figure><ul><li>You are a web developer and were asked for a desktop application?</li><li>Did you try to learn specific languages to create desktop applications and failed?</li><li>Did you notice that you are going to stop sleeping and waste quality time with your family and/or pet trying to create desktop applications?</li></ul><p>Say Hell To Da Naw! and learn from our dear friend and her wise words:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*BEquuL2jdkezw4NND66N5Q.jpeg" /></figure><p>And let’s enter together the magical world of <a href="https://www.electronjs.org/"><strong><em>Electron framework</em></strong></a> to create applications with web-oriented languages.</p><h4>Electron, what is it?</h4><p>Electron is a framework and a set of tools that allows you to be a lazy software developer who doesn’t want to learn…, sorry, it allows you to use HTML, CSS and JavaScript to create desktop applications, it achieves this by embedding nodejs and chromium in a single executable file.</p><p>Impressive, right? Electron is a project that has been operating for years and is very stable. Other alternatives have been created over the years, but I’m old and tired and I’m not going to change it. Here are some alternatives in case you are curious and are thinking about the use of resources such as RAM or disk space (Electron is not known for being the best at this) or if you want to publish your application in the App Store of a certain brand that uses a fruit logo:</p><ul><li><a href="http://neutralino.js.org/"><strong>NeutralinoJS</strong></a></li><li><a href="https://nwjs.io/"><strong>NW.js</strong></a></li><li><a href="https://tauri.app/"><strong>Tauri</strong></a></li></ul><h4>Preparing our development environment</h4><blockquote><strong>Warning:</strong> Let’s be clear about something before continuing, I use Windows, because of this, the guide will focus on this operating system. If you use a different one I recommend consulting the specific or equivalent steps for the one you use.</blockquote><p>We are going to start by creating a directory somewhere on our PC in which we will save the files of our project, in my case it will be (remember that it is according to your configuration and preference):</p><pre>D:\electron</pre><p>Next we will install two requirements to use Electron, they are <strong>Node.js</strong> and <strong>npm</strong>.</p><p>You can download<strong> Node.js+npm</strong> by clicking <a href="https://nodejs.org/en"><strong>here</strong></a> and install it following the instructions and running the executable file.</p><p>The installer already includes <strong>npm</strong>, you don’t have to follow additional steps to install it, then start a command prompt and run the following instructions to determine if the requirements are active:</p><pre>PS C:\Users\xxxxx&gt;node -v<br>v18.16.0<br><br>PS C:\Users\xxxxx&gt;npm -v<br>9.5.1</pre><p>If everything goes well, the version of <strong>Node.js</strong> and <strong>npm </strong>installed on your PC will be displayed, otherwise I recommend you perform the process again or determine if an error occurred during the installation (or there is some restriction on your computer).</p><p>For those of you who were successful in this step, stay with me and don’t get too far behind.</p><p>Now, having everything ready, we are going to start our project and install the Electron tools in it.</p><p>We are going to open a command terminal in Windows (powershell terminal if we are more precise), and enter <strong>D:\electron</strong> then create a new directory for our specific project like this:</p><pre>PS C:\Users\xx&gt; cd D:\electron\<br>PS D:\electron&gt; mkdir testapp<br>PS D:\electron&gt; ls<br>Mode                 LastWriteTime         Length Name<br>----                 -------------         ------ ----<br>d-----      30/08/2023  2:30 p. m.                testapp<br><br>PS D:\electron&gt; cd .\testapp\<br>PS D:\electron\testapp&gt;</pre><p>Inside the new <strong>testapp </strong>directory we create the initial structure of our application with the following command:</p><pre>PS D:\electron\testapp&gt; npm init<br><br>This utility will walk you through creating a package.json file.<br>It only covers the most common items, and tries to guess sensible defaults.<br><br>See `npm help init` for definitive documentation on these fields<br>and exactly what they do.<br><br>Use `npm install &lt;pkg&gt;` afterwards to install a package and<br>save it as a dependency in the package.json file.<br><br>Press ^C at any time to quit.<br>package name: (testapp) TestApp<br>Sorry, name can no longer contain capital letters.<br>package name: (testapp)<br>version: (1.0.0)<br>description: My Electron Test App<br>entry point: (index.js)<br>test command:<br>git repository:<br>keywords:<br>author: Camilo Herrera<br>license: (ISC)<br>About to write to D:\electron\testapp\package.json:<br><br>{<br>  &quot;name&quot;: &quot;testapp&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;My Electron Test App&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;author&quot;: &quot;Camilo Herrera&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;<br>}<br><br><br>Is this OK? (yes) yes</pre><p>During the process the basic data of your application will be requested, you can leave the default values for most, but the <strong>description </strong>and the <strong>author</strong> are mandatory.</p><p>Now we are ready to include the Electron functionalities, inside the directory execute the following command:</p><pre>PS D:\electron\testapp&gt; npm install --save-dev electron</pre><p>To run the application using Electron, an additional step is necessary. In the directory a file named <strong>package.json</strong> was created, open the file in a text editor and add an entry in “<strong>scripts</strong>” with the value <strong><em>“start”:”electron.”</em></strong> like this:</p><pre>{<br>  &quot;name&quot;: &quot;testapp&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;My Electron Test App&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>      &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>      &quot;start&quot;: &quot;electron .&quot;<br>  },<br>  &quot;author&quot;: &quot;Camilo Herrera&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;devDependencies&quot;: {<br>    &quot;electron&quot;: &quot;^26.1.0&quot;<br>  }<br>}</pre><p>Don’t forget the comma at the end of the previous line. Save the content of the file to finish.</p><h4>Creating our application</h4><p>Up to this point your basic configuration is ready, now it is necessary to create the files to display the main window of your application, to accomplish this we are going to create two files:</p><ul><li><strong>index.js</strong></li><li><strong>index.html</strong></li></ul><p><strong>index.js</strong> is the entry point of your application, as set in the <strong>package.json</strong> file.</p><p>The content of the file is shown below:</p><p><strong>index.js</strong></p><pre>//This is the way to include modules with Node.js, in this case the <br>//Electron module.<br>//You can learn more about importing modules by searching<br>//information about &quot;CommonJS&quot; modules on the internet<br>const { app, BrowserWindow } = require(&#39;electron&#39;)<br><br>//Create our main windows, here you can set the initial size.<br>const createWindow = () =&gt; {<br>  const win = new BrowserWindow({<br>    width: 800,<br>    height: 600<br>  })<br>  //The HTML file that will be shown, we will create this file in the next section.<br>  win.loadFile(&#39;index.html&#39;)<br>}<br><br>//This is our starting event, once &quot;Ready&quot;, create our main window.<br>app.whenReady().then(() =&gt; {<br>  createWindow()<br>})</pre><p>As an additional step, we are going to add my beloved bulma CSS library, you can download it from its official site <a href="https://bulma.io/"><strong>bulma.io</strong></a><strong> </strong>and save the <strong>bulma</strong> folder (that’s inside the downloaded .zip) in your <strong>testapp </strong>application directory, the folder structure will look like this:</p><pre>D:\electron<br>      \testapp<br>          \bulma<br>          -  index.html<br>          -  index.js<br>          -  package.json<br>          -  package-lock.json<br>          \node_modules</pre><p>Now our <strong>index.html</strong> file, this file will contain the HTML code to be displayed, just like a website… but in your desktop application, do you understand the concept? It’s easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Zr8vUDBb-GUI6VO9zC9SeQ.jpeg" /><figcaption>You smart Electron!</figcaption></figure><p><strong>index.html</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;!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --&gt;<br>    &lt;!-- CSP is a PITA ;). Disabled, don&#39;t try this at home!--&gt;<br>    &lt;meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;&quot;&gt;<br>    &lt;!-- include bulma css --&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;bulma/css/bulma.min.css&quot;&gt;<br>    &lt;title&gt;My Test App&lt;/title&gt;<br>    &lt;script&gt;<br>        window.addEventListener(&#39;load&#39;, (event) =&gt; {<br>            document.querySelector(&quot;.hello&quot;).textContent = &quot;Hello from Electron with bulma css!&quot;;<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;container&quot;&gt;<br>            &lt;div class=&quot;notification is-warning has-text-centered hello&quot;&gt;<br>                <br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/section&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><p>This HTML code loads the bulma css library and creates a notification with a message that is show at the end of the DOM loading process.</p><p>At this point you can also start modifying or adding sections, you can navigate relatively between .html files or use JavaScript libraries just like on a website with script tags like this:</p><pre>&lt;script defer src=&quot;/ruta relativa a mi archivo .js&quot;&gt;&lt;/script&gt;</pre><p>Now you can start the application for the first time, from the same command console execute the following instruction:</p><pre>PS D:\electron\testapp&gt; npm start</pre><p>The result will be something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*RgSF1m_JvfaUww4cyBb7rQ.png" /><figcaption>My first Electron App!</figcaption></figure><p>If you don’t want to show the default window menu (nobody wants that in production, for debugging it can be useful as it allows you to show the developer tools inside the same window.), you can disable it by editing your <strong>index.js</strong> file and adding the following line:</p><pre>win.setMenuBarVisibility(false)</pre><p><strong>index.js without window menu</strong></p><pre>//This is the way to include modules with Node.js, in this case the <br>//Electron module.<br>//You can learn more about importing modules by searching<br>//information about &quot;CommonJS&quot; modules on the internet<br>const { app, BrowserWindow } = require(&#39;electron&#39;)<br><br>//Create our main windows, here you can set the initial size.<br>const createWindow = () =&gt; {<br>  const win = new BrowserWindow({<br>    width: 800,<br>    height: 600<br>  })<br><br>  //disable menu bar<br>  win.setMenuBarVisibility(false)<br>  //The HTML file that will be shown, we will create this file in the next section.<br>  win.loadFile(&#39;index.html&#39;)<br>}<br><br>//This is our starting event, once &quot;Ready&quot;, create our main window.<br>app.whenReady().then(() =&gt; {<br>  createWindow()<br>})</pre><h4>Packaging our application</h4><p>Now we are going to compile the application into an executable and attach an icon to it.</p><p>Create or download a Windows icon (.ico format) and save it in a directory with an appropriate name inside <strong>testapp</strong>, for example we will call the directory <strong>icons</strong>, the directory structure will look like this:</p><pre>D:\electron<br>      \testapp<br>          \icons<br>              -  app.ico<br>          \bulma<br>          \node_modules<br>          -  index.html<br>          -  index.js<br>          -  package.json<br>          -  package-lock.json</pre><p>Next we go to the<strong> index.js</strong> file and add the path of the icon like this:</p><pre>icon: &#39;icons/app.ico&#39;</pre><p><strong>index.js with icon path</strong></p><pre>//This is the way to include modules with Node.js, in this case the <br>//Electron module.<br>//You can learn more about importing modules by searching<br>//information about &quot;CommonJS&quot; modules on the internet<br>const { app, BrowserWindow } = require(&#39;electron&#39;)<br><br>//Create our main windows, here you can set the initial size.<br>const createWindow = () =&gt; {<br>  const win = new BrowserWindow({<br>    width: 800,<br>    height: 600,<br>    icon: &#39;icons/app.ico&#39;<br>  })<br><br>  //disable menu bar<br>  win.setMenuBarVisibility(false)<br>  //The HTML file that will be shown, we will create this file in the next section.<br>  win.loadFile(&#39;index.html&#39;)<br>}<br><br>//This is our starting event, once &quot;Ready&quot;, create our main window.<br>app.whenReady().then(() =&gt; {<br>  createWindow()<br>})</pre><p>Now run the application, the icon should be displayed on the taskbar and at the top left of the window.</p><p>To package the application and generate an executable we will have to install <a href="https://www.electronforge.io/"><strong>Electron Forge</strong></a>, this is the most common solution to carry out this process.</p><p>Inside the <strong>testapp </strong>directory run the following commands:</p><pre>PS D:\electron\testapp&gt; npm install --save-dev @electron-forge/cli<br>PS D:\electron\testapp&gt; npx electron-forge import</pre><p>The result of the commands and a final thank you message for using Electron Forge will be displayed.</p><blockquote>Run the application again with the initial command, you will notice that now the one in charge of the process is Electron Forge and not Electron directly, the process will take a few more seconds but the result will be the same.</blockquote><p>To create an executable that can be distributed, run the following command in the same console:</p><pre>PS D:\electron\testapp&gt; npm run make</pre><p>It is important to me to show you the output of the command in the console, you should see something like this:</p><pre>&gt; testapp@1.0.0 make<br>&gt; electron-forge make<br><br>✔ Checking your system<br>✔ Loading configuration<br>✔ Resolving make targets<br>  › Making for the following targets: squirrel<br>✔ Running package command<br>  ✔ Preparing to package application<br>  ✔ Running packaging hooks<br>    ✔ Running generateAssets hook<br>    ✔ Running prePackage hook<br>  ✔ Packaging application<br>    ✔ Packaging for x64 on win32 [4s]<br>  ✔ Running postPackage hook<br>✔ Running preMake hook<br>✔ Making distributables<br>  ✔ Making a squirrel distributable for win32/x64 [33s]<br>✔ Running postMake hook<br>  › Artifacts available at: D:\electron\testapp\out\make</pre><p>Now you can enter the path (in my case) <strong>D:\electron\testapp\out</strong> and there you will find two directories named <strong>make </strong>and <strong>testapp-win32-x64</strong>, inside <strong>testapp-win32-x64</strong> are the files you want to use to distribute your application.</p><p>You will notice that the executable file named <strong>testapp.exe</strong> does not have the icon that we initially defined, this is expected, we are going to fix it by editing a new file that was created by Electron Forge in testapp, the file has the name <strong>forge.config.js</strong>, edit the file and add in the “<strong>packagerConfig</strong>” section a line with the following content:</p><pre>icon: &#39;icons/app&#39; // file type is not required</pre><p>The complete file will look like this (remember that it is JSON format and you must write a comma separating each item:</p><p><strong>forge.config.js with icon setting</strong></p><pre>module.exports = {<br>  packagerConfig: {<br>    asar: true,<br>    icon: &#39;icons/app&#39; // no se requiere la extensión del archivo .ico<br>  },<br>  rebuildConfig: {},<br>  makers: [<br>    {<br>      name: &#39;@electron-forge/maker-squirrel&#39;,<br>      config: {},<br>    },<br>    {<br>      name: &#39;@electron-forge/maker-zip&#39;,<br>      platforms: [&#39;darwin&#39;],<br>    },<br>    {<br>      name: &#39;@electron-forge/maker-deb&#39;,<br>      config: {},<br>    },<br>    {<br>      name: &#39;@electron-forge/maker-rpm&#39;,<br>      config: {},<br>    },<br>  ],<br>  plugins: [<br>    {<br>      name: &#39;@electron-forge/plugin-auto-unpack-natives&#39;,<br>      config: {},<br>    },<br>  ],<br>};</pre><p>Save the file and run the command again to create the files to distribute:</p><pre>PS D:\electron\testapp&gt; npm run make</pre><p>Once the process is finished, enter the <strong>testapp-win32-x64 </strong>directory and run <strong>testapp.exe</strong>, you will see the icon used in the taskbar and in the window.</p><blockquote>Up to this point your files would be ready for distribution, except for the signing of the application if you plan to distribute it in the Microsoft store, it is an animal completely outside the scope of this guide, if you need to do it check the Microsoft documentation to carry out the process.</blockquote><h4>Creating an installer with Inno Setup for Windows</h4><p>Now that we’ve got everything ready, we can’t just be vulgar software developers distributing our app inside a .zip right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*VpD01mnlxhcFhcvS2X4UpA.gif" /><figcaption>Inside a .zip? I’ve never done it! (yeah right)</figcaption></figure><p>Inno Setup is a great tool for creating installers on Windows, you can download it from <a href="https://jrsoftware.org/isinfo.php"><strong>here</strong></a>. Install it on your PC and we will proceed with the creation of our installer.</p><p>Run Inno Setup, at startup a welcome window will be displayed with some options, select “<strong>Create a new script file using the Script Wizard</strong>” and click the “OK” button, in the new window displayed click “Next”, it will be displayed a form, enter the data as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*lL6A4b6lbSFN1NLkU2BrHg.png" /><figcaption>Inno Setup Script Wizard basic info</figcaption></figure><p>Click “Next” to continue, some data will be shown by default, do not change it unless you know what you are doing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*6CfbIyCA9aKP2KMwUXygwg.png" /><figcaption>Install directory settings</figcaption></figure><p>Click “Next” again and the files to be packaged in the installer will be requested, in “<strong>Application main executable file:</strong>” select the file<strong> testapp.exe </strong>created in the directory <strong>D:\electron\testapp\out\testapp-win32-x64</strong>.</p><p>In the “<strong>Other application files</strong>” section, click the “Add folder” button and select the “<strong>D:\electron\testapp\out\testapp-win32-x64</strong>” directory, this will include all the dependencies and additional files used by our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*Ym0-8FfeBUEelfkIY74icA.png" /><figcaption>Files to be included in the installer</figcaption></figure><p>Click the “Next” button and in the next step uncheck the “<strong>Associate a file type to the main executable</strong>” option as it is not necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*4zmhjdMxX5hQhCuuPq4rpw.png" /><figcaption>Associate file type to app</figcaption></figure><p>Again click on “Next” and options for creating shortcuts in Windows will be shown, leave the default options, do not change them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*pcBRC73oVfSnC_RB9Mm1IQ.png" /><figcaption>Application Shortcuts</figcaption></figure><p>Clicking on “Next” will show options to include licenses and information before and after the installation, for now we do not need them, leave the default values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*Kbj52L8y-QGgD0D7kDdZyQ.png" /><figcaption>Installer documentation</figcaption></figure><p>Click “Next” and the installer execution permission options will be displayed, this allows the user to decide whether to install for everyone or just for their session. Leave the default values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*vf1p8SfKQaoYLBll0j2eZw.png" /><figcaption>Install mode</figcaption></figure><p>Clicking on “Next” will show the language selector for the installer, by default we will leave “English”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*43aypZJMcqRU01p5ePsAbA.png" /><figcaption>Setup Languages</figcaption></figure><p>Click “Next”, options for the installer compiler will be shown, in the field “<strong>Custom compiler output folder</strong>” we will set the path <strong>D:\electron\testapp\out\installer</strong> (create the <strong>installer </strong>directory inside the out directory, you can creat it from the directory selector).</p><p>In the “<strong>Compiler output base file name</strong>” field write “<strong>testapp</strong>” and in the “<strong>Custom Setup icon file</strong>” field use the icon of our application in the path <strong>D:\electron\testapp\icons\app.ico</strong> (or the path where you saved the ico file on your PC).</p><p>Do not type password for the installer, it is not necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*dOnh-MfPwlJVQHBaTp1LWQ.png" /><figcaption>Compiler Settings</figcaption></figure><p>Click “Next”, then an option to create the installer compiler script will be shown (you don’t have to understand it but in general, what it indicates is that the script that Inno Setup will use to generate the installer will be more or less user friendly to be edited manually). Leave the default value and don’t ask further questions!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*2s5q91o2nKSY31rvr85-Tw.png" /><figcaption>Inno Setup Preprocessor</figcaption></figure><p>Click “Next” and the final message will be displayed, then click “Finish” to start the installer creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*Jsm12Aod_mLG2eZC_zKxDw.png" /><figcaption>Final step</figcaption></figure><p>Clicking the “Finish” button will show the script to be used to generate the installer and a message will appear asking if you want to carry out the process. Click “Yes”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*I6qKrKv6RpjjnFMSuKd3KA.png" /><figcaption>Installer creation script</figcaption></figure><p>Now Inno Setup will ask you if you want to save the script to edit it in the future, click “yes” and save in a path of your choice.</p><p>The installer creation process will start and the progress will be displayed at the bottom of the Inno Setup window. Once finished, go to the <strong>D:\electron\testapp\out\installer</strong> directory and you will find the installer file, run it and follow the steps on screen.</p><p>The result will be your application installed in Windows, just like any pro top tier software developer can!.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*8epxqMQuqBDE92qE6cnO3A.png" /><figcaption>You made it!</figcaption></figure><p>And that’s it, as always, remember that <a href="https://winkhosting.com/"><strong>Winkhosting.co</strong></a> is much more than web hosting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55280682e96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/winkhosting/creating-a-desktop-app-with-javascript-html-css-and-the-old-faithful-electron-55280682e96">Creating a desktop app with JavaScript, HTML, CSS and the old faithful Electron</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[Server monitoring with PHP and Bash Scripts]]></title>
            <link>https://medium.com/winkhosting/server-monitoring-with-php-and-bash-scripts-c078616a6e2f?source=rss----c578fc6c854f---4</link>
            <guid isPermaLink="false">https://medium.com/p/c078616a6e2f</guid>
            <category><![CDATA[shell-script]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Camilo Herrera]]></dc:creator>
            <pubDate>Mon, 29 May 2023 15:09:50 GMT</pubDate>
            <atom:updated>2023-05-29T15:09:50.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U9I0SqLf_RAVqMok" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We’re back!, I’m working on a service to monitor our servers and I want to share some concepts and ideas with you, my dear reader, a basic implementation that you can use if you are planning something similar.</p><h4><strong>Why do I require a custom solution to monitor my servers?</strong></h4><p>I like your question, your question is one of those… good questions. In my case, because I want something specialized for our servers and we want to release it as a product to our customers.</p><p>Your needs may be different but I recommend you explore this option, despite the fact that there are lots of solutions already available and much more advanced (bearing in mind that the greater the number of features, the complexity increases and the technical and knowledge requirements as well).</p><h4>The basic components</h4><p>In this post we will cover the process of creating the Bash script that will capture the information from our server and send it to a central repository. We will also explore a web service that will be receiving the telemetry data and it will also store it as plain files on a directory.</p><p>We will not cover the presentation of information. I leave it to your imagination this time. (You have the power to do it boy!).</p><p>Let’s start with the bash script:</p><h4>Requirements</h4><p>Our servers use Linux, we will create this script using Ubuntu 22.04 LTS. and the script will monitor the following information:</p><ul><li>Load and Uptime every 10 seconds</li><li>Storage every 24 hours</li><li>RAM usage every 30 seconds</li><li>Top 10 processes using CPU every 5 minutes</li></ul><p>The commands to be used to capture this information will be the following:</p><h4>Load and Uptime</h4><p>We will check the load and uptime in a simple way with the “uptime” command from the server command console:</p><pre>&gt; uptime<br><br> 09:32:48 up 296 days,  3:01,  2 users,  load average: 1.92, 1.23, 0.97</pre><p>This command displays the time the server has been running since the last reboot, the number of active users, and the average processing load for the last 1, 5, and 15 minutes.</p><h4>Storage</h4><p>Storage can be queried as follows with the “df -h” command:</p><pre>&gt; df -h<br><br>Filesystem      Size  Used Avail Use% Mounted on<br>devtmpfs        384M     0  384M   0% /dev<br>tmpfs           403M     0  403M   0% /dev/shm<br>tmpfs           403M   42M  362M  11% /run<br>tmpfs           403M     0  403M   0% /sys/fs/cgroup<br>/dev/sda         25G   12G   12G  49% /<br>/dev/sdb         25G  4.2M   24G   1% /home2<br>/dev/loop0      915M  804K  867M   1% /tmp<br>tmpfs            81M     0   81M   0% /run/user/0</pre><p>When executed, the detected storage devices are shown with their respective mount point, total and used capacity in Megabytes.</p><h4>RAM usage</h4><p>RAM usage can be checked as follows with the “free -m” command:</p><pre>&gt; free -m<br><br>              total        used        free      shared  buff/cache   available<br>Mem:            804         533          82          50         188         102<br>Swap:             0           0           0</pre><p>The command will display the server’s RAM, Swap usage, free memory and cache</p><h4>Top 10 processes that use CPU</h4><p>This command is more elaborate, it requires the combination of three basic commands to sort, filter and display the 10 processes with the highest CPU usage like this:</p><pre>&gt; ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10<br><br>%CPU     PID USER     COMMAND<br> 0.4      75 root     [kswapd0]<br> 0.3 3623591 mysql    /usr/sbin/mysqld<br> 0.1 3831215 root     lfd - sleeping<br> 0.1    1079 root     /usr/libexec/platform-python -Es /usr/sbin/tuned -l -P<br> 0.0       9 root     [mm_percpu_wq]<br> 0.0     839 root     /usr/lib/systemd/systemd-logind<br> 0.0     838 root     /usr/sbin/NetworkManager --no-daemon<br> 0.0     831 root     [ext4-rsv-conver]<br> 0.0     830 root     [jbd2/loop0-8]</pre><p>First we will use the “ps” command to display cpu usage, process id, user, and arguments used. Next we order the list by the first column with the “sort” command and finally we filter to leave only the first 10 records with the “head” command.</p><h4>The file</h4><p>Let’s start by creating a file named “servermon.sh”. You can use the name you want, it is only necessary to keep it in mind during the creation process. The initial file will look like this:</p><p><strong>servermon.sh (init)</strong></p><pre>#!/bin/bash</pre><p>The first line indicates the interpreter to use, normally this value should not be changed. Now we go with the initial capture of information.</p><h4>Data collection</h4><p>To capture the result of the execution of the commands that we are going to use, we will send the console output to a text file like this:</p><p><strong>servermon.sh (data collection)</strong></p><pre>#!/bin/bash<br><br># Temp storage dir<br>DIRTMP=/tmp<br><br># uptime and load<br>uptime &gt; $DIRTMP/uptime.log<br><br># storage<br>  df -h &gt; $DIRTMP/storage.log<br><br># memory usage<br>free -m &gt; $DIRTMP/memoryusage.log<br><br># top 10 cpu<br>ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10 &gt; $DIRTMP/top10cpu.log</pre><p>We also create a variable that contains the temporary directory to save the captured files, you can use the directory of your choosing, in this case we will use /tmp and will be updated for each data submission, it is not necessary to save them indefinitely.</p><h4>Capture loop</h4><p>The capture loop will allow us to check the information periodically, for each type of query we will define a customizable interval since it is not necessary (or at least in this case) to check the storage every 3 seconds. But we are interested in checking the server load at shorter intervals.</p><p>Let’s define the timers for collecting information like this:</p><p><strong>servermon.sh (loop y timers)</strong></p><pre>#!/bin/bash<br><br># Temp storage dir<br>DIRTMP=/tmp<br><br># Timers (in seconds)<br># Storage timer<br>STORAGETIMER=3600<br># RAM timer<br>RAMTIMER=60<br># CPU timer<br>CPUTOPTIMER=300<br># Uptime timer<br>UPTIMETIMER=5<br><br># Tickers<br>STORAGETICKER=0<br>RAMTICKER=0<br>CPUTOPTICKER=0<br>UPTIMETICKER=0<br><br># Our main loop<br>while true<br>do<br><br>  # Ticker update every second<br>  ((STORAGETICKER += 1))<br>  ((RAMTICKER += 1))<br>  ((CPUTOPTICKER += 1))<br>  ((UPTIMETICKER += 1))<br><br>  # If ticker reaches the limit to report information<br>  if [ $STORAGETICKER == $STORAGETIMER ]; then<br>    # ticker reset<br>    ((STORAGETICKER = 0))<br>    # Capture info<br>    df -h &gt; $DIRTMP/storage.log<br>    rm -f $DIRTMP/storage.log<br>  fi<br><br>  # Check RAM.<br>  if [ $RAMTICKER == $RAMTIMER ]; then<br>      ((RAMTICKER = 0))<br>      free -m &gt; $DIRTMP/memoryusage.log<br>      rm -f $DIRTMP/memoryusage.log<br>  fi<br><br>  # Check Top 10 + CPU<br>  if [ $CPUTOPTICKER == $CPUTOPTIMER ]; then<br>      ((CPUTOPTICKER = 0))<br>      ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10 &gt; $DIRTMP/top10cpu.log<br>      rm -f $DIRTMP/top10cpu.log<br>  fi<br><br>  # Uptime and load<br>  if [ $UPTIMETICKER == $UPTIMETIMER ]; then<br>      ((UPTIMETICKER = 0))<br>      uptime &gt; $DIRTMP/uptime.log<br>      rm -f $DIRTMP/uptime.log<br><br>  fi<br><br>  # Wait a second...<br>  sleep 1<br><br>done</pre><p>As you can see, running this script will periodically capture CPU, RAM, Uptime/Load and Storage information to a flat file.</p><p>At the end of each cycle, the file that contains the information is deleted. If you only want to keep the files to check them later, you can remove or comment the deletion line and assign a variable text string to the file name (the date and time, for example) to maintain files with historical data. Since in this case we plan to send the information to a central server, we will not store files locally.</p><p>Now we are going to create the web service with PHP to receive the information and we will adjust the bash script to send the files.</p><h4>PHP endpoint/script</h4><p>We are going to create a “hack and slash” kind of script as a demo, simple, fast to receive the files and store them.</p><h4>Requirements</h4><p>You must have a development environment compatible with PHP 8.x to create this script, keep in mind that our bash script must also have access within the local network or Internet to the URL of the PHP script we are going to create to send the files to it.</p><h4>The file</h4><p>In our case we create a <strong>/storeinfo/ </strong>directory at the root of our web server directory and we will create a file and call it <strong>index.php</strong>, also create a <strong>/files</strong> directory inside <strong>/storeinfo/</strong>, this will be used to save the received files.</p><p>The <strong>index.php</strong> file will look like this:</p><pre>&lt;?php<br><br>//Security token to authenticate the access to this script.<br>$_TOKEN = &quot;f66dc5a4-f668-40d6-9b31-7d5d7c947985&quot;;<br><br>//Received files storage path.<br>$_SAVEPATH = __DIR__ . &quot;/files&quot;;<br><br>//Checks if a token was received over POST, if not the script ends.<br>if (!isset($_POST[&quot;token&quot;])) {<br>    echo &quot;Token not found, you need a valid token.&quot;;<br>    exit;<br>}<br><br>//Checks if the token is valid, if not the script ends.<br>if ($_POST[&quot;token&quot;] != $_TOKEN) {<br>    echo &quot;The token is not valid.&quot;;<br>    exit;<br>}<br><br>//Checks if there is a file in the request to be stored.<br>if (!isset($_FILES)) {<br>    echo &quot;There is no file to be stored, please check that the request was made over POST and that it includes a file.&quot;;<br>    exit;<br>}<br><br>//Creates the full path where the file will be stored, it adds date and time to the filename.<br>$_SAVEPATH = $_SAVEPATH . &quot;/&quot; . date(&quot;Ymdhis&quot;) . &quot;_&quot; . basename($_FILES[&#39;data&#39;][&#39;name&#39;]);<br><br><br>//Moves the file to the $_SAVEPATH, and shows a message according to the operation result.<br>if (!move_uploaded_file($_FILES[&#39;data&#39;][&#39;tmp_name&#39;], $_SAVEPATH)) {<br>    echo &quot;It was not possible to move the file to the path {$_SAVEPATH}&quot;;<br>    exit;<br>} else {<br>    echo &quot;File saved at {$_SAVEPATH}&quot;;<br>    exit;<br>}</pre><p>First we define a token to validate that the client sending the information is authorized and a save directory to store the files received.</p><p>The received files will be saved with a name format like this <strong><em>“&lt;yyymmddhhis&gt;_&lt;original name&gt;”</em></strong> in the <strong>/files </strong>directory.</p><p>Now that we have our php file to receive data, let’s adjust the bash script so that it can send data to it. For this we are going to add the curl command as shown below:</p><p><strong>cURL (POST) Command</strong></p><pre>curl -F &quot;data=@$DIRTMP/storage.log&quot; -F &quot;token=$TOKEN&quot; http://127.0.0.1/storeinfo/index.php</pre><p>The command objective is to send a POST request adding the content of the file using <strong>data=&lt;file path&gt;</strong> and <strong>token=&lt;token for authentication&gt;</strong> to the URL <a href="http://127.0.0.1/storeinfo/index.php"><strong>http://127.0.0.1/storeinfo/index.php</strong></a></p><p>The -F parameter tells cURL to treat each of the parameters as part of a form to be submitted using POST.</p><p>The final bash script will look like this:</p><p><strong>servermon.sh (final)</strong></p><pre>#!/bin/bash<br><br># Temp storage dir<br>DIRTMP=/tmp<br><br># Timers (in seconds)<br># Storage timer<br>STORAGETIMER=3600<br># RAM timer<br>RAMTIMER=60<br># CPU timer<br>CPUTOPTIMER=300<br># Uptime timer<br>UPTIMETIMER=5<br><br># Tickers<br>STORAGETICKER=0<br>RAMTICKER=0<br>CPUTOPTICKER=0<br>UPTIMETICKER=0<br><br># Our main loop<br>while true<br>do<br><br>  # Ticker update every second<br>  ((STORAGETICKER += 1))<br>  ((RAMTICKER += 1))<br>  ((CPUTOPTICKER += 1))<br>  ((UPTIMETICKER += 1))<br><br>  # If ticker reaches the limit to report information<br>  if [ $STORAGETICKER == $STORAGETIMER ]; then<br>    # ticker reset<br>    ((STORAGETICKER = 0))<br>    # Capture info<br>    df -h &gt; $DIRTMP/storage.log<br>    curl -F &quot;data=@$DIRTMP/storage.log&quot; -F &quot;token=$TOKEN&quot; $URL<br>    rm -f $DIRTMP/storage.log<br>  fi<br><br>  # Check RAM.<br>  if [ $RAMTICKER == $RAMTIMER ]; then<br>      ((RAMTICKER = 0))<br>      free -m &gt; $DIRTMP/memoryusage.log<br>      curl -F &quot;data=@$DIRTMP/memoryusage.log&quot; -F &quot;token=$TOKEN&quot; $URL<br>      rm -f $DIRTMP/memoryusage.log<br>  fi<br><br>  # Check Top 10 + CPU<br>  if [ $CPUTOPTICKER == $CPUTOPTIMER ]; then<br>      ((CPUTOPTICKER = 0))<br>      ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10 &gt; $DIRTMP/top10cpu.log<br>      curl -F &quot;data=@$DIRTMP/top10cpu.log&quot; -F &quot;token=$TOKEN&quot; $URL<br>      rm -f $DIRTMP/top10cpu.log<br>  fi<br><br>  # Uptime and load<br>  if [ $UPTIMETICKER == $UPTIMETIMER ]; then<br>      ((UPTIMETICKER = 0))<br>      uptime &gt; $DIRTMP/uptime.log<br>      curl -F &quot;data=@$DIRTMP/uptime.log&quot; -F &quot;token=$TOKEN&quot; $URL<br>      rm -f $DIRTMP/uptime.log<br><br>  fi<br><br>  # Wait a second...<br>  sleep 1<br><br>done</pre><p>For each type of information to be reported, a new line was added so that the file can be sent via cURL to the URL of the service where our PHP file is located.</p><p>Now we are ready, with this it would be enough to capture the information and send it to a central server for storage or processing.</p><p>You can try as follows:</p><h4>Bash script</h4><pre># open a terminal on your linux test server (where the script servermon.sh is located and run:<br>chmod +x servermon.sh<br># now start the script:<br>./servermon.sh</pre><p>If all goes well (and I hope it goes well…), the result of the submissions will be displayed after a few seconds (depending on the submission interval that you set on the bash script).</p><p>Now, on the web server, you can go into the /files directory and you will find files with names like these:</p><pre>/files<br>  20230424043142_uptime.log<br>  20230424043242_uptime.log</pre><p>Each file will contain the information reported by the server for each type of monitored resource.</p><p>At this point what is left is to process the information within the files and decide what to do with it on the central server.</p><p>Thanks for getting to this point. Remember that at <a href="https://winkhosting.co/"><strong>Winkhosting.co</strong></a><strong> </strong>we are much more than hosting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c078616a6e2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/winkhosting/server-monitoring-with-php-and-bash-scripts-c078616a6e2f">Server monitoring with PHP and Bash Scripts</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[Why you should switch from shared hosting to a virtual private server (VPS)]]></title>
            <link>https://medium.com/winkhosting/why-you-should-switch-from-shared-hosting-to-a-virtual-private-server-vps-697197a3bc6a?source=rss----c578fc6c854f---4</link>
            <guid isPermaLink="false">https://medium.com/p/697197a3bc6a</guid>
            <category><![CDATA[vps-hosting]]></category>
            <category><![CDATA[vps]]></category>
            <dc:creator><![CDATA[andrea almanza]]></dc:creator>
            <pubDate>Fri, 19 May 2023 13:51:15 GMT</pubDate>
            <atom:updated>2023-05-19T13:51:15.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tRZVHG56UxQ57xAa0WQ6lQ.jpeg" /></figure><p>When it comes to hosting your website, it is important to consider the different options available. One of the key points to consider is the choice between shared hosting and a virtual private server (VPS). Although shared hosting is a popular choice for smaller websites, a VPS offers a number of benefits and advantages that can significantly improve the performance and security of your site. In this article, we’ll explore the top reasons why you should consider switching from shared hosting to a VPS.<br>Dedicated resources:</p><ol><li><strong>Dedicated resources:</strong><br>One of the biggest limitations of shared hosting is that server resources, such as RAM, storage space, and processing power, are shared among multiple users. This can negatively affect the performance of your website, especially if you experience traffic spikes or if other sites on the same server consume too many resources. With a VPS, you get dedicated resources, which means you have exclusive access to the amount of RAM, storage and processing power you have contracted for. This ensures more stable and consistent performance for your website.</li><li><strong>Greater scalability:</strong><br>If you have growth plans for your website or if you expect a long-term increase in traffic, a VPS gives you greater scalability compared to shared hosting. With a VPS, you can scale vertically by increasing the resources allocated to your server, such as RAM or storage capacity, without negatively affecting other users. This allows you to easily adapt to the changing needs of your website and ensure optimal performance at all times.</li><li><strong>Greater control and customization:</strong><br>With shared hosting, you are limited in terms of the configurations and customizations you can make to the server. In contrast, with a VPS, you have complete control over your server environment. You can install the operating system of your choice, configure security settings according to your specific needs, and adjust the server configuration to optimize your website’s performance. This gives you significant flexibility and freedom to tailor your server to your exact requirements.</li><li><strong>Better security:</strong><br>Online security is a growing concern, and a VPS can provide an additional level of protection for your website. With shared hosting, if another site on the same server is vulnerable to attack or suffers a security breach, there is a chance that your site will also be affected. However, with a VPS, the environments are isolated, which means that security issues from other sites will not affect you. Additionally, you have the option to implement custom security measures and set up firewalls to protect your site from online threats.</li><li><strong>Better performance and uptime:</strong><br>Performance and uptime are crucial aspects for any website. With a VPS, you get better performance compared to shared hosting, since you don’t share resources with other users. This translates into faster load times and a smoother experience for your website visitors. By having dedicated resources, your site can handle higher traffic volumes without experiencing slowdowns or server crashes.</li></ol><p><strong>Conclusion</strong><br>Switching from shared hosting to a VPS can offer a number of significant benefits for your website. You get dedicated resources, greater scalability, control and customization, better security, improved performance and more reliable uptime. If your website is growing, has specific configuration or security requirements, or you simply want to provide a faster and more reliable user experience, switching to a VPS may be the ideal option. Evaluate your needs and consider your website’s future growth potential to make an informed decision about migrating to a VPS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=697197a3bc6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/winkhosting/why-you-should-switch-from-shared-hosting-to-a-virtual-private-server-vps-697197a3bc6a">Why you should switch from shared hosting to a virtual private server (VPS)</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[Introduction to the programming language: Python]]></title>
            <link>https://medium.com/winkhosting/introduction-to-the-programming-language-python-fde133a24c8?source=rss----c578fc6c854f---4</link>
            <guid isPermaLink="false">https://medium.com/p/fde133a24c8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[andrea almanza]]></dc:creator>
            <pubDate>Tue, 09 May 2023 15:35:32 GMT</pubDate>
            <atom:updated>2023-05-09T15:35:32.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBF4bGc50KedOqbz1HP89w.jpeg" /></figure><p>In this post, we will cover everything you need to know to start programming in Python, from the basics of syntax to some advanced features offered by this language.</p><p><strong>What is Python?</strong></p><p>Python is a high-level interpreted, multi-paradigm, object-oriented programming language. It was created in the late 1980s by Guido van Rossum and has become one of the most popular languages today, especially in the field of data science and artificial intelligence. Python is known for its clear and concise syntax, which makes it easy to read and write, and it has a large number of libraries and tools that make it very versatile and efficient in the development of applications in various fields.</p><p><strong>Advantages of using Python</strong></p><p>Python is a very popular and widely used programming language in a variety of fields, including data science, artificial intelligence, web development, game development, and more. Some of the advantages of Python include:</p><ol><li>Simple, easy-to-read syntax.</li><li>Extensive library of predefined modules and packages.</li><li>Can be used on a variety of operating systems.</li><li>Object-oriented programming language.</li><li>Large community of developers who share resources and provide technical support.</li></ol><p><strong>Disadvantages of using Python</strong></p><p>Although Python is a very popular programming language used in several areas, there are some disadvantages that may affect its use in certain situations.</p><ol><li><strong>Execution speed:</strong> Despite being a high-level programming language, Python is relatively slow compared to other languages such as C++ or Java. This can be a problem in applications that require high processing speed or where response time is critical.</li><li><strong>Memory consumption:</strong> Python tends to consume more memory than other languages, which can be a problem in resource-constrained systems or when handling large data sets.</li><li><strong>Dynamic typing:</strong> Although the nature of Python’s dynamic typing can make it easy to learn and fast to develop prototypes, it can be a problem in large, complex projects where a high level of control over data types needs to be maintained.</li><li><strong>Dependencies:</strong> When using third-party libraries in Python, there can be compatibility issues or conflicts between different versions of the libraries, which can be difficult to manage.</li><li><strong>Interpretation:</strong> Python is an interpreted language, which means that its code is executed line by line instead of being compiled before execution. This can affect performance in high-demand applications.</li><li><strong>Limitations in mobile application development:</strong> Python is not the primary programming language for mobile application development, as it does not support all mobile development platforms and tools.</li></ol><p>It is important to note that many of these disadvantages can be addressed by using appropriate tools, such as Just-in-Time (JIT) compilers, Python-specific frameworks, and good project planning. Overall, Python remains an excellent choice for a wide variety of applications and projects.</p><p><strong>Installing Python</strong></p><p>To install Python on your system, you can follow the steps below:</p><ol><li>Download the Python installer from the official Python website:<a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a></li><li>Select the version of Python you want to download. If you are a beginner, we recommend downloading the latest stable version of Python 3.</li><li>Run the installer and follow the on-screen instructions to complete the installation.</li></ol><p><strong>Basic Python syntax</strong></p><p><strong>-Variables in Python</strong></p><p>In Python, a variable is a container used to store values, such as numbers, text, or complex data, such as lists and dictionaries. Assigning values to variables is a common task in Python programming, and is done using the assignment operator “=”.</p><p><strong>-Operators in Python</strong></p><p>Python has a variety of operators that can be used to perform calculations and operations on variables. Some of the most common operators include:<br>Arithmetic operators: +, -, *, /, %.<br>Comparison operators: ==, !=, &gt;, &lt;, &gt;=, &lt;=, &lt;=<br>Logical operators: and, or, not.</p><p><strong>-Control structures in Python</strong></p><p>Control structures in Python are used to control the execution flow of a program. Some of the most common control structures include:</p><p>If-else: used to execute a block of code if a condition is met, and another block of code if the condition is not met.</p><p>Loops: used to repeat a block of code until a condition is met. The most common loops in Python are the “for” and “while” loops.</p><p><strong>-Functions in Python</strong></p><p>In Python, functions are reusable blocks of code that perform a specific task. Functions in Python are defined by the “def” keyword and can have zero or more arguments (parameters) that are passed to the function when it is called. Some of the most common functions in Python include:</p><ol><li><strong>print():</strong> to print to the console or to an output file.</li><li><strong>input():</strong> to get user input from the keyboard.</li><li><strong>len():</strong> to get the length of a string, list, or other collection of objects.</li><li><strong>range():</strong> to create a sequence of integers.</li><li><strong>type():</strong> to get the type of an object.</li><li><strong>sum(): </strong>to sum all the elements of a list or collection.</li><li><strong>max():</strong> to get the maximum value of a list or a collection.</li><li><strong>min():</strong> to get the minimum value of a list or a collection.</li><li><strong>abs():</strong> to get the absolute value of a number.</li><li><strong>round():</strong> to round a number.</li></ol><p>In addition, it is also possible to define custom functions to perform specific tasks according to the user’s needs. Custom functions can be very useful to encapsulate the logic of a task in one place and reuse it in different parts of the program.</p><p><strong>To summarize</strong><br> Python is a versatile and easy-to-use programming language that offers a wealth of tools and libraries to facilitate programming in various applications. Therefore, it is a good choice for you to learn to program or work in fields related to data science and machine learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fde133a24c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/winkhosting/introduction-to-the-programming-language-python-fde133a24c8">Introduction to the programming language: Python</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>
    </channel>
</rss>