skip to Main Content

The code below used to work fine a while ago, sending emails with images to Blogger’s email; or sending emails to any provided email address. Unfortunately I have no idea when it stopped working and how to fix it. The error given is

Array ( [type] => 2 [message] => preg_match() expects parameter 2 to be string, array given [file] => /var/www/html/PHPMailer.php [line] => 4533 )

Below is the page, I appreciate if someone could fix it.

<?php
// error_reporting(0);
// ini_set('display_errors', 0);
var_dump($_POST["name"]); 
var_dump($_POST["age"]);
var_dump($_FILES);
    use PHPMailerPHPMailerPHPMailer;
    use PHPMailerPHPMailerException;

$error = '';
$name = '';
$age = '';
$email = '';
$subject = '';
$country = '';
$message = '';
$msg = '';
$youtube = '';

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>';
  }
 }
 //age
 if(empty($_POST["age"]))
 {
  $error .= '<p><label class="text-danger">Please Enter your Age</label></p>';
 }
 else
 {
  $age = clean_text($_POST["age"]);
  if(!preg_match("/^[0-9]*$/",$age))
  {
   $error .= '<p><label class="text-danger">Only numbers allowed</label></p>';
  }
 }
 //age
 //i am
 if(empty($_POST['formGender'])) 
{
  $error .= '<p><label class="text-danger">Select your gender</label></p>';
}
 //i am
  //looking for
 if(empty($_POST['formGender2'])) 
{
  $error .= '<p><label class="text-danger">Select your Partner</label></p>';
}
  //looking for
    //for
 if(empty($_POST['formGender3'])) 
{
  $error .= '<p><label class="text-danger">Select your preferences</label></p>';
}
  //for
 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">City/Town is required</label></p>';
 }
 else
 {
  $subject = clean_text($_POST["subject"]);
 }
 //country 
 if(empty($_POST["country"]))
 {
  $error .= '<p><label class="text-danger">Country is required</label></p>';
 }
 else
 {
  $subject = clean_text($_POST["country"]);
 }
 //country
 if(empty($_POST["youtube"]))
 {
 // $error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
 }
 else
 {
  $youtube = clean_text($_POST["youtube"]);
 }
 if(empty($_POST["message"]))
 {
  $error .= '<p><label class="text-danger">Message is required</label></p>';
 }
 else
 {
  $message = clean_text($_POST["message"]);
 }
 if(empty($_POST["phone"]))
 {
 // $error .= '<p><label class="text-danger">Message is required</label></p>';
 }
 else
 {
  $phone = clean_text($_POST["phone"]);
 }
 
 
 if($error == '')
 {
if (array_key_exists('userfile', $_FILES)) {
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
$ip = $_SERVER['REMOTE_ADDR'];
    require 'Exception.php';
    require 'PHPMailer.php';
    require 'SMTP.php';
    $mail = new PHPMailer;
  $mail->IsSMTP();        //Sets Mailer to send message using SMTP
  $mail->Host = 'smtp.gmail.com';  //Sets the SMTP hosts
  $mail->Port = '465';        //Sets the default SMTP server port
  $mail->SMTPAuth = true;       //Sets SMTP authentication. Utilizes the Username and Password variables
  $mail->Username = 'asdfdfgndfbgasdf';     //Sets SMTP username
  $mail->Password = 'asdfsgdbfsfg';     //Sets SMTP password
  $mail->SMTPSecure = 'ssl';       //Sets connection prefix. Options are "", "ssl" or "tls"
  $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 protected]', 'Name');//Adds a "To" address
  $mail->AddCC($_POST["email"], $_POST["name"]); //Adds a "Cc" address
  $mail->WordWrap = 1000;       //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 = $_POST["name"] . ', ' . $_POST['formGender'] . ' (' . $_POST["age"] . ') looking to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ' ' . $_POST["country"];    //Sets the Subject of the message
 if(empty($_POST["youtube"]))
 {
  $mail->Body = '<div id="intro"> Meet <span style="text-transform: capitalize;">' . $_POST["name"] . '</span>, a ' . $_POST["age"] . ' yo ' . $_POST["formGender"] . ' looking for ' . $_POST["formGender2"] . ' to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ' ' . $_POST["country"] . '. If you want to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ', ' . $_POST["country"] . ', leave a message for ' . $_POST["name"] . ' on this page or use the contact details below.<br/><br/><strong>Email</strong> ' . $_POST["email"] . ' <br/><strong>Phone</strong> ' .  $_POST["phone"] . '.</div><div id="beforeblock">... more about ' . $_POST["name"] . ' below, in their own words: </div><div style="clear:both;"></div><blockquote>' . $_POST["message"] . '</blockquote><div id="regip">Profile registered from IP <strong><a href="https://href.li/?https://whatismyipaddress.com/ip/' . $ip . '" rel="nofollow noopener noreferrer" target="_blank">' . $ip . '</a></strong></div><iframe width="600" height="500" id="gmap_canvas" src="https://maps.google.com/maps?q=' . $_POST['subject'] . ',' . $_POST['country'] . '&t=&z=10&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" loading="lazy" style="width:100%;max-width:100%;height:auto;min-height:315px;"></iframe><br/><span id="tags">' . $_POST['formGender'] . ', ' . $_POST['subject'] . ', ' . $_POST['country'] . '</span>';     //An HTML or plain text message body
 }
 if($_POST["youtube"])
 {
  $mail->Body = '<div id="intro"> Meet <span style="text-transform: capitalize;">' . $_POST["name"] . '</span>, a ' . $_POST["age"] . ' yo ' . $_POST["formGender"] . ' looking for ' . $_POST["formGender2"] . ' to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ' ' . $_POST["country"] . '. If you want to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ', ' . $_POST["country"] . ', leave a message for ' . $_POST["name"] . ' on this page or use the contact details below.<br/><br/><strong>Email</strong> ' . $_POST["email"] . ' <br/><strong>Phone</strong> ' .  $_POST["phone"] . '.</div><div id="beforeblock">... more about ' . $_POST["name"] . ' below, in their own words: </div><div style="clear:both;"></div><blockquote>' . $_POST["message"] . '</blockquote><iframe loading="lazy" style="width:100%;min-height:315px;height:auto;margin:0 5px;" width="560" height="315" src="https://www.youtube.com/embed/' . $_POST["youtube"] . '" title="Video" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" id="youtubeframe" allowfullscreen></iframe><div id="regip">Profile registered from IP <strong><a href="https://href.li/?https://whatismyipaddress.com/ip/' . $ip . '" rel="nofollow noopener noreferrer" target="_blank">' . $ip . '</a></strong></div><iframe width="600" height="500" id="gmap_canvas" src="https://maps.google.com/maps?q=' . $_POST['subject'] . ',' . $_POST['country'] . '&t=&z=10&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" loading="lazy" style="width:100%;max-width:100%;height:auto;min-height:200px;"></iframe><br/><span id="tags">' . $_POST['formGender'] . ', ' . $_POST['subject'] . ', ' . $_POST['country'] . '</span>';    //An HTML or plain text message body
}
  $mail->set('X-Priority', '3'); //Priority 1 = High, 3 = Normal, 5 = low

//photo 

    //Attach multiple files one by one
    for ($ct = 0, $ctMax = count($_FILES['userfile']['tmp_name']); $ct < $ctMax; $ct++) {
        //Extract an extension from the provided filename
        $ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
        //Define a safe location to move the uploaded file to, preserving the extension
        $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct])) . '.' . $ext;
        $filename = $_FILES['userfile']['name'][$ct];
        if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
            if (!$mail->addAttachment($uploadfile, $filename)) {
                $msg .= 'Failed to upload the photos ' . $filename;
            }
        } else {
            $msg .= 'Failed to move photo to ' . $uploadfile;
        }
    }

// $mail->AddAttachment($image_location);
//photos
  
  if($mail->Send())        //Send an Email. Return true on success or false on error
  {
   $error = '<label class="text-success">Thank you for registering your profile. It will be visible soon after aproval.</label><style>.form-container {display:none!important;}</style>';
  }
  else
  {
   $error = '<label class="text-danger">Your profile was not registered. Please try again!</label>';
//   $errorMessage = error_get_last()['message'];
//    echo $errorMessage;
//   var_dump($_FILES);
print_r(error_get_last());
  }
  $name = '';
  $age = '';
  $email = '';
  $subject = '';
  $country = '';
  $message = '';
  $msg = '';
  $youtube = '';
  } //if img check ends
 } //if error ends
 
}

?>
<!DOCTYPE html>
<html>
 <head>
  <style>
.form-container{width:96%;MAX-WIDTH:96%;margin:0 2%;}
.form-group{margin-bottom:10px}
.btn{background:#1c94ff;padding:4px 8px;border:none;box-shadow:2px 1px 1px #d3d3d3;color:#fff;outline:0;font-size:17px;cursor:pointer;width:100%}
label{display:block;margin-bottom:2px}
.form-group .form-control{width:100%;outline:0;padding:5px;border:none;background:#d1d1d1;border-bottom:2px solid #1c94ff;font-size:16px}
.has-success .form-control{border-bottom:2px solid #168b3f}
.has-danger .form-control{border-bottom:2px solid #dc1d34}
.form-group .text-help{color:#dc1d34}
.inline-label label{display:inline}
.pristine-error{display:table}
  </style>

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script type="text/javascript">
if (typeof jQuery == 'undefined'){
    document.write(unescape("%3Cscript src='//cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.slim.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
 </head>
 <body>
     <?php echo $error; ?>
     <div style="float:right;font-style: italic;"><span style="color:red;font-style: normal;">!</span> = mandatory</div>

<div class="form-container">
     <form method="post" enctype="multipart/form-data" id="registercafebar">
     <div class="form-group">
       <label><span style="color:red">!</span> Name</label>
       <input type="text" name="name" required minlength="3" maxlength="20" placeholder="Enter Your Name" class="form-control" value="<?php echo $name; ?>" />
     </div>
     <div class="form-group">
       <label><span style="color:red">!</span> Age</label>
       <input required type="number" minlength="2" maxlength="2" min="16" max="99" name="age" placeholder="Enter your real age" class="form-control" value="<?php echo $age; ?>" />
     </div>
     <div class="form-group">
       <label><span style="color:red">!</span> I am a</label>
<select required name="formGender" class="form-control">
    <option value="">Select your gender at birth</option>
    <option value="woman">Woman</option>
    <option value="man">Man</option>
</select>
     </div>
     <div class="form-group">
       <label><span style="color:red">!</span> Looking for a</label>
<select name="formGender2" required class="form-control">
  <option value="">Select who you are looking for</option>
  <option value="man">Man</option>
  <option value="woman">Woman</option>
  <option value="couples">Couple</option>
</select>
     </div>
     <div class="form-group">
       <label><span style="color:red">!</span> For</label>
<select name="formGender3" required class="form-control">
  <option value="">Select what your intentions are</option>
  <option value="date">Dating</option>
  <option value="chat">Chat</option>
  <option value="marry">Marriage</option>
  <option value="have sex">Sex</option>
</select>
     </div> 
      
     <div class="form-group">
       <label><span style="color:red">!</span> City</label>
       <input type="text" name="subject" required class="form-control" minlength="2" maxlength="25" placeholder="Enter your City/Town" value="<?php echo $subject; ?>" />
     </div>
     <div class="form-group">
       <label><span style="color:red">!</span> Country</label>
       <input type="text" name="country" required class="form-control" minlength="2" maxlength="20" placeholder="Enter your Country" value="<?php echo $country; ?>" />
     </div>
     <div class="form-group">
       <label><span style="color:red">!</span> About me </label>
       <textarea name="message" cols="30" rows="5" minlength="200" maxlength="1000" required class="form-control" placeholder="Describe who you are and what you are looking for, write about the things you like or dislike or talk about your hobbies, but keep it spam free."><?php echo $message; ?></textarea>
     </div>
     <div class="form-group">
       <label><span style="color:red">!</span> Email</label>
       <input type="email" name="email" class="form-control" minlength="6" maxlength="30" required placeholder="Enter Your Email" value="<?php echo $email; ?>" />
     </div>
     <div class="form-group">
       <label>Phone</label>
       <input type="number" name="phone" class="form-control" minlength="4" maxlength="25" placeholder="Enter Your Phone" value="<?php echo $phone; ?>" />
     </div>
     
     <div class="form-group">
       <label>Youtube video ID <br/><span style="text-decoration: line-through;">https://www.youtube.com/watch?v=</span><strong style="padding:0 5px;border:1px solid gray;">fhgnfyhfth</strong></label>
       <input type="text" name="video" class="form-control" minlength="5" maxlength="15" placeholder="Enter Your Youtube video" value="<?php echo $youtube; ?>" />
     </div>
     
     <div class="form-group">
     <input type="hidden" name="MAX_FILE_SIZE" value="10000000">
        <span style="color:red">!</span> Photos:
        <input name="userfile[]" required type="file" multiple="multiple" accept="image/*">
</div>
    <div id="message"><span style="color:red">!</span> Please verify:</div>
            <div id="success">Perfect ✓</div>
            <div id="fail"><span style="color:red">!</span> Try again</div>
<p id="question"></p> <input id="ans" type="text">

<p><span style="color:red">!</span> Are you human?<br/> No <input type="checkbox" name="no"> Yes <input type="checkbox" name="yes" required></p>
<script>
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
</script>
<div class="form-group inline-label">
          <span style="color:red">!</span>  <input id="ch1" type="checkbox" name="future" required data-pristine-required-message="You must accept the terms and conditions"/>
          <label for="ch1">I accept the terms  and conditions</label><br/>
      </div>
      <div class="form-group">
       <input type="submit" name="submit" value="Register" class="btn btn-info" disabled="disabled"  /><!--disabled="disabled"-->
      </div>
     </form>
</div>
<div class="timer" onload="timer(1800)">
  <div class="time">
    <strong>Time until the page will refresh: <span id="time">Loading...</span></strong>
  </div>
</div>
<br/>
<script>
     var total;
function getRandom() {
  return Math.ceil(Math.random() * 20);
}
function createSum() {
  var randomNum1 = getRandom(),
    randomNum2 = getRandom();
  total = randomNum1 + randomNum2;
  jQuery("#question").text(randomNum1 + " + " + randomNum2 + "=");
  jQuery("#ans").val('');
  checkInput();
}

function checkInput() {
  var input = jQuery("#ans").val(),
    slideSpeed = 200,
    hasInput = !!input,
    valid = hasInput && input == total;
  jQuery('#message').toggle(!hasInput);
  jQuery('input[type=submit]').prop('disabled', !valid);
  jQuery('#success').toggle(valid);
  jQuery('#fail').toggle(hasInput && !valid);
}

jQuery(document).ready(function() {
  //create initial sum
  createSum();
  // On "reset button" click, generate new random sum
  jQuery('input[type=reset]').click(createSum);
  // On user input, check value
  jQuery("#ans").keyup(checkInput);
  //cookie registered
});
     </script>
   
 </body>
</html>

If it matters, I am using PHP 7.3, NginX. From my knowledge, same config as when the script used to work.

Also tried this:

Adding the following right after <?php, following the comments

var_dump($_POST["name"]); 
var_dump($_POST["age"]);
var_dump($_FILES);

Returns this before submitting the form:

NULL NULL array(0) { }

And this after submitting the form:

string(14) "Johny macaroni" string(2) "22" array(1) { ["userfile"]=> array(5) { ["name"]=> array(1) { [0]=> string(8) "oslo.png" } ["type"]=> array(1) { [0]=> string(9) "image/png" } ["tmp_name"]=> array(1) { [0]=> string(14) "/tmp/phpen1nVm" } ["error"]=> array(1) { [0]=> int(0) } ["size"]=> array(1) { [0]=> int(28358) } } }

2

Answers


  1. Chosen as BEST ANSWER

    In the end, the problem was not related to my script at all. It was the Gmail and Outlook SMTP services that, for some reason, refused to honor the script's SMTP requests; both of them.

    So, after switching to a 3rd free SMTP provider, everything started to work as it did before. Solved.


  2. There are quite a few nonsensical things in here. It looks like you’ve adapted this from a very old example.

    The require statements inside the function mean that this will crash the second time you call the function.

    You’re preprocessing the email address into $email but not using that variable when actually setting the recipient.

    You’re forging the from address, which is likely to mean your messages will not be delivered.

    Sending a copy to the supposed sender means your script is a spam gateway that can be abused to send arbitrary content to arbitrary recipients. This is bad and will be mercilessly exploited by spammers.

    Port is an integer, not a string:

    $mail->Port = 465;
    

    This will do nothing useful:

    $mail->set('X-Priority', '3');
    

    If you want to add a custom header, use addCustomHeader. If you want to set a priority, set the Priority property, which is also an int:

    $mail->Priority = 3;
    

    Overall, base your code on the examples provided, particularly the contact form example.

    Update

    Now that we have a location for the error, we can see that it’s in the call to PHPMailer::mb_pathinfo, which passes in $_FILES['userfile']['name'] as the $path parameter, and not in addCC as I had guessed. The HTML form declares this input as an array of file type allowing multiple values:

    <input name="userfile[]" required type="file" multiple="multiple" accept="image/*">
    

    This means that $_FILES['userfile']['name'] will be an array, not a string (see the PHP docs), which is the cause of the error.

    The fix here is to get the name property of the individual file, not the array of all of them, which is done by adding the array index, so this line:

    $ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
    

    should be:

    $ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'][$ct], PATHINFO_EXTENSION);
    

    This bug was previously present in the example code that this was originally adapted from, though that was fixed 6 months ago.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search