kandi background
Explore Kits

PHPMailer | The classic email sending library for PHP | Email library

 by   PHPMailer PHP Version: v6.6.0 License: LGPL-2.1

 by   PHPMailer PHP Version: v6.6.0 License: LGPL-2.1

Download this library from

kandi X-RAY | PHPMailer Summary

PHPMailer is a PHP library typically used in Telecommunications, Media, Media, Entertainment, Messaging, Email applications. PHPMailer has no bugs, it has a Weak Copyleft License and it has medium support. However PHPMailer has 4 vulnerabilities. You can download it from GitHub.
The classic email sending library for PHP
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • PHPMailer has a medium active ecosystem.
  • It has 18018 star(s) with 9203 fork(s). There are 884 watchers for this library.
  • There were 2 major release(s) in the last 12 months.
  • There are 26 open issues and 1847 have been closed. On average issues are closed in 11 days. There are 9 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of PHPMailer is v6.6.0
PHPMailer Support
Best in #Email
Average in #Email
PHPMailer Support
Best in #Email
Average in #Email

quality kandi Quality

  • PHPMailer has 0 bugs and 0 code smells.
PHPMailer Quality
Best in #Email
Average in #Email
PHPMailer Quality
Best in #Email
Average in #Email

securitySecurity

  • PHPMailer has 4 vulnerability issues reported (2 critical, 1 high, 1 medium, 0 low).
  • PHPMailer code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
PHPMailer Security
Best in #Email
Average in #Email
PHPMailer Security
Best in #Email
Average in #Email

license License

  • PHPMailer is licensed under the LGPL-2.1 License. This license is Weak Copyleft.
  • Weak Copyleft licenses have some restrictions, but you can use them in commercial projects.
PHPMailer License
Best in #Email
Average in #Email
PHPMailer License
Best in #Email
Average in #Email

buildReuse

  • PHPMailer releases are available to install and integrate.
  • Installation instructions, examples and code snippets are available.
  • PHPMailer saves you 2115 person hours of effort in developing the same functionality from scratch.
  • It has 4834 lines of code, 169 functions and 58 files.
  • It has high code complexity. Code complexity directly impacts maintainability of the code.
PHPMailer Reuse
Best in #Email
Average in #Email
PHPMailer Reuse
Best in #Email
Average in #Email
Top functions reviewed by kandi - BETA

kandi has reviewed PHPMailer and discovered the below as its top functions. This is intended to give you an instant insight into PHPMailer implemented functionality, and help decide if they suit your requirements.

  • Create email body
    • Create DKIM
      • Authenticates to the server
        • Get lines from the SMTP connection
          • Connect to the POP3 server
            • Authorise the server
              • Generate the OAuth 64
                • Get an access token .
                  • Get error message .

                    Get all kandi verified functions for this library.

                    Get all kandi verified functions for this library.

                    PHPMailer Key Features

                    Probably the world's most popular code for sending email from PHP!

                    Used by many open-source projects: WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla! and many more

                    Integrated SMTP support – send without a local mail server

                    Send emails with multiple To, CC, BCC and Reply-to addresses

                    Multipart/alternative emails for mail clients that do not read HTML email

                    Add attachments, including inline

                    Support for UTF-8 content and 8bit, base64, binary, and quoted-printable encodings

                    SMTP authentication with LOGIN, PLAIN, CRAM-MD5, and XOAUTH2 mechanisms over SMTPS and SMTP+STARTTLS transports

                    Validates email addresses automatically

                    Protects against header injection attacks

                    Error messages in over 50 languages!

                    DKIM and S/MIME signing support

                    Compatible with PHP 5.5 and later, including PHP 8.1

                    Namespaced to prevent name clashes

                    Much more!

                    Installation & loading

                    copy iconCopydownload iconDownload
                    "phpmailer/phpmailer": "^6.5"
                    

                    A Simple Example

                    copy iconCopydownload iconDownload
                    <?php
                    //Import PHPMailer classes into the global namespace
                    //These must be at the top of your script, not inside a function
                    use PHPMailer\PHPMailer\PHPMailer;
                    use PHPMailer\PHPMailer\SMTP;
                    use PHPMailer\PHPMailer\Exception;
                    
                    //Load Composer's autoloader
                    require 'vendor/autoload.php';
                    
                    //Create an instance; passing `true` enables exceptions
                    $mail = new PHPMailer(true);
                    
                    try {
                        //Server settings
                        $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
                        $mail->isSMTP();                                            //Send using SMTP
                        $mail->Host       = 'smtp.example.com';                     //Set the SMTP server to send through
                        $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
                        $mail->Username   = 'user@example.com';                     //SMTP username
                        $mail->Password   = 'secret';                               //SMTP password
                        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
                        $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
                    
                        //Recipients
                        $mail->setFrom('from@example.com', 'Mailer');
                        $mail->addAddress('joe@example.net', 'Joe User');     //Add a recipient
                        $mail->addAddress('ellen@example.com');               //Name is optional
                        $mail->addReplyTo('info@example.com', 'Information');
                        $mail->addCC('cc@example.com');
                        $mail->addBCC('bcc@example.com');
                    
                        //Attachments
                        $mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
                        $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name
                    
                        //Content
                        $mail->isHTML(true);                                  //Set email format to HTML
                        $mail->Subject = 'Here is the subject';
                        $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
                        $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
                    
                        $mail->send();
                        echo 'Message has been sent';
                    } catch (Exception $e) {
                        echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
                    }
                    

                    Localization

                    copy iconCopydownload iconDownload
                    //To load the French version
                    $mail->setLanguage('fr', '/optional/path/to/language/directory/');
                    

                    Contributing

                    copy iconCopydownload iconDownload
                    git remote set-url upstream https://github.com/PHPMailer/PHPMailer.git
                    

                    Why PHP PDO bindParam return null if include jQuery file

                    copy iconCopydownload iconDownload
                    <form  spellcheck="false" autocomplete="off" autocorrect="off" id='contactOwner' class='form ajax' name='contactOwner' action='' method='POST'>
                    <h4 id="responseOwner" class="success">
                    <!-- This will hold response from the server --></h4>
                      <fieldset>
                        <legend>Vaši podaci</legend>
                            <div class="form-control halb InputIconBg"><input minlength="6" type="text" class="input username" name="fname" placeholder="Vaše ime i prezime..." value="<?php echo Input::get('fname'); ?>"><i class="fas fa-user" aria-hidden="true"></i><span class="error"><?=$fname_error; ?></span></div><!-- end .form-control -->
                                
                            <div class="form-control halb InputIconBg"><input minlength="9" type="text" class="input phone" name="tel" placeholder="Vaš broj telefona..." value="<?php echo Input::get('tel'); ?>"><i class="fas fa-phone-alt" aria-hidden="true"></i><span class="error"><?=$tel_error; ?></span></div><!-- end .form-control -->
                    
                            <div class="form-control single InputIconBg"><input type="text" class="input mail" name="userMail" placeholder="Vaš e-mail..." value="<?php echo Input::get('userMail'); ?>" autocomplete="email"><i id="" class="fas fa-envelope" aria-hidden="true"></i><span class="error"><?=$userMail_error; ?></span></div><!-- end .form-control --> 
                                
                            <div class="form-control InputIconBg"><textarea maxlength="1000" name="userMessage" class="textinput message" cols="46" rows="8" placeholder="Vaša poruka..."><?php echo Input::get('userMessage'); ?></textarea><i class="fas fa-pencil-alt owner_icon" aria-hidden="true"></i><span class="error"><?=$userMessage_error; ?></span></div><!-- end .form-control -->
                                
                        </fieldset>
                        <input type="hidden" name="pages_id" value="<?=$pages_id?>">
                        <input type="submit" class="btn_submit" id="submitOwner" name="submitOwner" value="POŠALJI"/>
                    </form>
                    

                    How to display all selected Checkboxes in PHPmailer

                    copy iconCopydownload iconDownload
                    name="cfselection[]"
                    
                    $checkbox = implode(", ", $_POST['cfselection']);
                    
                    search engines, media marketing
                    
                    name="cfselection[]"
                    
                    $checkbox = implode(", ", $_POST['cfselection']);
                    
                    search engines, media marketing
                    
                    name="cfselection[]"
                    
                    $checkbox = implode(", ", $_POST['cfselection']);
                    
                    search engines, media marketing
                    

                    php file size validation

                    copy iconCopydownload iconDownload
                    if( $_FILES['uploaded-file']["name"]['size'][$i] > $maxsize ) {
                    
                                echo "file is too big";
                                die();
                            }else{
                             move_uploaded_file($fileTmpName,  "uploads/" . $filename);
                             $mail-> AddAttachment("uploads/". $filename);
                    }
                    
                    $_FILES['uploaded-file']["name"]['size'][$i]
                    
                    if (isset($_FILES['uploaded-file'])) {
                    for ($i = 0; $i < count($_FILES['uploaded-file']['name']); $i++) { 
                    
                    if ($_FILES['uploaded-file']['error'][$i] !== UPLOAD_ERR_OK) continue;
                    ...
                    if ($_FILES['uploaded-file']['size'][$i] > $maxsize) {
                    ...
                    
                    $_FILES['uploaded-file']["name"]['size'][$i]
                    
                    if (isset($_FILES['uploaded-file'])) {
                    for ($i = 0; $i < count($_FILES['uploaded-file']['name']); $i++) { 
                    
                    if ($_FILES['uploaded-file']['error'][$i] !== UPLOAD_ERR_OK) continue;
                    ...
                    if ($_FILES['uploaded-file']['size'][$i] > $maxsize) {
                    ...
                    
                    $_FILES['uploaded-file']["name"]['size'][$i]
                    
                    if (isset($_FILES['uploaded-file'])) {
                    for ($i = 0; $i < count($_FILES['uploaded-file']['name']); $i++) { 
                    
                    if ($_FILES['uploaded-file']['error'][$i] !== UPLOAD_ERR_OK) continue;
                    ...
                    if ($_FILES['uploaded-file']['size'][$i] > $maxsize) {
                    ...
                    

                    Get Google access token not through the browser

                    copy iconCopydownload iconDownload
                    $access_token= json_decode($oauth_token)->access_token;
                                  
                    $mail->AuthType ="XOAUTH2";
                    $mail->oauthUserEmail = 'auto-mail@example.com';
                    $mail->oauthClientId = "xxx.apps.googleusercontent.com";
                    $mail->oauthClientSecret = "password";
                    $mail->oauthRefreshToken = $access_token;
                    
                    $refresh_token= json_decode($oauth_token)->refresh_token;
                                  
                    $mail->AuthType ="XOAUTH2";
                    $mail->oauthUserEmail = 'auto-mail@example.com';
                    $mail->oauthClientId = "xxx.apps.googleusercontent.com";
                    $mail->oauthClientSecret = "password";
                    $mail->oauthRefreshToken = $refresh_token;
                    
                    $access_token= json_decode($oauth_token)->access_token;
                                  
                    $mail->AuthType ="XOAUTH2";
                    $mail->oauthUserEmail = 'auto-mail@example.com';
                    $mail->oauthClientId = "xxx.apps.googleusercontent.com";
                    $mail->oauthClientSecret = "password";
                    $mail->oauthRefreshToken = $access_token;
                    
                    $refresh_token= json_decode($oauth_token)->refresh_token;
                                  
                    $mail->AuthType ="XOAUTH2";
                    $mail->oauthUserEmail = 'auto-mail@example.com';
                    $mail->oauthClientId = "xxx.apps.googleusercontent.com";
                    $mail->oauthClientSecret = "password";
                    $mail->oauthRefreshToken = $refresh_token;
                    

                    PHPMailer: Working on localhost, stuck after clicking &quot;submit&quot; button on the domain, gives Error 503, E-Mail arrives after 4mins

                    copy iconCopydownload iconDownload
                    $mail->Port = '465';
                    $mail->SMTPSecure = 'ssl';
                    

                    What is the purpose of the ob_ functions in php? (ob_start(), ob_get_contents(), etc.)

                    copy iconCopydownload iconDownload
                    echo 'Hello';
                    
                    ob_start();
                    echo 'Hello';
                    $tmp = ob_get_contents();
                    ob_end_clean();
                    
                    $mail->Body = $tmp;
                    
                    echo 'Hello';
                    
                    ob_start();
                    echo 'Hello';
                    $tmp = ob_get_contents();
                    ob_end_clean();
                    
                    $mail->Body = $tmp;
                    
                    echo 'Hello';
                    
                    ob_start();
                    echo 'Hello';
                    $tmp = ob_get_contents();
                    ob_end_clean();
                    
                    $mail->Body = $tmp;
                    

                    Hiding php codes from file_get_contents method

                    copy iconCopydownload iconDownload
                    $mail_template = htmlspecialchars(file_get_contents($template_file));
                    
                    $mail_template_php = htmlspecialchars(file_get_contents($template_file));
                    $mail_template = eval($mail_template_php);
                    
                    $mail_template = htmlspecialchars(file_get_contents($template_file));
                    
                    $mail_template_php = htmlspecialchars(file_get_contents($template_file));
                    $mail_template = eval($mail_template_php);
                    
                    ob_start();
                    include ( $template_file );
                    $mail_template = ob_get_clean();
                    

                    PHPMailer not working - no specific error

                    copy iconCopydownload iconDownload
                    require ('libphp-phpmailer/PHPMailerAutoload.php');
                    
                    use PHPMailer\PHPMailer\PHPMailer;
                    use PHPMailer\PHPMailer\Exception;
                    use PHPMailer\PHPMailer\SMTP;
                    
                    require 'PHPMailer/src/Exception.php';
                    require 'PHPMailer/src/PHPMailer.php';
                    require 'PHPMailer/src/SMTP.php';
                    
                    require ('libphp-phpmailer/PHPMailerAutoload.php');
                    
                    use PHPMailer\PHPMailer\PHPMailer;
                    use PHPMailer\PHPMailer\Exception;
                    use PHPMailer\PHPMailer\SMTP;
                    
                    require 'PHPMailer/src/Exception.php';
                    require 'PHPMailer/src/PHPMailer.php';
                    require 'PHPMailer/src/SMTP.php';
                    

                    How to force TLS 1.2 usage for PhpMailer 5.2

                    copy iconCopydownload iconDownload
                    public function startTLS()
                    {
                        if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
                            return false;
                        }
                        // Begin encrypted connection
                        if (!stream_socket_enable_crypto(
                            $this->smtp_conn,
                            true,
                            STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
                        )) {
                            return false;
                        }
                        return true;
                    }
                    

                    LetsEncrypt Certificate invalid/expired when seemingly not in PHPMailer, TLS, Openssl, file_get_contents, Sep 30 2021

                    copy iconCopydownload iconDownload
                    cp -i /etc/pki/tls/certs/ca-bundle.crt ~/ca-bundle.crt-backup
                    
                    trust dump --filter "pkcs11:id=%c4%a7%b1%a4%7b%2c%71%fa%db%e1%4b%90%75%ff%c4%15%60%85%89%10" | openssl x509 | sudo tee /etc/pki/ca-trust/source/blacklist/DST-Root-CA-X3.pem
                    
                    sudo update-ca-trust extract
                    
                    diff ~/ca-bundle.crt-backup /etc/pki/tls/certs/ca-bundle.crt
                    
                    yum upgrade ca-certificates
                    
                    cp -i /etc/pki/tls/certs/ca-bundle.crt ~/ca-bundle.crt-backup
                    
                    trust dump --filter "pkcs11:id=%c4%a7%b1%a4%7b%2c%71%fa%db%e1%4b%90%75%ff%c4%15%60%85%89%10" | openssl x509 | sudo tee /etc/pki/ca-trust/source/blacklist/DST-Root-CA-X3.pem
                    
                    sudo update-ca-trust extract
                    
                    diff ~/ca-bundle.crt-backup /etc/pki/tls/certs/ca-bundle.crt
                    
                    yum upgrade ca-certificates
                    
                    cp -i /etc/pki/tls/certs/ca-bundle.crt ~/ca-bundle.crt-backup
                    
                    trust dump --filter "pkcs11:id=%c4%a7%b1%a4%7b%2c%71%fa%db%e1%4b%90%75%ff%c4%15%60%85%89%10" | openssl x509 | sudo tee /etc/pki/ca-trust/source/blacklist/DST-Root-CA-X3.pem
                    
                    sudo update-ca-trust extract
                    
                    diff ~/ca-bundle.crt-backup /etc/pki/tls/certs/ca-bundle.crt
                    
                    yum upgrade ca-certificates
                    
                    cp -i /etc/pki/tls/certs/ca-bundle.crt ~/ca-bundle.crt-backup
                    
                    trust dump --filter "pkcs11:id=%c4%a7%b1%a4%7b%2c%71%fa%db%e1%4b%90%75%ff%c4%15%60%85%89%10" | openssl x509 | sudo tee /etc/pki/ca-trust/source/blacklist/DST-Root-CA-X3.pem
                    
                    sudo update-ca-trust extract
                    
                    diff ~/ca-bundle.crt-backup /etc/pki/tls/certs/ca-bundle.crt
                    
                    yum upgrade ca-certificates
                    
                    cp -i /etc/pki/tls/certs/ca-bundle.crt ~/ca-bundle.crt-backup
                    
                    trust dump --filter "pkcs11:id=%c4%a7%b1%a4%7b%2c%71%fa%db%e1%4b%90%75%ff%c4%15%60%85%89%10" | openssl x509 | sudo tee /etc/pki/ca-trust/source/blacklist/DST-Root-CA-X3.pem
                    
                    sudo update-ca-trust extract
                    
                    diff ~/ca-bundle.crt-backup /etc/pki/tls/certs/ca-bundle.crt
                    
                    yum upgrade ca-certificates
                    

                    Community Discussions

                    Trending Discussions on PHPMailer
                    • Why PHP PDO bindParam return null if include jQuery file
                    • How to display all selected Checkboxes in PHPmailer
                    • php file size validation
                    • Get Google access token not through the browser
                    • PHPMailer: Working on localhost, stuck after clicking &quot;submit&quot; button on the domain, gives Error 503, E-Mail arrives after 4mins
                    • What is the purpose of the ob_ functions in php? (ob_start(), ob_get_contents(), etc.)
                    • Hiding php codes from file_get_contents method
                    • PHPMailer not working - no specific error
                    • How to force TLS 1.2 usage for PhpMailer 5.2
                    • Composer post-install scripts not executed
                    Trending Discussions on PHPMailer

                    QUESTION

                    Why PHP PDO bindParam return null if include jQuery file

                    Asked 2022-Apr-02 at 20:41

                    On every page I have jQuery modal which contains a contact form and which on every page need sent data to different email address. When a form is submitted I need to display successful response using json_encode. Also on every page I use page identifier as $pages_id=1, $pages_id=2, etc., for identify which form is submitted. However, very important, without jQuery file, complete my PHP code it's executed correctly, all data are successfully inserted into database and in Xdebug I also see that code on every line it's executed successfully. But, if I include jQuery file then in Xdebug the value for $pages_id return null. I exactly think at this line of code:

                    $query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
                    $dbstmt = $pdo->prepare($query);
                    $dbstmt->bindParam(1,$pages_id);
                    $dbstmt->execute();
                    

                    However, below is my complete PHP code:

                    <?php
                    // set error reporting
                    ini_set('display_errors', 1);
                    ini_set('display_startup_errors', 1);
                    error_reporting(E_ALL | E_STRICT);
                    
                    $fname = $tel = $userMail = $userMessage = $email_address_id = "";
                    $fname_error = $tel_error = $userMail_error = $userMessage_error = "";
                    $error=false;
                    //Load the config file
                    $dbHost = "secret";
                    $dbUser = "secret";
                    $dbPassword = "secret";
                    $dbName = "secret";
                    $dbCharset = "utf8";
                    $pdo="";
                    try{
                        $dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
                        $pdo = new PDO($dsn, $dbUser, $dbPassword);
                        array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
                        $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                    }catch(PDOException $e){
                        echo "Connection error: " . $e->getMessage();
                    }
                    use PHPMailer\PHPMailer\PHPMailer;
                    require 'PHPMailer/PHPMailer.php';
                    require 'PHPMailer/SMTP.php';
                    require 'PHPMailer/Exception.php';
                    if($_SERVER['REQUEST_METHOD'] == 'POST'){
                    if(isset($_POST['submitOwner'])){
                        $fname = $_POST['fname'];
                        $tel = $_POST['tel'];
                        $userMail = $_POST['userMail'];
                        $userMessage = $_POST['userMessage'];
                    if(empty($_POST['fname'])){
                            $error=true;
                            $fname_error = "Name and surname cannot be empty!";
                        }else{
                            $fname = $_POST['fname'];   
                            if(!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ\s]*$/", $fname)){
                                $fname_error = "Name and surname can only contain letters and spaces!";
                            }
                        }
                        if(empty($_POST['tel'])) {
                            $tel_error = "Phone number cannot be blank!";
                        }else{
                            $tel = $_POST['tel'];
                            if(!preg_match('/^[\+]?[0-9]{9,15}$/', $tel)) {
                                $tel_error = "The phone number should contain a minimum of 9 to 15 numbers!";
                            }
                        }
                    if(empty($_POST['userMail'])){
                            $userMail_error = "Email cannot be blank!";
                        }else{
                            $userMail = $_POST['userMail'];
                            if(!filter_var($userMail, FILTER_VALIDATE_EMAIL)) {
                                $userMail_error = "Email address is incorrect!";
                            }
                        }
                        if(empty($_POST['userMessage'])) {
                            $userMessage_error = "The content of the message cannot be empty!";
                        }else{
                            $userMessage = $_POST['userMessage'];
                            if(!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ0-9 ,.!?\'\"]*$/", $userMessage)){
                                $userMessage_error = "The content of the message cannot be special characters!";
                            }
                        }
                    if($fname_error == '' && $tel_error == '' && $userMail_error == '' && $userMessage_error == ''){
                        $mail = new PHPMailer(true);
                        $mail->CharSet = "UTF-8";
                        $mail->isSMTP();
                        $mail->Host = 'secret';
                        $mail->SMTPAuth = true;
                        $mail->Username = 'secret';
                        $mail->Password = 'secret';
                        $mail->Port = 465; // 587
                        $mail->SMTPSecure = 'ssl'; // tls
                        $mail->WordWrap = 50;  
                        $mail->setFrom('secret@secret.com');
                        $mail->Subject = "New message from visit-neum.com";
                        $mail->isHTML(true);
                        $query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
                    $dbstmt = $pdo->prepare($query);
                    $dbstmt->bindParam(1,$pages_id); 
                    $dbstmt->execute(); //in Xdebug this line of code return NULL for $pages_id if include jQuery file
                    $emails_other = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
                    $jsonData=array();
                        if(is_array($emails_other) && count($emails_other)>0){
                          foreach($emails_other as $email_other){
                            //var_dump($email_other['email_address']);
                            $mail->addAddress($email_other['email_address']);
                            $body_other = "<p>Dear {$email_other['owner_name']}, <br>" . "You just received a message from the site <a href='https://www.visit-neum.com'>visit-neum.com</a><br>Details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "<br><strong>E-mail: </strong>" .strtolower($userMail)."<br><strong>Message: </strong>" . $userMessage . "</p>";
                    $mail->Body = $body_other;
                    if($mail->send()){
                                
                                $mail = "INSERT INTO visitneum.contact_owner(fname, tel, userMail, userMessage, email_address_id) VALUES(:fname, :tel, :userMail, :userMessage, :email_address_id)";
                                $stmt = $pdo->prepare($mail);
                                $stmt->execute(['fname' => $fname, 'tel' => $tel, 'userMail' => $userMail, 'userMessage' => $userMessage, 'email_address_id' => $email_other['email_address_id']]);
                    
                                    // Load AJAX
                                    if($error==false){
                                        $information['response'] = "success";
                                        $information['content'] = "Thanks " . ucwords($fname) . "! Your message has been successfully sent to the owner of property! You will get an answer soon!";
                                        $jsonData[] = $information;
                                    }
                    }//end if mail send         
                    else{   
                        $information['response'] = "error";
                        $information['content'] = "An error has occurred! Please try again..." . $mail->ErrorInfo;
                        $jsonData[]=$information;  
                    }
                    echo(json_encode($jsonData));
                    } // end foreach($emails_other as $email_other)
                    } // end if(is_array($emails_other) && count($emails_other)>0)
                    } // end if validation
                    } // end submitOwner
                    } // end REQUEST METHOD = POST
                    

                    And below you can see submitHandler for my jQuery file which causes me problem:

                     submitHandler: function(form){  
                          var formData=jQuery("#contactOwner").serialize();
                          console.log(formData);
                          jQuery.ajax({
                            url: "/inc/FormProcess.php",
                            type: "post",
                            dataType: "json",
                            data: formData,
                          success:function(jsonData) {
                             jQuery("#responseOwner").text(jsonData.content);
                             console.log(jsonData);
                          error: function (jqXHR, textStatus, errorThrown) {
                                        console.log(JSON.stringify(jqXHR));
                                        console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                                      }
                          }); // Code for AJAX Ends
                    // Clear all data after submit
                          var resetForm = document.getElementById('contactOwner').reset();
                          return false;
                        } // end submitHandler
                    

                    And the page which contains contact form is below:

                    <?php
                    include_once './inc/FormProcess.php';
                    ?>
                    <form  spellcheck="false" autocomplete="off" autocorrect="off" id='contactOwner' class='form' name='contactOwner' action='' method='POST'>
                    <h4 id="responseOwner" class="success">
                    <!-- This will hold response from the server --></h4>
                      <fieldset>
                        <legend>Vaši podaci</legend>
                            <div class="form-control halb InputIconBg"><input minlength="6" type="text" class="input username" name="fname" placeholder="Your name and surname ..." value="<?php echo Input::get('fname'); ?>"><i class="fas fa-user" aria-hidden="true"></i><span class="error"><?=$fname_error; ?></span></div><!-- end .form-control -->
                                
                            <div class="form-control halb InputIconBg"><input minlength="9" type="text" class="input phone" name="tel" placeholder="Your phone number..." value="<?php echo Input::get('tel'); ?>"><i class="fas fa-phone-alt" aria-hidden="true"></i><span class="error"><?=$tel_error; ?></span></div><!-- end .form-control -->
                    
                            <div class="form-control single InputIconBg"><input type="text" class="input mail" name="userMail" placeholder="Your e-mail..." value="<?php echo Input::get('userMail'); ?>" autocomplete="email"><i id="" class="fas fa-envelope owner_icon" aria-hidden="true"></i><span class="error"><?=$userMail_error; ?></span></div><!-- end .form-control --> 
                                
                            <div class="form-control InputIconBg"><textarea maxlength="1000" name="userMessage" class="textinput message" cols="46" rows="8" placeholder="Your message..."><?php echo Input::get('userMessage'); ?></textarea><i class="fas fa-pencil-alt owner_icon" aria-hidden="true"></i><span class="error"><?=$userMessage_error; ?></span></div><!-- end .form-control -->
                                
                        </fieldset>
                        <input type="submit" class="btn_submit" id="submitOwner" name="submitOwner" value="SENT"/>
                    </form>
                    <script defer src="/JS/validateOwner.js"></script>
                    

                    So, I can not figure out what is the problem and why $pages_id return null when include jQuery file. Also, I was forget to mention that code inside line if(is_array($emails_other) && count($emails_other)>0){ return number 0, so complete seguent code isn't executed, but of course this is normal, because $pages_id is null. However, I hope that somebody understand what is the problem and so, thanks in advance for any kind of help that you can give me.

                    ANSWER

                    Answered 2021-Dec-20 at 17:54

                    page_id is null in your script because you dont set it in the script.

                    So why not just adding an hidden input field in your froms with the page id and then in your PHP code

                    $page_id = $_POST['pageId'];


                    i think you did not understood ajax correclty. if you post your data to /inc/FormProcess.php it is not like an include before, where you could create variables first and then include it. AJax is like a sub call to the script. it is like if you would open ONLY this scrirpt provided in URL. so at this point you dont have your variables.

                    you need to get the variables or send your ajax request NOT to /inc/FormProcess.php but to the script where you define the variable

                    Source https://stackoverflow.com/questions/70425907

                    Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                    Vulnerabilities

                    No vulnerabilities reported

                    Install PHPMailer

                    PHPMailer is available on Packagist (using semantic versioning), and installation via Composer is the recommended way to install PHPMailer. Just add this line to your composer.json file:. Note that the vendor folder and the vendor/autoload.php script are generated by Composer; they are not part of PHPMailer. If you want to use the Gmail XOAUTH2 authentication class, you will also need to add a dependency on the league/oauth2-client package in your composer.json.
                    While installing the entire package manually or with Composer is simple, convenient, and reliable, you may want to include only vital files in your project. At the very least you will need src/PHPMailer.php. If you're using SMTP, you'll need src/SMTP.php, and if you're using POP-before SMTP (very unlikely!), you'll need src/POP3.php. You can skip the language folder if you're not showing errors to users and can make do with English-only errors. If you're using XOAUTH2 you will need src/OAuth.php as well as the Composer dependencies for the services you wish to authenticate with. Really, it's much easier to use Composer!.

                    Support

                    Start reading at the GitHub wiki. If you're having trouble, head for the troubleshooting guide as it's frequently updated. Examples of how to use PHPMailer for common scenarios can be found in the examples folder. If you're looking for a good starting point, we recommend you start with the Gmail example. To reduce PHPMailer's deployed code footprint, examples are not included if you load PHPMailer via Composer or via GitHub's zip file download, so you'll need to either clone the git repository or use the above links to get to the examples directly. Complete generated API documentation is available online. You can generate complete API-level documentation by running phpdoc in the top-level folder, and documentation will appear in the docs folder, though you'll need to have PHPDocumentor installed. You may find the unit tests a good reference for how to do various operations such as encryption. If the documentation doesn't cover what you need, search the many questions on Stack Overflow, and before you ask a question about "SMTP Error: Could not connect to SMTP host.", read the troubleshooting guide.

                    DOWNLOAD this Library from

                    Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                    over 430 million Knowledge Items
                    Find more libraries
                    Reuse Solution Kits and Libraries Curated by Popular Use Cases
                    Explore Kits

                    Save this library and start creating your kit

                    Share this Page

                    share link
                    Reuse Pre-built Kits with PHPMailer
                    Consider Popular Email Libraries
                    Try Top Libraries by PHPMailer
                    Compare Email Libraries with Highest Support
                    Compare Email Libraries with Highest Quality
                    Compare Email Libraries with Highest Security
                    Compare Email Libraries with Permissive License
                    Compare Email Libraries with Highest Reuse
                    Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                    over 430 million Knowledge Items
                    Find more libraries
                    Reuse Solution Kits and Libraries Curated by Popular Use Cases
                    Explore Kits

                    Save this library and start creating your kit

                    • © 2022 Open Weaver Inc.