your php installation be missing the MySQL extension WordPress CPANEL

I download the last wordpress and try install, but wp show this

Your PHP installation appears to be missing the MySQL extension which
is required by WordPress

This happend wen i change to PHP 7.x

When i change to 5.6 work fine but i need use PHP 7.x

error

CPANEL

phpv

PHP INFO Show me thist but i select and saved PHP 7
phopinfi

httpd – Checking php configuration

One of our ticketing systems uses php as the application and it is being hosted with httpd. Recently, it has been reported that the httpd service has been intermittently going up and down. From further investigation, I found out that there were no php modules installed, and the mpm used was mpm-event and not mpm-prefork. Also, many modules that were not used were not commented out from 00-base.conf file in /usr/local/httpd/conf.modules.d.

I checked the httpd logs and found that these were the errors :

AH00493: SIGUSR1 received.  Doing graceful restart

These are the full logs (from 22 – 29th) that shows the intermittent http service connectivity :

(Tue Sep 22 03:40:01.778015 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00493: SIGUSR1 received.  Doing graceful restart
(Tue Sep 22 03:40:01.978594 2020) (lbmethod_heartbeat:notice) (pid 15291:tid 140357203278016) AH02282: No slotmem from mod_heartmonitor
(Tue Sep 22 03:40:01.981317 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00489: Apache/2.4.34 (Red Hat) OpenSSL/1.0.2k-fips   configured -- resuming normal operations
(Tue Sep 22 03:40:01.981358 2020) (core:notice) (pid 15291:tid 140357203278016) AH00094: Command line: '/opt/rh/httpd24/root/usr/sbin/httpd -D FOREGROUND'
(Wed Sep 23 03:48:02.613473 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00493: SIGUSR1 received.  Doing graceful restart
(Wed Sep 23 03:48:02.794093 2020) (lbmethod_heartbeat:notice) (pid 15291:tid 140357203278016) AH02282: No slotmem from mod_heartmonitor
(Wed Sep 23 03:48:02.797159 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00489: Apache/2.4.34 (Red Hat) OpenSSL/1.0.2k-fips   configured -- resuming normal operations
(Wed Sep 23 03:48:02.797230 2020) (core:notice) (pid 15291:tid 140357203278016) AH00094: Command line: '/opt/rh/httpd24/root/usr/sbin/httpd -D FOREGROUND'
(Thu Sep 24 03:48:02.313840 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00493: SIGUSR1 received.  Doing graceful restart
(Thu Sep 24 03:48:02.470234 2020) (lbmethod_heartbeat:notice) (pid 15291:tid 140357203278016) AH02282: No slotmem from mod_heartmonitor
(Thu Sep 24 03:48:02.472765 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00489: Apache/2.4.34 (Red Hat) OpenSSL/1.0.2k-fips   configured -- resuming normal operations
(Thu Sep 24 03:48:02.472829 2020) (core:notice) (pid 15291:tid 140357203278016) AH00094: Command line: '/opt/rh/httpd24/root/usr/sbin/httpd -D FOREGROUND'
(Fri Sep 25 03:44:02.157914 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00493: SIGUSR1 received.  Doing graceful restart
(Fri Sep 25 03:44:02.316100 2020) (lbmethod_heartbeat:notice) (pid 15291:tid 140357203278016) AH02282: No slotmem from mod_heartmonitor
(Fri Sep 25 03:44:02.319089 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00489: Apache/2.4.34 (Red Hat) OpenSSL/1.0.2k-fips   configured -- resuming normal operations
(Fri Sep 25 03:44:02.319149 2020) (core:notice) (pid 15291:tid 140357203278016) AH00094: Command line: '/opt/rh/httpd24/root/usr/sbin/httpd -D FOREGROUND'
(Sat Sep 26 03:37:02.703473 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00493: SIGUSR1 received.  Doing graceful restart
(Sat Sep 26 03:37:02.854782 2020) (lbmethod_heartbeat:notice) (pid 15291:tid 140357203278016) AH02282: No slotmem from mod_heartmonitor
(Sat Sep 26 03:37:02.857291 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00489: Apache/2.4.34 (Red Hat) OpenSSL/1.0.2k-fips   configured -- resuming normal operations
(Sat Sep 26 03:37:02.857434 2020) (core:notice) (pid 15291:tid 140357203278016) AH00094: Command line: '/opt/rh/httpd24/root/usr/sbin/httpd -D FOREGROUND'
(Sun Sep 27 03:07:02.134428 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00493: SIGUSR1 received.  Doing graceful restart
(Sun Sep 27 03:07:02.293453 2020) (lbmethod_heartbeat:notice) (pid 15291:tid 140357203278016) AH02282: No slotmem from mod_heartmonitor
(Sun Sep 27 03:07:02.295940 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00489: Apache/2.4.34 (Red Hat) OpenSSL/1.0.2k-fips   configured -- resuming normal operations
(Sun Sep 27 03:07:02.295972 2020) (core:notice) (pid 15291:tid 140357203278016) AH00094: Command line: '/opt/rh/httpd24/root/usr/sbin/httpd -D FOREGROUND'
(Mon Sep 28 03:40:02.502201 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00493: SIGUSR1 received.  Doing graceful restart
(Mon Sep 28 03:40:02.655018 2020) (lbmethod_heartbeat:notice) (pid 15291:tid 140357203278016) AH02282: No slotmem from mod_heartmonitor
(Mon Sep 28 03:40:02.657714 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00489: Apache/2.4.34 (Red Hat) OpenSSL/1.0.2k-fips   configured -- resuming normal operations
(Mon Sep 28 03:40:02.657785 2020) (core:notice) (pid 15291:tid 140357203278016) AH00094: Command line: '/opt/rh/httpd24/root/usr/sbin/httpd -D FOREGROUND'
(Tue Sep 29 03:16:02.338908 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00493: SIGUSR1 received.  Doing graceful restart
(Tue Sep 29 03:16:02.483232 2020) (lbmethod_heartbeat:notice) (pid 15291:tid 140357203278016) AH02282: No slotmem from mod_heartmonitor
(Tue Sep 29 03:16:02.485872 2020) (mpm_event:notice) (pid 15291:tid 140357203278016) AH00489: Apache/2.4.34 (Red Hat) OpenSSL/1.0.2k-fips   configured -- resuming normal operations
(Tue Sep 29 03:16:02.485944 2020) (core:notice) (pid 15291:tid 140357203278016) AH00094: Command line: '/opt/rh/httpd24/root/usr/sbin/httpd -D FOREGROUND'

From googling this error, I found that the reasons given were that php was a non-thread safe software, and you don’t use worker (or other threaded MPM) with non-thread-safe software.

Thinking that the current configuration was not properly done, I edited httpd.conf to add these lines :

<FilesMatch ".phps$">
    SetHandler application/x-httpd-php-source
</FilesMatch>

<FilesMatch .php$>
    SetHandler application/x-httpd-php
</FilesMatch>

# Load php handler
AddHandler php5-script .php
AddType text/html .php

I also installed rh-php56-php and rh-php56, which were not installed previously. Only rh-php56-php-fpm was installed previously. So now I could see the php module file and conf file in their respective directories. I then enabled mpm-prefork and disabled mpm-event in httpd. I also disabled all the unneeded modules from 00-base.conf. After restarting httpd I could see that the php module was now enabled.

However, I am not sure if this is the correct solution that will resolve this problem.

I checked also, that the php installed did not have thread safety enabled :

(root@its aigini)# /opt/rh/rh-php56/root/usr/bin/php -i | grep Thread
Thread Safety => disabled
(root@its aigini)#

How do I enable thread safe, and will this indeed resolve the problem?

According to the link below,the steps that I have used is a thread-safe method, but still I am not sure:

(https://www.geeksforgeeks.org/what-is-thread-safe-or-non-thread-safe-in-php/)(1)

How do I resolve the intermittent http service issue?

html – Email Validation in PHP

Is this script sufficient enough to validate user email input?

    <?php 
    //1 DATABASE CONNECTION
    $dbHost = "HOST";
    $dbUser = "USER";
    $dbPassword = "PASSWORD";
    $dbName = "DATABASE";
    
    try {
      $dsn = "mysql:host=" . $dbHost . ";dbname=" . $dbName;
      $pdo = new PDO($dsn, $dbUser, $dbPassword);
      $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
      echo "DB Connection Failed: " . $e->getMessage();
      exit(0);
    }
    //1 END

    //2 ADD EMAIL TO DATABASE
    
    //set date and time
    date_default_timezone_set('America/Los_Angeles');
    $timestamp = strtotime('NOW');
    $dateTime = date('Ymd-His', $timestamp);
    
    //variable to store ipv4 address
    $userIP4 = gethostbyname($_SERVER('REMOTE_ADDR'));
    //storing ip6 could be something like: "bin2hex(inet_pton($_SERVER('REMOTE_ADDR')));" but I couldn't figure out if the output was correct, because it looked nothing like an ipv6 address.....
    
    if(filter_var($userIP4, FILTER_VALIDATE_IP)) {
        //yes it's valid IPv4
        if($_SERVER('REQUEST_METHOD') == 'POST') {
            $email = htmlspecialchars($_POST('email')); //convert special characters to HTML entities (&,",<,>)
            $Temail = trim($email); //trim spaces on ends
            
            //allow international characters
            if(preg_match("/^(_a-z0-9-)+(.(_a-z0-9-)+)*@(a-z0-9-)+(.(a-z0-9-)+)*(.(a-z){2,3})$^/", $Temail)) {
                //prevents invalid email addresses
                header("Location: invalid.html");
                exit (0);
            } else {
                //Check Email Domain MX Record
                $email_host = strtolower(substr(strrchr($Temail, "@"), 1));
                if (!checkdnsrr($email_host, "MX")) {
                    header("Location: invalid.html");
                    exit (0);
                } else {
                    //Prevent users from inputting a specific domain...
                    $notallowed = (
                        'mydomain.com',
                    );
                    $parts = explode('@', $Temail); //Separate string by @ characters (there should be only one)
                    $domain = array_pop($parts); //Remove and return the last part, which should be the domain
                    if ( ! in_array($domain, $notallowed)) {

                        //checks database to make sure the email is not a duplicate
                        $stmt1 = $pdo->prepare("SELECT * FROM emailTable WHERE email=?");
                        $stmt1->execute(($Temail));
                        $user = $stmt1->fetch();
                        if($user) {
                            //prevents adding a duplicate email
                            header("Location: duplicate.html");
                            exit (0);
                        } else {
                            //generate Activation code
                            $Acode = md5(time().$Temail);
                            
                            //send verification email
                            $emailfrom = 'no-reply@mydomain.com';
                            $fromname = 'MY NAME';
                            $subject = 'Confirm Your Email Subscription';
                            $emailbody = "
                                <html>
                                <body style='background-color: #000; padding: 15px;'>
                                    <table style='background-color: #222;'>
                                        <tr style='background-color: #333; padding: 15px; font-size: 1.3rem;'>
                                            <td><h2 style='color: #FFF;' align='center'>Please Verify Subscription</h2></td>
                                        </tr>
                                        <tr>
                                            <td style='color: #FFF; font-size: 1.1rem;' align='center'>
                                                <br/>
                                                <br/>
                                                If you didn't sign up for my email list, simply delete this message. You will not be added unless you push the button below.
                                                <br/>
                                                <br/>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style='color: #FFF; font-size: 1.3rem;' align='center'>
                                                <button style='background-color: #000; width: 6rem; height: 2rem;'><a href='https://www.MYDOMAIN.com/verify.php?acode=$Acode' style='color: #F00; text-decoration: none; font-size:1rem;'>VERIFY</a></button>
                                                <br/>
                                                <br/>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style='color: #FFF; font-size: 1.1rem;' align='center'>
                                                <font style='font-size:0.8rem;'>This email was automatically generated from a mailbox that is not monitored.</font>
                                            </td>
                                        </tr>
                                    </table>
                                </body>
                                </html>";
                                
                            $headers = "Reply-To: MY NAME <no-reply@MYDOMAIN.com>rn"; 
                            $headers .= "Return-Path: MY NAME <no-reply@MYDOMAIN.com>rn"; 
                            $headers .= "From: MY NAME <no-reply@MYDOMAIN.com>rn";  
                            $headers .= "MIME-Version: 1.0rn";
                            $headers .= "Content-type: text/html; charset=UTF-8rn";
                            $headers .= "X-Priority: 3rn";
                            $headers .= "X-Mailer: PHP". phpversion() ."rn" ;
        
                            $params = '-f ' . $emailfrom;
                            $send = mail($Temail, $subject, $emailbody, $headers, $params); // $send should be TRUE if the mail function is called correctly
                            if($send) {
                                //add the new email and other data to the database
                                $sql = "INSERT INTO emailTable (IP4, datetime, email, acode) VALUES (:IP4, :datetime, :email, :acode)";
                                $stmt2 = $pdo->prepare($sql);
                                $stmt2->execute(('IP4' => $userIP4, 'datetime' => $dateTime, 'email' => $Temail, 'acode' => $Acode));
                                $userIP4 = "";
                                $dateTime = "";
                                $Temail = "";
                                $Acode = "";
                                header("Location: success.html");
                                exit (0);
                            } else {
                                header("Location: invalid.html");
                                exit (0);
                            }
                        }
                    } else {
                        header("Location: notallowed.html");
                        exit (0);
                    }
                }
            }
        } else {
            header("Location: invalid.html");
            exit (0);
        }
    } else {
        header("Location: invalid.html");
        exit (0);
    }
    //2 END
    ?>

Security threats in mind:

1. SQL Injections!!! — Solutions: Prepared Statements (PDO), using only UTF-8, and including “$bpdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);” in the database connection

2. XSS Attacks!!! — Solutions: htmlspecialchars(), Content-Security Policy (placed in htaccess):

<FilesMatch ".(html|php)$">
    Header set Content-Security-Policy "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data: 'unsafe-inline'; media-src 'self' data: 'unsafe-inline'; connect-src 'self';"
</FilesMatch>

3. OS Command Attacks!!! — Solutions: Striping whitespace (not necessary with emails), validating against a whitelist of permitted values.

4. DOS Attacks!!! — Solution: None implemented. I’m unsure if any additional precaution is necessary, since there are no login possibilities on my website.

5. PHP Email Injection!!! — Solution: A Regular Expression (the one I have is mostly designed to allow for international characters).

Additionally, I use an SSL Certificate, SiteLock Security- Essential, CloudFlare CDN, and have implemented a DMARC Policy in my DNS (something I’ll be fine tuning for the foreseeable future).

security – PHP Email Verification, Sanitizing Email Input for Database Table

Intro

The purpose of this post is review and feedback. I’ve been working with PHP for three weeks and have reached a point where I require the advice from those with much more experience. The PHP scripts I’ve written are fully functional and have already been perfected to the best of my abilities. There is a lot to go over, so I will be as detailed as possible…

I have an HTML form on my website where users can input their email address. Using php, the input is sanitized and stored in a database table for the purpose of creating an email list. The information that I insert into the table includes:

  • id: int(11) AUTO_INCREMENT,
  • datetime: VARCHAR(18),
  • email: VARCHAR(255),
  • acode: VARCHAR(45) *this is a verification code sent to the user’s email (more on this later),
  • verified: tinyint(1) *this is the verification status (either a 0 or 1),
  • IP4: VARBINARY(39) *used to store the user’s IPv4 Address

Security threats in mind:

1. SQL Injections!!! — Solutions: Prepared Statements (PDO), using only UTF-8, and including “$bpdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);” in the database connection

2. XSS Attacks!!! — Solutions: htmlspecialchars(), Content-Security Policy (placed in htaccess):

<FilesMatch ".(html|php)$">
    Header set Content-Security-Policy "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data: 'unsafe-inline'; media-src 'self' data: 'unsafe-inline'; connect-src 'self';"
</FilesMatch>

3. OS Command Attacks!!! — Solutions: Striping whitespace (not necessary with emails), validating against a whitelist of permitted values.

4. DOS Attacks!!! — Solution: None implemented. I’m unsure if any additional precaution is necessary, since there are no login possibilities on my website.

5. PHP Email Injection!!! — Solution: A Regular Expression (the one I have is mostly designed to allow for international characters).

Additionally, I use an SSL Certificate, SiteLock Security- Essential, CloudFlare CDN, and have implemented a DMARC Policy in my DNS (something I’ll be fine tuning for the foreseeable future).

A detailed look at emailconfig.php:

This is the full script for reference. I’ll discuss each piece below it.

<?php 
    //1 DATABASE CONNECTION
    $dbHost = "HOST";
    $dbUser = "USER";
    $dbPassword = "PASSWORD";
    $dbName = "DATABASE";
    
    try {
      $dsn = "mysql:host=" . $dbHost . ";dbname=" . $dbName;
      $pdo = new PDO($dsn, $dbUser, $dbPassword);
      $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
      echo "DB Connection Failed: " . $e->getMessage();
      exit(0);
    }
    //1 END

    //2 ADD EMAIL TO DATABASE
    
    //set date and time
    date_default_timezone_set('America/Los_Angeles');
    $timestamp = strtotime('NOW');
    $dateTime = date('Ymd-His', $timestamp);
    
    //variable to store ipv4 address
    $userIP4 = gethostbyname($_SERVER('REMOTE_ADDR'));
    //storing ip6 could be something like: "bin2hex(inet_pton($_SERVER('REMOTE_ADDR')));" but I couldn't figure out if the output was correct, because it looked nothing like an ipv6 address.....
    
    if(filter_var($userIP4, FILTER_VALIDATE_IP)) {
        //yes it's valid IPv4
        if($_SERVER('REQUEST_METHOD') == 'POST') {
            $email = htmlspecialchars($_POST('email')); //convert special characters to HTML entities (&,",<,>)
            $Temail = trim($email); //trim spaces on ends
            
            //allow international characters
            if(preg_match("/^(_a-z0-9-)+(.(_a-z0-9-)+)*@(a-z0-9-)+(.(a-z0-9-)+)*(.(a-z){2,3})$^/", $Temail)) {
                //prevents invalid email addresses
                header("Location: invalid.html");
                exit (0);
            } else {
                //Check Email Domain MX Record
                $email_host = strtolower(substr(strrchr($Temail, "@"), 1));
                if (!checkdnsrr($email_host, "MX")) {
                    header("Location: invalid.html");
                    exit (0);
                } else {
                    //Prevent users from inputting a specific domain...
                    $notallowed = (
                        'mydomain.com',
                    );
                    $parts = explode('@', $Temail); //Separate string by @ characters (there should be only one)
                    $domain = array_pop($parts); //Remove and return the last part, which should be the domain
                    if ( ! in_array($domain, $notallowed)) {

                        //checks database to make sure the email is not a duplicate
                        $stmt1 = $pdo->prepare("SELECT * FROM emailTable WHERE email=?");
                        $stmt1->execute(($Temail));
                        $user = $stmt1->fetch();
                        if($user) {
                            //prevents adding a duplicate email
                            header("Location: duplicate.html");
                            exit (0);
                        } else {
                            //generate Activation code
                            $Acode = md5(time().$Temail);
                            
                            //send verification email
                            $emailfrom = 'no-reply@mydomain.com';
                            $fromname = 'MY NAME';
                            $subject = 'Confirm Your Email Subscription';
                            $emailbody = "
                                <html>
                                <body style='background-color: #000; padding: 15px;'>
                                    <table style='background-color: #222;'>
                                        <tr style='background-color: #333; padding: 15px; font-size: 1.3rem;'>
                                            <td><h2 style='color: #FFF;' align='center'>Please Verify Subscription</h2></td>
                                        </tr>
                                        <tr>
                                            <td style='color: #FFF; font-size: 1.1rem;' align='center'>
                                                <br/>
                                                <br/>
                                                If you didn't sign up for my email list, simply delete this message. You will not be added unless you push the button below.
                                                <br/>
                                                <br/>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style='color: #FFF; font-size: 1.3rem;' align='center'>
                                                <button style='background-color: #000; width: 6rem; height: 2rem;'><a href='https://www.MYDOMAIN.com/verify.php?acode=$Acode' style='color: #F00; text-decoration: none; font-size:1rem;'>VERIFY</a></button>
                                                <br/>
                                                <br/>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style='color: #FFF; font-size: 1.1rem;' align='center'>
                                                <font style='font-size:0.8rem;'>This email was automatically generated from a mailbox that is not monitored.</font>
                                            </td>
                                        </tr>
                                    </table>
                                </body>
                                </html>";
                                
                            $headers = "Reply-To: MY NAME <no-reply@MYDOMAIN.com>rn"; 
                            $headers .= "Return-Path: MY NAME <no-reply@MYDOMAIN.com>rn"; 
                            $headers .= "From: MY NAME <no-reply@MYDOMAIN.com>rn";  
                            $headers .= "MIME-Version: 1.0rn";
                            $headers .= "Content-type: text/html; charset=UTF-8rn";
                            $headers .= "X-Priority: 3rn";
                            $headers .= "X-Mailer: PHP". phpversion() ."rn" ;
        
                            $params = '-f ' . $emailfrom;
                            $send = mail($Temail, $subject, $emailbody, $headers, $params); // $send should be TRUE if the mail function is called correctly
                            if($send) {
                                //add the new email and other data to the database
                                $sql = "INSERT INTO emailTable (IP4, datetime, email, acode) VALUES (:IP4, :datetime, :email, :acode)";
                                $stmt2 = $pdo->prepare($sql);
                                $stmt2->execute(('IP4' => $userIP4, 'datetime' => $dateTime, 'email' => $Temail, 'acode' => $Acode));
                                $userIP4 = "";
                                $dateTime = "";
                                $Temail = "";
                                $Acode = "";
                                header("Location: success.html");
                                exit (0);
                            } else {
                                header("Location: invalid.html");
                                exit (0);
                            }
                        }
                    } else {
                        header("Location: notallowed.html");
                        exit (0);
                    }
                }
            }
        } else {
            header("Location: invalid.html");
            exit (0);
        }
    } else {
        header("Location: invalid.html");
        exit (0);
    }
    //2 END
    ?>

Let’s discuss in pieces:

1. Database Connection —

As far as I know, this is the correct way to set up the connection. I’ve found that about half of people recommend including the DB connection in each php file and the other half of people recommend having the connection in a separate file of its’ own and then linking it with require_once(). I’ve decided to include a database connection in each file.

2. Setting the Date and Time —

3. Setting and validating IPv4 variable —

I’m most unsure of this section. Through testing, I’ve found that this accurately stores the user’s ipv4 address into my database, but I feel that it may be insufficent from a security standpoint. I’ve attempted to store ipv6 addresses, but the code that I tried (found in the note) gave me an output that looked nothing like an ipv6 address, but perhaps it was correct. More info on this would be much appreciated. For the working ipv4 code, I’ve found that removing the gethostbyname() makes no difference to the output, so would removing this be acceptable, or should it be replaced with something else? Again, it works.

4. Validating the User’s Email Input —

Here’s a long one, but let’s go through it step by step. I used to use filter_var($email, FILTER_VALIDATE_EMAIL), but found that there was no way to make it so this allowed for international characters, so I got rid of it and replaced it with what you see. First we run the $email string through htmlspecialchars($_POST('email')); and a trim to replace certain characters and get rid of whitespace on either end. Next we put the $Temail string through the preg_match() regex in order to allow international characters. Does this also protect against OS Command Attacks?? Next we use the $email_host variable to check to see if the domain is real or not. I’ve tested it against gmail.com, yahoo.com, protonmail.com, my own domain and many others, and it seems to work well. Next I use an array ($notallowed), two variables and an if statement to prevent users from inputting my own domain, or any other domain that I include in the array. If the input matches any of these domains, then they are sent to notallowed.html. Next we check the database to see if the email is already in the database. If it is, then the user is directed to duplicate.html. Phew.

5. Generate verification code and send it in an email —

I decided to combine md5 with the time and the user’s trimmed email in order to create the verification code. The html email is pretty straight forward. I read a bit about how you basically need to pretend it’s 1999 when using html for emails. This led me to format it with tables and inline css. The verification code that is generated is placed in a button that reads <a href='https://www.MYDOMAIN.com/verify.php?acode=$Acode'>. The link uses a second php script (verify.php) that I’ll discuss later on. One of my major goals for this section was preventing the verification email from going to spam! I include a number of headers in the email, which, to the best of my knowledge, are enough to prevent this. Testing on gmail, yahoo, protonmail and my own domain have proven their effectiveness.

6. Adding everything to the database —

Additional Goals:

1. Storing IPv6 Addresses — As it stands, the code that I have accurately stores the user’s IPv4 address. What I haven’t been able to figure out is how to store the Ipv6 address. I tried the following: $userIP6 = bin2hex(inet_pton($_SERVER('REMOTE_ADDR')));
this inserted a string in the table (a VARBINARY column) that looked nothing like an IPv6 address, but remained consistent after each test…

Questions:

  • What changes/additions should be made to strengthen security?
  • I use filter_var($userIP4, FILTER_VALIDATE_IP) to validate the IP.
    Is this sufficient? Would the user having a VPN affect the
    functionality of this??
  • Is the regex that I used
    (preg_match("/^(_a-z0-9-)+(.(_a-z0-9-)+)*@(a-z0-9-)+(.(a-z0-9-)+)*(.(a-z){2,3})$^/", $Temail)) helpful in preventing OS Command Attacks? If not, what
    could be added to do so?

php – Si el usuario existe que no lo registre

estoy creando un sistema de logeo y funciona perfecto! El tema ahora es que quiero que si el correo de usuario está registrado que no se pueda registrar nuevamente. No se cómo generar la consulta ni donde, dejo el código a ver si pueden ayudarme.
Muchas gracias.

Esto es ClienteUsuario.php, quién se encarga del proceso de registro:

<?php

namespace Akron;

class ClienteUsuario{

private $config;
private $cn = null;

public function __construct(){

    $this->config = parse_ini_file(__DIR__.'/../config.ini') ;

    $this->cn = new PDO( $this->config('dns'), $this->config('usuario'),$this->config('clave'),array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
    ));
    
}

public function registrar($_params){
    $sql = "INSERT INTO `cliente_usuario`(`nombre_usuario`, `correo_usuario`, `telefono_usuario`, `contrasena_usuario`) 
    VALUES (:nombre_usuario,:correo_usuario,:telefono_usuario,:contrasena_usuario)";

    $resultado = $this->cn->prepare($sql);

    $_array = array(
        ":nombre_usuario" => $_params('nombre_usuario'),
        ":correo_usuario" => $_params('correo_usuario'),
        ":telefono_usuario" => $_params('telefono_usuario'),
        ":contrasena_usuario" => $_params('contrasena_usuario'),

    );

    if($resultado->execute($_array))
        return $this->cn->lastInsertId();

    return false;
}

}

Esto es la validación del registro

<?php
require '../vendor/autoload.php';

$producto = new AkronClienteUsuario;

if($_SERVER('REQUEST_METHOD') === 'POST'){
    
    if($_POST('accion') === 'Registrar'){


    $_params = array(
        
        'nombre_usuario'=>$_POST('nombre_usuario'),
        'correo_usuario'=>$_POST('correo_usuario'),
        'telefono_usuario'=>$_POST('telefono_usuario'),
        'contrasena_usuario'=>$_POST('contrasena_usuario'),
    
    );
        
        $rpt = $producto->registrar($_params);
        
        if($rpt)
            header("Location: successaccount.php");
        else
            print 'Error al registrar un producto';
        
    
}
    
    
}

Y este es el formulario de registro:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form enctype="multipart/form-data" action="acciones.php" method="post">
    <label>Nombre</label>
    <input name="nombre_usuario" type="text">
    <label>Correo</label>
    <input name="correo_usuario" type="text">
    <label>Telefono</label>
    <input name="telefono_usuario" type="text">
    <label>Contrase&ntilde;a</label>
    <input name="contrasena_usuario" type="text">
    <input type="submit" name="accion" value="Registrar">
    </form>
</body>
</html>

php – Agregar mensaje de error en cada apartado del formulario

actualmente tengo un problema para mostrar los mensajes de error traídos de parte del servidor a mi formulario. este es mi formulario

introducir la descripción de la imagen aquí

en caso de que el usuario cometa un error en la información a registrar deberá de mostrar el error que tiene en cada respectivo lugar del formulario.

informacion que se obtiene por parte del servidor en un error

{
    "status":"error",
    "status_code":409,
    "message":"Validations failed, see validations for more details",
    "validations":{
        "name":"The name field is required.",
        "emailuser":"The field email user must be between 6 and 120 characters in length",
        "passworduser":"The password user field is required.",
        "confirmpass":"The Password Confirmation field is required."},
    "data":null
}

en el caso de un error en el campo por ejemplo name como podría mandar el error de validations en el campo name al formulario

<form id="registerForm">
      <h2>REGISTER</h2>
      <input type="text" placeholder="User" id="name"  name="name">
      <span>insertar mensaje error</span>
      <input type="text" placeholder="Email" id="emailuser"  name="emailuser">
      <input type="password" placeholder="Password" id="passworduser"  name="passworduser">
      <input type="password" placeholder="Confirm Password" id="confirmpass"  name="confirmpass">
      <input type="hidden" placeholder="" id="type"  name="type" value="Administrador">
      <input type="submit" class="btn btn-secondary" value="Register">
</form>

es posible mandar una etiqueta span con el error de cada campo?

php – SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value

Estou importanto uma planilha do excel e preciso converter a data para datetime p o mysql aceitar gravação entretanto já tentei todas as opções do mutator do laravel e não passa.

No Controller
$import = new ComercialImport

class ComercialImport implements
   ToCollection,
    WithHeadingRow,

public function collection(Collection $rows)
{
          acredito que teria que mudar aqui na array pois no model nao esta obedecendo, mas nao tenho ideia de como fazer aqui .
    foreach ($rows as $row) {
        $com = Comercial::create((
       
           'vigencia_inicial'               => $row  ('vigencial_inicial'),
           'vigencial'                      => $row  ('vigencia_final'),

no model ja tentei de tudo

  class Comercial extends Model
     {

        protected $guarded = ('id');

        public $timestamps = false;
        protected $dates = ('vigencia_inicial', 'Vigencia_final');
        protected $dateFormat = 'd/m/Y';

php – carrito de compras ecommerce- suma acumulativa de productos

Estoy terminando de desarrollar un ecommerce, utilizando boostrap como front, una api desarrollada en PHP para el back y ajax como middleware para traer productos desde el back sin tener que recargar la pagina.
El problema que tengo es que no se como se hace para guardar la información traída ya que cada vez que se selecciona otro producto o se cambia de pagina, el producto que estaba se elimina.
Se que se puede utilizar la variable $_SESSION pero no se como se utiliza o como tendría que hacer para sumarle varios productos. Puede que este explicado medio mal, cualquier cosa puedo agregarle la info necesaria para brindar la solucion.

php – (facil) Como alterar de uma pagina html para outra, tudo no mesmo dominio

Olá, tenho uma duvida em html, eu tenho um ficheiro index.html que tem o meu site quase todo, mas queria que ao clicar num botão fosse para outra pagina, por exemplo, “ysnocksite.com” >> clico no botão >> “ysnocksite.com/funcionario-do-mes”. Mais ou menos assim.

php – ¿Cómo optimizar este código para que cargue mas rápido?

Recibo una tabla que mi programa pinta por html table, entonces me piden que la ordene por las diferentes columnas de modo ascendente y descendente, lo pense y lo puse por onclick en el titulo de cada columna, un click, ordena ascendente el segundo click de forma descendente.

pero mi problema es que la tabla tiene muchisimos registros/tuplas, y tarda como 5′ en ejecutarse el sort

acá mi código de ordenacion:

function sortTable(n) {
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById("listado-empresas");
  switching = true;
  dir = "asc"; 
  while (switching) {
    switching = false;
    rows = table.rows;
    for (i = 1; i < (rows.length - 1); i++) {
       shouldSwitch = false;
       x = rows(i).getElementsByTagName("td")(n);
      y = rows(i + 1).getElementsByTagName("td")(n);
       if (dir == "asc") {
        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
           shouldSwitch= true;
          break;
        }
      } else if (dir == "desc") {
        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
          shouldSwitch = true;
          break;
        }
      }
    }
    if (shouldSwitch) {
      rows(i).parentNode.insertBefore(rows(i + 1), rows(i));
      switching = true;
      switchcount ++;      
    } else {
      if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}