Jump to content

ianhaney

Members
  • Posts

    330
  • Joined

  • Last visited

Posts posted by ianhaney

  1. Manged to get the array printed out and the results are below

     

    Array
    (
        [name] => Array
            (
                [0] => 
            )
    
        [type] => Array
            (
                [0] => 
            )
    
        [tmp_name] => Array
            (
                [0] => 
            )
    
        [error] => Array
            (
                [0] => 4
            )
    
        [size] => Array
            (
                [0] => 0
            )
    
    )

    Looking at the error codes online, it looks like 4 means no file was uploaded but I need the upload file be optional so the form can be submitted without files uploaded as well as files uploaded and only allow jpg, png files to be uploaded if a user does upload a file or files

  2. I put the code in like below but does not say what's in the userfile, just says the same notice about only the jpg etc files allowed

     

    $allowed = array( 'jpg', 'jpeg', 'gif', 'png');
            if (is_array($_FILES['userfile'])) {
                foreach($_FILES['userfile']['name'] as $name) {
        $type = pathinfo($name, PATHINFO_EXTENSION);
            if(!in_array($type, $allowed))
                die("Error: Only jpg, jpeg, gif and png files are allowed.-".$type);
            }
        }
    }
    
    echo "<pre>";
    print_r($_FILES['userfile']);
    echo "</pre>";

    Have I put the print code in the wrong place?

  3. Getting closer, I have updated the code to below and it now gives me the notice if trying to upload a file that is not allowed so go back to the form and upload the correct file types and it send the email and redirects me to the confirmation page but if try to send the form with no files attached, I get the notice Error: Only jpg, jpeg, gif and png files are allowed.

    $msg = '';
    if (array_key_exists('userfile', $_FILES)) {
    
    // create object of PHPMailer class with boolean parameter which sets/unsets exception.
    $mail = new PHPMailer(true);
        
        //$mail->isSMTP(); // using SMTP protocol
        $mail->Host = 'host'; // SMTP host as gmail 
        $mail->SMTPAuth = true;  // enable smtp authentication
        $mail->Username = 'emailaddress';  // sender gmail host              
        $mail->Password = 'emailpassword'; // sender gmail host password                          
        $mail->SMTPSecure = 'ssl';  // for encrypted connection                           
        $mail->Port = 587;   // port for SMTP     
    
        $mail->setFrom('emailaddress', "Name"); // sender's email and name
        $mail->addAddress('emailaddress', "Name");  // receiver's email and name
        
        $attachmentNames = [];
        
        $allowed = array( 'jpg', 'jpeg', 'gif', 'png');
            if (is_array($_FILES['userfile'])) {
                foreach($_FILES['userfile']['name'] as $name) {
        $type = pathinfo($name, PATHINFO_EXTENSION);
            if(!in_array($type, $allowed))
                die("Error: Only jpg, jpeg, gif and png files are allowed.-".$type);
            }
        }
    }
        
        //Attach multiple files one by one
        for ($ct = 0, $ctMax = count($_FILES['userfile']['tmp_name']); $ct < $ctMax; $ct++) {
            $uploadfile=$name.'.'.pathinfo($name, PATHINFO_EXTENSION);
            $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
            $filename = $_FILES['userfile']['name'][$ct];
            if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
                if ($mail->addAttachment($uploadfile, $filename)) {
                $attachmentNames[] = $_FILES['userfile']['name'][$ct];
            } else {
                $msg .= 'Failed to attach file ' . $_FILES['userfile']['name'][$ct];
                }
            } else {
                $msg .= 'Failed to move file to ' . $uploadfile;
                }
            }
    
    $mail->Subject = 'New Repair Booking Made At' . ' ' .date('d-m-Y H:i:s');
        
        $mail->Body    = "A new repair has been booked in. This repair booking was made at " . $date = date('d-m-Y H:i:s') . "\r\n\r\n" . "The repair information is below" . "\r\n\r\n" . "Repair Date/Time: " . $_POST["date"] . "\r\n" . "Device: " . $_POST["selectdevice"] . "\r\n" . "Brand: " . $_POST["selectbrand"] . "\r\n" . "Name: " . $_POST["name"] . "\r\n" . "Email: " . $_POST["email"] . "\r\n" . "Phone Number: " . $_POST["phone"] . "\r\n" . "Repair Description/Issue: " . $_POST["repairdescription"] . "\r\n\r\n" . "Attached Filename(s): " . implode(', ', $attachmentNames);
            
    $response = $_POST["g-recaptcha-response"];
    
    	$url = 'https://www.google.com/recaptcha/api/siteverify';
    	$data = array(
    		'secret' => 'SECRETKEY',
    		'response' => $_POST["g-recaptcha-response"]
    	);
        $query = http_build_query($data);
    	$options = array(
    		'http' => array (
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
                "Content-Length: ".strlen($query)."\r\n".
                "User-Agent:MyAgent/1.0\r\n",
    			'method' => 'POST',
    			'content' => $query
    		)
    	);
    	$context  = stream_context_create($options);
    	$verify = file_get_contents($url, false, $context);
    	$captcha_success=json_decode($verify);
    
    	if ($captcha_success->success==false) {
    		echo "<p>You are a bot! Go away!</p>";
            echo "<br><a href=\"javascript:history.go(-1)\">Go Back To Form</a>";
            exit();
        } else if ($captcha_success->success==true) {
            
            if(!$mail->send()) {
                echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
            } else {
        header('Location:booking-confirmation.php');
        }
        };

     

  4. Tried it again and still getting a blank white page but no error log this time on the server so guessing the code is almost correct and it's sending the email if there is attachments but if no attachments it shows the error message Error: Only jpg, jpeg, gif and png files are allowed.-

    and it's not redirecting to the confirmation page when there are files attached and guessing will do the same when no files are attached

  5. The whole code is below as thought that might be better to post the whole code and to follow

     

    $msg = '';
    if (array_key_exists('userfile', $_FILES)) {
    
    // create object of PHPMailer class with boolean parameter which sets/unsets exception.
    $mail = new PHPMailer(true);
    try {
        
        //$mail->isSMTP(); // using SMTP protocol
        $mail->Host = 'host'; // SMTP host as gmail 
        $mail->SMTPAuth = true;  // enable smtp authentication
        $mail->Username = 'emailaddress';  // sender gmail host              
        $mail->Password = 'emailpassword'; // sender gmail host password                          
        $mail->SMTPSecure = 'ssl';  // for encrypted connection                           
        $mail->Port = 587;   // port for SMTP     
    
        $mail->setFrom('emailaddress', "Name"); // sender's email and name
        $mail->addAddress('emailaddress', "Name");  // receiver's email and name
        
        $attachmentNames = [];
        
        $allowed = array( 'jpg', 'jpeg', 'gif', 'png');
            if (is_array($_FILES['userfile'])) {
                foreach($_FILES['userfile']['name'] as $name) {
        $type = pathinfo($name, PATHINFO_EXTENSION);
            if(!in_array($type, $allowed))
                die("Error: Only jpg, jpeg, gif and png files are allowed.-".$type);
            }
        }
        
        //Attach multiple files one by one
        for ($ct = 0, $ctMax = count($_FILES['userfile']['tmp_name']); $ct < $ctMax; $ct++) {
            $uploadfile=$name.'.'.pathinfo($name, PATHINFO_EXTENSION);
            $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
            $filename = $_FILES['userfile']['name'][$ct];
            if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
                if ($mail->addAttachment($uploadfile, $filename)) {
                $attachmentNames[] = $_FILES['userfile']['name'][$ct];
            } else {
                $msg .= 'Failed to attach file ' . $_FILES['userfile']['name'][$ct];
                }
            } else {
                $msg .= 'Failed to move file to ' . $uploadfile;
                }
            }
    
    $mail->Subject = 'New Repair Booking Made At' . ' ' .date('d-m-Y H:i:s');
        
        $mail->Body    = "A new repair has been booked in. This repair booking was made at " . $date = date('d-m-Y H:i:s') . "\r\n\r\n" . "The repair information is below" . "\r\n\r\n" . "Repair Date/Time: " . $_POST["date"] . "\r\n" . "Device: " . $_POST["selectdevice"] . "\r\n" . "Brand: " . $_POST["selectbrand"] . "\r\n" . "Name: " . $_POST["name"] . "\r\n" . "Email: " . $_POST["email"] . "\r\n" . "Phone Number: " . $_POST["phone"] . "\r\n" . "Repair Description/Issue: " . $_POST["repairdescription"] . "\r\n\r\n" . "Attached Filename(s): " . implode(', ', $attachmentNames);
            
    $response = $_POST["g-recaptcha-response"];
    
    	$url = 'https://www.google.com/recaptcha/api/siteverify';
    	$data = array(
    		'secret' => 'SECRETKEY',
    		'response' => $_POST["g-recaptcha-response"]
    	);
        $query = http_build_query($data);
    	$options = array(
    		'http' => array (
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
                "Content-Length: ".strlen($query)."\r\n".
                "User-Agent:MyAgent/1.0\r\n",
    			'method' => 'POST',
    			'content' => $query
    		)
    	);
    	$context  = stream_context_create($options);
    	$verify = file_get_contents($url, false, $context);
    	$captcha_success=json_decode($verify);
    
    	if ($captcha_success->success==false) {
    		echo "<p>You are a bot! Go away!</p>";
            echo "<br><a href=\"javascript:history.go(-1)\">Go Back To Form</a>";
            exit();
        } else if ($captcha_success->success==true) {
            
            if(!$mail->send()){
        header('Location:booking-confirmation.php');
        }
        }    } catch (Exception $e) { // handle error.
        echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
            }
    };

     

  6. I updated the code to the following

     

    $allowed = array( 'jpg', 'jpeg', 'gif', 'png');
            if (is_array($_FILES['userfile'])) {
                foreach($_FILES['userfile']['name'] as $name) {
        $type = pathinfo($name, PATHINFO_EXTENSION);
            if(!in_array($type, $allowed))
                die("Error: Only jpg, jpeg, gif and png files are allowed.-".$type);
            }
        }

    and below

     

    //Attach multiple files one by one
        for ($ct = 0, $ctMax = count($_FILES['userfile']['tmp_name']); $ct < $ctMax; $ct++) {
            $uploadfile=$name.'.'.pathinfo($name, PATHINFO_EXTENSION);
            $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
            $filename = $_FILES['userfile']['name'][$ct];
            if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
                if ($mail->addAttachment($uploadfile, $filename)) {
                $attachmentNames[] = $_FILES['userfile']['name'][$ct];
            } else {
                $msg .= 'Failed to attach file ' . $_FILES['userfile']['name'][$ct];
                }
            } else {
                $msg .= 'Failed to move file to ' . $uploadfile;
                }
            }

    But seem to be getting new errors that I did not get before

    The errors are below

    PHP Notice:  file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded in booking-process.php on line 76
    PHP Fatal error:  Uncaught Error: Call to undefined function json_decode() in booking-process.php:77
    Stack trace:
    #0 {main}
      thrown in booking-process.php on line 77

    Line 76 is $verify = file_get_contents($url, false, $context);

    Line 77 is $captcha_success=json_decode($verify);

  7. Been playing about with the code and getting there I think, it now works and shows the message if I try to send the form with a incorrect file type, it gives me the notice that it's the wrong file type and have to go back to the form to upload the correct file type and the code sends the form with the correct file type so that bit is all ok and working but tested with no file attachment and it's saying the message as if I was selecting a non allowed file type, below is the updated code

     

    $allowed = array( 'jpg', 'jpeg', 'gif', 'png');
        foreach($_FILES['userfile']['name'] as $name) {
    	$type = pathinfo($name, PATHINFO_EXTENSION); 
    	if(!in_array($type, $allowed)) 
    	die("Error: Only jpg, jpeg, gif and png files are allowed.-".$type); 
        }
        
        //Attach multiple files one by one
        for ($ct = 0, $ctMax = count($_FILES['userfile']['tmp_name']); $ct < $ctMax; $ct++) {
            $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
            $filename = $_FILES['userfile']['name'][$ct];
            $uploadfile=$filename.'.'.pathinfo($filename, PATHINFO_EXTENSION);
            if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
                if ($mail->addAttachment($uploadfile, $filename)) {
                $attachmentNames[] = $_FILES['userfile']['name'][$ct];
            } else {
                $msg .= 'Failed to attach file ' . $_FILES['userfile']['name'][$ct];
                }
            } else {
                $msg .= 'Failed to move file to ' . $uploadfile;
                }
            }

    I think it may be just hopefully moving some of the code around

  8. I have currently updated the code to the following but does not say the message about only uploading jpg or png files, the email does work though if I do upload the wrong file and I receive the email but don't attach the wrong file type attachment but if I attach the correct file types, it sends the email with the attachments

     

    //Attach multiple files one by one
        for ($ct = 0, $ctMax = count($_FILES['userfile']['tmp_name']); $ct < $ctMax; $ct++) {
            $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
            	$filename = $_FILES['userfile']['name'][$ct];        
            		$FileType = pathinfo($filename, PATHINFO_EXTENSION);
            // Allow certain file formats
            $allowTypes = array('jpg', 'png', 'jpeg');
            	if(in_array($FileType, $allowTypes)){
            		if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
                		if ($mail->addAttachment($uploadfile, $filename)) {
                	$attachmentNames[] = $_FILES['userfile']['name'][$ct];
            } else {
                $msg .= 'Failed to attach file ' . $_FILES['userfile']['name'][$ct];
                }
            } else {
                $msg .= 'Failed to move file to ' . $uploadfile;
                }
            } else {
                $msg .= 'Sorry only jpg, png and jpeg files are allowed to upload';
            }
        }
    
    I do try and indent the code as best I can as know it's easier to read if indented correctly

     

  9. I found a example below but unsure how to know that only jpg or png files can be uploaded/attached

     

    $fname = $_FILES['file']['name'];
    $this->ext = pathinfo($fname, PATHINFO_EXTENSION);
    //I assume you've done the if move_upload thing to get the file to its destination
    $this->filename = $name.'-'.date('dmY-Hi').'-cv.'.$this->ext;
    $mail->AddAttachment('files/cvs/'.$this->filename, "CV File");

     

  10. I did try the following

     

    //Attach multiple files one by one
        for ($ct = 0, $ctMax = count($_FILES['userfile']['tmp_name']); $ct < $ctMax; $ct++) {
            $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
            $filename = $_FILES['userfile']['name'][$ct];
            
            $AllowedFileTypes = array("jpg","png"); // build array
            $FileName = $_FILES['userfile']['name']; // get filename of file input
            $FileType = end((explode(".", $FileName))); // get file type/extension
            if(in_array($FileType, $AllowedFileTypes)){ // check to see if file type is allowed
            if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
                if ($mail->addAttachment($uploadfile, $filename)) {
                $attachmentNames[] = $_FILES['userfile']['name'][$ct];
            } else {
                $msg .= 'Failed to attach file ' . $_FILES['userfile']['name'][$ct];
                }
            } else {
                $msg .= 'Failed to move file to ' . $uploadfile;
                }
            } else {
                $msg .= 'Only jpg and png files allowed';
                }
            }

    That just gives me the following errors

    PHP Warning: explode() expects parameter 2 to be string, array given PHP Warning: end() expects parameter 1 to be array, null given
     

    I got the code from https://stackoverflow.com/questions/41244570/allowed-extension-phpmailer

  11. How do I only allow jpg and png file extensions to be uploaded as a attachment. My current code is below

     

    $msg = '';
    if (array_key_exists('userfile', $_FILES)) {
    
    // create object of PHPMailer class with boolean parameter which sets/unsets exception.
    $mail = new PHPMailer(true);
    try {
        
        //$mail->isSMTP(); // using SMTP protocol
        $mail->Host = 'host'; // SMTP host as gmail 
        $mail->SMTPAuth = true;  // enable smtp authentication
        $mail->Username = 'emailaddress';  // sender gmail host              
        $mail->Password = 'emailpassword'; // sender gmail host password                          
        $mail->SMTPSecure = 'ssl';  // for encrypted connection                           
        $mail->Port = 587;   // port for SMTP     
    
        $mail->setFrom('emailaddress', "Name"); // sender's email and name
        $mail->addAddress('emailaddress', "Name");  // receiver's email and name
        
        $attachmentNames = [];
        
        //Attach multiple files one by one
        for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
            $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
            $filename = $_FILES['userfile']['name'][$ct];
            if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
                if(isset($uploadfile))
                $mail->addAttachment($uploadfile, $filename);
                $attachmentNames[] = $_FILES['userfile']['name'][$ct];
            } else {
                $msg .= 'Failed to move file to ' . $uploadfile;
            }
        }

     

  12. Sorry just managed to solve it with the following code and not got any errors

     

    //Attach multiple files one by one
        for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
            $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
            $filename = $_FILES['userfile']['name'][$ct];
            if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
                if(isset($uploadfile))
                $mail->addAttachment($uploadfile, $filename);
                $attachmentNames[] = $_FILES['userfile']['name'][$ct];
            } else {
                $msg .= 'Failed to move file to ' . $uploadfile;
            }
        }

     

  13. Just noticed with the above code, the form works and submits if there is no attachment or if I do upload a attachment but I get a error log with the following error

    PHP Warning:  file_exists() expects exactly 1 parameter, 2 given

    How should the code be as getting confused on it now

  14. Just solved the above issue with the code below

     

    //Attach multiple files one by one
        for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
            $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
            $filename = $_FILES['userfile']['name'][$ct];
            if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
                $mail->addAttachment($uploadfile, $filename);
                $attachmentNames[] = $_FILES['userfile']['name'][$ct];
            } else {
                $msg .= 'Failed to move file to ' . $uploadfile;
            }
            if (file_exists($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
                $mail->addAttachment($uploadfile, $filename);
            }
        }

     

  15. I am new to phpmailer and still trying to learn and understand it, I can do the basics in it if want to just use it to send a email but now want to use it to send attachments but the attachments are optional and only want to be able to send jpg and png attachments but am trying to concentrate on one thing at a time but getting frustrated with it. I am currently trying to get it so that the attachments are not required so if the user sends the form with no attachments, the form sends all ok and the same as if the user sends attachments, below is my current code but is not working, am getting unexpected errors as either ; or }

     

    $attachmentNames = [];
        
        //Attach multiple files one by one
        for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
            $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));        
            $filename = $_FILES['userfile']['name'][$ct];
            if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
                $mail->addAttachment($uploadfile, $filename);
                $attachmentNames[] = $_FILES['userfile']['name'][$ct];
            } else {
                $msg .= 'Failed to move file to ' . $uploadfile;
            }
            if ($mail->addAttachment {
                $msg .= 'Failed to attach file'
            }
        }
    
        $mail->Subject = 'New Repair Booking Made At' . ' ' .date('d-m-Y H:i:s');
                
        $mail->Body    = "A new repair has been booked in. This repair booking was made at " . $date = date('d-m-Y H:i:s') . "\r\n\r\n" . "The repair information is below" . "\r\n\r\n" . "Repair Date/Time: " . $_POST["date"] . "\r\n" . "Device: " . $_POST["selectdevice"] . "\r\n" . "Brand: " . $_POST["selectbrand"] . "\r\n" . "Name: " . $_POST["name"] . "\r\n" . "Email: " . $_POST["email"] . "\r\n" . "Phone Number: " . $_POST["phone"] . "\r\n" . "Repair Description/Issue: " . $_POST["repairdescription"] . "\r\n\r\n" . "Attached Filename(s): " . implode(', ', $attachmentNames);

     

  16. Think I just got it working with the following code

     

    <?php
    
    // PHPMailer classes into the global namespace
    use PHPMailer\PHPMailer\PHPMailer; 
    use PHPMailer\PHPMailer\Exception;
    // Base files 
    require 'PHPMailer/src/Exception.php';
    require 'PHPMailer/src/PHPMailer.php';
    require 'PHPMailer/src/SMTP.php';
    
    // create object of PHPMailer class with boolean parameter which sets/unsets exception.
    $mail = new PHPMailer(true);
    try {
        //$mail->isSMTP(); // using SMTP protocol
        $mail->Host = 'host'; // SMTP host as gmail 
        $mail->SMTPAuth = true;  // enable smtp authentication
        $mail->Username = 'emailaddress';  // sender gmail host              
        $mail->Password = 'password'; // sender gmail host password                          
        $mail->SMTPSecure = 'ssl';  // for encrypted connection                           
        $mail->Port = 587;   // port for SMTP     
    
        $mail->setFrom('emailaddress', "Business Name"); // sender's email and name
        $mail->addAddress('emailaddress', "Business Name");  // receiver's email and name
    
        $mail->Subject = 'New Website Enquiry';
        $mail->Body    = "A new website enquiry has been made. The enquiry information is below" . "\r\n\r\n" . "Name: " . $_POST["name"] . "\r\n" . "Email: " . $_POST["email"] . "\r\n" . "Subject: " . $_POST["subjectline"] . "\r\n" . "Message: " . $_POST["message"];
    
    $response = $_POST["g-recaptcha-response"];
    
    	$url = 'https://www.google.com/recaptcha/api/siteverify';
    	$data = array(
    		'secret' => 'SECRETKEY',
    		'response' => $_POST["g-recaptcha-response"]
    	);
    	$options = array(
    		'http' => array (
    			'method' => 'POST',
    			'content' => http_build_query($data)
    		)
    	);
    	$context  = stream_context_create($options);
    	$verify = file_get_contents($url, false, $context);
    	$captcha_success=json_decode($verify);
    
    	if ($captcha_success->success==false) {
    		echo "<p>You are a bot! Go away!</p>";
            echo "<br><a href=\"javascript:history.go(-1)\">Go Back To Form</a>";        
    	} else if ($captcha_success->success==true) {
            
            $mail->send();
        header('Location:enquiry-confirmation.php');
        }
            } catch (Exception $e) { // handle error.
        echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
    }
    ?>

     

  17. I normally use this code: https://www.codexworld.com/new-google-recaptcha-with-php/ but that code does not send the email to the client for some reason, they receive their emails through office 365 so switched to phpmailer and they receive the emails now but they get bit of spam emails so need to prevent the spam emails from going through so need a idea of the code to prevent the contact form sending if the checkbox is not checked

    Do I take bits of code from the link I put and put inside the sendenquiry.php file I have which has the phpmailer code in I posted above?

  18. I am still fairly new to using phpmailer and it works but I have been asked to google recaptcha v2 checkbox into their contact form but unsure how to do that within the phpmailer code, below is what I currently have

     

    <?php
    
    // PHPMailer classes into the global namespace
    use PHPMailer\PHPMailer\PHPMailer; 
    use PHPMailer\PHPMailer\Exception;
    // Base files 
    require 'PHPMailer/src/Exception.php';
    require 'PHPMailer/src/PHPMailer.php';
    require 'PHPMailer/src/SMTP.php';
    
    // create object of PHPMailer class with boolean parameter which sets/unsets exception.
    $mail = new PHPMailer(true);
    try {
        //$mail->isSMTP(); // using SMTP protocol
        $mail->Host = 'hostname'; // SMTP host as gmail 
        $mail->SMTPAuth = true;  // enable smtp authentication
        $mail->Username = 'emailaddress';  // sender gmail host              
        $mail->Password = 'emailpassword'; // sender gmail host password                          
        $mail->SMTPSecure = 'ssl';  // for encrypted connection                           
        $mail->Port = 587;   // port for SMTP     
    
        $mail->setFrom('emailaddress', "Business Name"); // sender's email and name
        $mail->addAddress('emailaddress', "Business Name");  // receiver's email and name
    
        $mail->Subject = 'New Website Enquiry';
        $mail->Body    = "A new website enquiry has been made. The enquiry information is below" . "\r\n\r\n" . "Name: " . $_POST["name"] . "\r\n" . "Email: " . $_POST["email"] . "\r\n" . "Subject: " . $_POST["subjectline"] . "\r\n" . "Message: " . $_POST["message"];
        
        $mail->send();
        header('Location:enquiry-confirmation.php');
        } catch (Exception $e) { // handle error.
        echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
        }
    ?>


    Can anyone help please as to where the code needs to go to check if the checkbox has been checked or not

  19. I have phpmailer on a website and after clicking send, it goes to the forms action page and don't seem to redirect to the enquiry confirmation page, the forms action page is a blank white page which am guessing is correct as it's PHP coding but thought it should redirect. I don't get any errors showing what the issue is. I have the phpmailer uploaded onto the FTP server and has the class.phpmailer.php file inside the phpmailer folder. The client has their email going through office365. Below is the code I have

    +

    <?php
    
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);
    
    //index.php
    
    $error = '';
    $name = '';
    $email = '';
    $subject = '';
    $message = '';
    
    function clean_text($string)
    {
    $string = trim($string);
    $string = stripslashes($string);
    $string = htmlspecialchars($string);
    return $string;
    }
    
    if(isset($_POST["submit"]))
    {
    if(empty($_POST["name"]))
    {
    $error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
    }
    else
    {
    $name = clean_text($_POST["name"]);
    if(!preg_match("/^[a-zA-Z ]*$/",$name))
    {
    $error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
    }
    }
    if(empty($_POST["email"]))
    {
    $error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
    }
    else
    {
    $email = clean_text($_POST["email"]);
    if(!filter_var($email, FILTER_VALIDATE_EMAIL))
    {
    $error .= '<p><label class="text-danger">Invalid email format</label></p>';
    }
    }
    if(empty($_POST["subject"]))
    {
    $error .= '<p><label class="text-danger">Subject is required</label></p>';
    }
    else
    {
    $subject = clean_text($_POST["subject"]);
    }
    if(empty($_POST["message"]))
    {
    $error .= '<p><label class="text-danger">Message is required</label></p>';
    }
    else
    {
    $message = clean_text($_POST["message"]);
    }
    if($error == '')
    {
    
    require 'phpmailer/class.phpmailer.php';
    $mail = new PHPMailer;
    $mail->SMTPDebug  = 2;
    $mail->IsSMTP();        //Sets Mailer to send message using SMTP
    $mail->Host = 'smtp.office365.com';  //Sets the SMTP hosts
    $mail->Port = '587';        //Sets the default SMTP server port
    $mail->SMTPSecure = 'tls';       //Sets connection prefix. Options are "", "ssl" or "tls"
    $mail->SMTPAuth = true;       //Sets SMTP authentication. Utilizes the Username and Password variables
    $mail->Username = 'email@domain.co.uk';     //Sets SMTP username
    $mail->Password = 'password';     //Sets SMTP password
    $mail->From = $_POST["email"];     //Sets the From email address for the message
    $mail->FromName = $_POST["name"];    //Sets the From name of the message
    $mail->AddAddress('email@domain.co.uk', 'Name');//Adds a "To" address
    $mail->AddCC($_POST["email"], $_POST["name"]); //Adds a "Cc" address
    $mail->WordWrap = 50;       //Sets word wrapping on the body of the message to a given number of characters
    $mail->IsHTML(true);       //Sets message type to HTML    
    $mail->Subject = "New Website Enquiry";    //Sets the Subject of the message
    $mail->Body = "Name: " . $_POST["name"] . "<br><br>" . "Email: " . $_POST["email"] . "<br><br>" . "Subject: " . $_POST["subject"] . "<br><br>" . "Message: " . "<br>" . $_POST["message"];    //An HTML or plain text message body
    if (!$mail->Send())        //Send an Email. Return true on success or false on error
    {
    header('Location: https://www.domain.co.uk/enquiry-confirmation.php');
    }
    else
    {
    $error = '<label class="text-danger">There is an Error</label>';
    }
    $name = '';
    $email = '';
    $subject = '';
    $message = '';
    }
    }
    ?>



     

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.