Can anyone help me figure out why my phpmailer suddenly stopped working after I updated my form

### Website URL

(please specify the URL of the site on which you are experiencing the problem)

none

(please share the FULL error message you see, if applicable)

submit php:

<?php

require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/functions.php';
require_once __DIR__.'/config.php';

session_start();

// Basic check to make sure the form was submitted.
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    redirectWithError("The form must be submitted with POST data.");
}

// Validate reCAPTCHA
if (empty($_POST['g-recaptcha-response'])) {
    redirectWithError("Please complete the CAPTCHA.");
}

$recaptcha = new \ReCaptcha\ReCaptcha(CONTACTFORM_RECAPTCHA_SECRET_KEY);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

if (!$resp->isSuccess()) {
    $errors = $resp->getErrorCodes();
    $error = $errors[0];

    $recaptchaErrorMapping = [
        'missing-input-secret' => 'No reCAPTCHA secret key was submitted.',
        'invalid-input-secret' => 'The submitted reCAPTCHA secret key was invalid.',
        'missing-input-response' => 'No reCAPTCHA response was submitted.',
        'invalid-input-response' => 'The submitted reCAPTCHA response was invalid.',
        'bad-request' => 'An unknown error occurred while trying to validate your response.',
        'timeout-or-duplicate' => 'The request is no longer valid. Please try again.',
    ];

    $errorMessage = $recaptchaErrorMapping[$error] ?? "Unknown error occurred during CAPTCHA validation.";
    redirectWithError("Please retry the CAPTCHA: " . $errorMessage);
}

// Validate required fields
$requiredFields = ['name', 'age', 'archetype', 'alignment', 'strength', 'dexterity', 'vitality', 'spirit'];

foreach ($requiredFields as $field) {
    if (empty($_POST[$field])) {
        redirectWithError("The field '$field' is required and must be filled.");
    }
}

// Collect furnace stats
$furnaceStats = [
    'Level' => $_POST['furnace-level'] ?? 'N/A',
    'Durability' => $_POST['furnace-durability'] ?? 'N/A',
    'Passive Effect' => $_POST['furnace-passive-effect'] ?? 'N/A',
    'Combat Effect' => $_POST['furnace-combat-effect'] ?? 'N/A',
    'Setup Time' => $_POST['furnace-setup-time'] ?? 'N/A',
    'Repair Time' => $_POST['furnace-repair-time'] ?? 'N/A',
    'Repair Cost' => $_POST['furnace-repair-cost'] ?? 'N/A',
    'Cost' => $_POST['furnace-cost'] ?? 'N/A',
];

// Prepare furnace stats details
$furnaceDetails = <<<EOT
Furnace Details:
Level: {$furnaceStats['Level']}
Durability: {$furnaceStats['Durability']}
Passive Effect: {$furnaceStats['Passive Effect']}
Combat Effect: {$furnaceStats['Combat Effect']}
Setup Time: {$furnaceStats['Setup Time']}
Repair Time: {$furnaceStats['Repair Time']}
Repair Cost: {$furnaceStats['Repair Cost']}
Cost: {$furnaceStats['Cost']}

EOT;

// Extract derived stats and currency data
$speed = $_POST['speed2'] ?? '';
$qigong = $_POST['qigong'] ?? '';
$hitpoints = $_POST['hitpoints'] ?? '';
$attackpoint = $_POST['attackpoint'] ?? '';
$defensepoint = $_POST['defensepoint'] ?? '';
$plat = $_POST['plat'] ?? '';
$gold = $_POST['gold'] ?? '';
$silver = $_POST['silver'] ?? '';
$copper = $_POST['copper'] ?? '';


// contact info
$contactEmail = $_POST['email'] ?? '';


// Validate email
function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

// Collect sanitized inputs
$contactEmail = sanitize($_POST['email'] ?? '');
if (!validateEmail($contactEmail)) {
    redirectWithError("Invalid email address provided.");
}


// Prepare manuals data dynamically
$manualKeys = ['basic', 'weapon', '0', '01']; // Prefixes for each manual

$manuals = []; // Initialize manuals array

foreach ($manualKeys as $key) {
    $manuals[] = [
        'name' => sanitize($_POST["{$key}-manual-name"] ?? 'N/A'),
        'technique' => sanitize($_POST["{$key}-manual-technique"] ?? 'N/A'),
        'qi_cost' => sanitize($_POST["{$key}-manual-qi-cost"] ?? 'N/A'),
        'effect' => sanitize($_POST["{$key}-manual-effect"] ?? 'N/A'),
        'cooldown' => sanitize($_POST["{$key}-manual-cooldown"] ?? 'N/A'),
        'learned' => sanitize($_POST["{$key}-manual-learned"] ?? 'N/A'),
    ];
}


$manualsText = ""; // For plain text version
$manualsDetails = '<table class="character-table">'; // For HTML version
$manualsDetails .= '<tr><th>#</th><th>Name</th><th>Technique</th><th>Qi Cost</th><th>Effect</th><th>Cooldown</th><th>Learned</th></tr>';

foreach ($manuals as $index => $manual) {
    $manualsDetails .= '<tr>';
    $manualsDetails .= '<td>' . ($index + 1) . '</td>';
    $manualsDetails .= '<td>' . htmlspecialchars($manual['name']) . '</td>';
    $manualsDetails .= '<td>' . htmlspecialchars($manual['technique']) . '</td>';
    $manualsDetails .= '<td>' . htmlspecialchars($manual['qi_cost']) . '</td>';
    $manualsDetails .= '<td>' . htmlspecialchars($manual['effect']) . '</td>';
    $manualsDetails .= '<td>' . htmlspecialchars($manual['cooldown']) . '</td>';
    $manualsDetails .= '<td>' . htmlspecialchars($manual['learned']) . '</td>';
    $manualsDetails .= '</tr>';

    $manualsText .= "Manual " . ($index + 1) . ":\n";
    $manualsText .= "Name: {$manual['name']}\n";
    $manualsText .= "Technique: {$manual['technique']}\n";
    $manualsText .= "Qi Cost: {$manual['qi_cost']}\n";
    $manualsText .= "Effect: {$manual['effect']}\n";
    $manualsText .= "Cooldown: {$manual['cooldown']}\n";
    $manualsText .= "Learned: {$manual['learned']}\n";
    $manualsText .= str_repeat('-', 40) . "\n";
}
$manualsDetails .= '</table>';



// Sanitize inputs
function sanitize($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

// Collect sanitized inputs
$name = sanitize($_POST['name'] ?? '');
$age = sanitize($_POST['age'] ?? '');
$gender = sanitize($_POST['gender'] ?? '');
$cultivationXp = sanitize($_POST['cultivation-xp'] ?? '');
$cultivationStage = sanitize($_POST['cultivation-stage'] ?? '');
$background = sanitize($_POST['background'] ?? '');
$archetype = sanitize($_POST['archetype'] ?? '');
$alignment = sanitize($_POST['alignment'] ?? '');
$strength = sanitize($_POST['strength'] ?? '');
$dexterity = sanitize($_POST['dexterity'] ?? '');
$vitality = sanitize($_POST['vitality'] ?? '');
$spirit = sanitize($_POST['spirit'] ?? '');
$speed = sanitize($_POST['speed2'] ?? '');
$qigong = sanitize($_POST['qigong'] ?? '');
$hitpoints = sanitize($_POST['hitpoints'] ?? '');
$attackpoint = sanitize($_POST['attackpoint'] ?? '');
$defensepoint = sanitize($_POST['defensepoint'] ?? '');
$plat = sanitize($_POST['plat'] ?? '');
$gold = sanitize($_POST['gold'] ?? '');
$silver = sanitize($_POST['silver'] ?? '');
$copper = sanitize($_POST['copper'] ?? '');
$furnaceType = sanitize($_POST['furnace'] ?? '');
$weapon = sanitize($_POST['weapon'] ?? '');
$artifact = sanitize($_POST['artifact'] ?? '');
$pills = sanitize($_POST['pills'] ?? '');
$talisman = sanitize($_POST['talisman'] ?? '');
$furnaceLevel = sanitize($_POST['furnace-level'] ?? '');
$furnaceDurability = sanitize($_POST['furnace-durability'] ?? '');
$furnacePassiveEffect = sanitize($_POST['furnace-passive-effect'] ?? '');
$furnaceCombatEffect = sanitize($_POST['furnace-combat-effect'] ?? '');
$furnaceSetupTime = sanitize($_POST['furnace-setup-time'] ?? '');
$furnaceRepairTime = sanitize($_POST['furnace-repair-time'] ?? '');
$furnaceRepairCost = sanitize($_POST['furnace-repair-cost'] ?? '');
$furnaceCost = sanitize($_POST['furnace-cost'] ?? '');
//$contactEmail = sanitize($_POST['email'] ?? ''); 



// Prepare email content
$characterDetails = <<<EOT
<html>
<body>

<p>Contact: {$contactEmail}</p>

<div class="character-sheet">
<fieldset> 
<legend>Bio</legend>

    <!-- Basic Information -->
   <table class="character-table">
   <tr>
   <td rowspan="6" style="text-align: center;">
   <div class="profile-image"><img src="../imgs/bagua.png" width="" height="" alt="character image"></div>
   </td>
        <th>Name</th><td>{$name}</td></tr>
        <tr><th>Age</th><td>{$age}</td></tr>
        <tr><th>Gender</th><td>{$gender}</td></tr>
        <tr><th>Cultivation XP</th><td>{$cultivationXp}</td></tr>
        <tr><th>Cultivation Stage</th><td>{$cultivationStage}</td></tr>
		<tr><th>Archetype</th><td>{$archetype}</td></tr>
		<tr><th></th>
		<th>Alignment</th><td>{$alignment}</td></tr>
	    </table>	
</fieldset>	

<Fieldset>

 <legend>Background  Story </legend>		
		
<p>{$background}</p>
</Fieldset>



    <!-- Stats -->
		<fieldset>
        <legend>Stats</legend>
        <table class="character-table">
        <tr>
            <th>Strength</th>
			<th>Dexterity</th>
			<th>Vitality</th>
			<th>Spirit</th>
        </tr>
		
        <tr>
            <td>{$strength}</td>
			<td>{$dexterity}</td>
			<td>{$vitality}</td>
			<td>{$spirit}</td>
        </tr>
   
    </table>

    <!-- Derived Stats -->

        <table class="character-table">
        <tr>
		<th>Speed</th>
		<th>Qi</th>
		<th>HP</th>
		<th>Attack</th>
		<th>Defense</th>
		</tr>
		
        <tr>
		<td>{$speed}</td>
		<td>{$qigong}</td>
		<td>{$hitpoints}</td>
		<td>{$attackpoint}</td>
		<td>{$defensepoint}</td>
		</tr>
    </table>
	
</Fieldset>


        <!-- equipment-->
<fieldset>
<legend>Equipment</legend>

        <table class="character-table">
            <tr>
              <th>Weapon:</th>
            </tr>
			
			  <tr>
              <td>{$weapon}</td>
            </tr>
        </table>
		
		
 <!-- Artifact -->
        
        <table class="character-table">
		
		     <tr>
                <th>Artifact</th>
				<th>Pills</th>
				<th>Talismans</th>
            </tr>
		
		
            <tr>
                <td>{$artifact}</td>
				<td>{$pills}</td>
				<td>{$talisman}</td>

            </tr>
        </table>



    <!-- Furnace -->

<strong>Furnace Name:</strong> {$furnaceType}
<table class="character-table">
		     <tr>
                <td colspan="8">Furnace Stats</td>
            </tr>
			 <tr>
                <th>Level</th>
                <th>Durability</th>
                <th>Passive Effect</th>
                <th>Combat Effect</th>
                <th>Setup Time</th>
                <th>Repair Time</th>
                <th>Repair Cost</th>
                <th>Cost</th>
            </tr>
         <tr>
           <td>{$furnaceLevel}</td>
           <td>{$furnaceDurability}</td>
           <td>{$furnacePassiveEffect}</td>
           <td>{$furnaceCombatEffect}</td>

            <td> {$furnaceSetupTime}</td>
            <td> {$furnaceRepairTime}</td>
            <td> {$furnaceRepairCost} </td>
            <td> {$furnaceCost}</td>
        </tr>
    </table>
	
</fieldset>
  
<!-- Martial Arts Manuals -->


<fieldset>
<legend>Manuals</legend>

{$manualsDetails}

</fieldset>

    <!-- Currency -->
		        <table class="character-table">
            <tr>
                <th>Currency</th>
 <td>Platinum: {$plat}, Gold: {$gold}, Silver: {$silver}, Copper: {$copper}</td>
           </tr>
		  
    </table>
	
	
 <hr>	
	
</div>



</body>
</html>
EOT;

// Send the email
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);


try {
    $mail->setLanguage(CONTACTFORM_LANGUAGE);
    $mail->SMTPDebug = CONTACTFORM_PHPMAILER_DEBUG_LEVEL;
    $mail->isSMTP();
    $mail->Host = CONTACTFORM_SMTP_HOSTNAME;
    $mail->SMTPAuth = true;
    $mail->Username = CONTACTFORM_SMTP_USERNAME;
    $mail->Password = CONTACTFORM_SMTP_PASSWORD;
    $mail->SMTPSecure = CONTACTFORM_SMTP_ENCRYPTION;
    $mail->Port = CONTACTFORM_SMTP_PORT;
    $mail->CharSet = CONTACTFORM_MAIL_CHARSET;
    $mail->Encoding = CONTACTFORM_MAIL_ENCODING;

    $mail->setFrom(CONTACTFORM_FROM_ADDRESS, CONTACTFORM_FROM_NAME);
    $mail->addAddress(CONTACTFORM_TO_ADDRESS, CONTACTFORM_TO_NAME);
    $mail->addReplyTo(CONTACTFORM_FROM_ADDRESS, 'Reply');

    $mail->isHTML(true);        // Ensure email content is sent as HTML
    $mail->Subject = "Character Submission from {$name}";
    $mail->Body = $characterDetails;
	
	
// Generate plain text alternative for AltBody

$mail->AltBody = 
"Character Submission Details:\n" .
"----------------------------------\n" .
"  Contact: {$contactEmail}\n" .

"Bio:\n" .
"  Name: {$name}\n" .
"  Age: {$age}\n" .
"  Gender: {$gender}\n" .
"  Cultivation XP: {$cultivationXp}\n" .
"  Cultivation Stage: {$cultivationStage}\n" .
"  Archetype: {$archetype}\n\n" .
"  Alignment: {$alignment}\n\n" .

"Stats:\n" .
"  Strength: {$strength}\n" .
"  Dexterity: {$dexterity}\n" .
"  Vitality: {$vitality}\n" .
"  Spirit: {$spirit}\n" .
"  Speed: {$speed}\n" .
"  Qi: {$qigong}\n" .
"  HP: {$hitpoints}\n" .
"  Attack: {$attackpoint}\n" .
"  Defense: {$defensepoint}\n\n" .

"Equipment:\n" .
"  Weapon: {$weapon}\n" .
"  Artifact: {$artifact}\n" .
"  Pills: {$pills}\n" .
"  Talisman: {$talisman}\n\n" .

"Furnace:\n" .
"  Type: {$furnaceType}\n" .
"  Level: {$furnaceLevel}\n" .
"  Durability: {$furnaceDurability}\n" .
"  Passive Effect: {$furnacePassiveEffect}\n" .
"  Combat Effect: {$furnaceCombatEffect}\n" .
"  Setup Time: {$furnaceSetupTime}\n" .
"  Repair Time: {$furnaceRepairTime}\n" .
"  Repair Cost: {$furnaceRepairCost}\n" .
"  Cost: {$furnaceCost}\n\n" .

"Martial Arts Manuals:\n" .
$manualsText .

"Currency:\n" .
"Platinum: {$plat}\n" .
"Gold: {$gold}\n" .
"Silver: {$silver}\n" .
"Copper: {$copper}\n" .
"----------------------------------\n" .
"This is the plain-text version of the email.";

	

    $mail->send();
    redirectSuccess();
} catch (Exception $e) {
    error_log("PHPMailer Error: " . $mail->ErrorInfo);
    redirectWithError("An error occurred while trying to send your message: " . $mail->ErrorInfo);
}

?>

What is the error?

4 Likes

Sorry, there was no error displayed. I also apologize that I have no real working knowledge of these things. However after updating the character submission form (which worked previously but had some javascript bugs) it no longer sends me the form data. The page reloads, but there in no “successfully sent” message, nor a sent email.

So what do you see when you try to submit this form?

Does it say the email was sent successfully? Does it say nothing at all? Does it just show the input form like it wasn’t submitted? Does it show a blank page?

We’re happy to help you, and having the code to check helps, but you can’t throw 459 lines of code at us and tell us “find what’s wrong with this code”. Especially when the issue might not be in this code to begin with.

7 Likes

Ahaha. Yeah that was crazy. I apologize for that. How can I tame that code? About the error. In the firefox debugger all the fields are correctly filled in and on submit the page just reloads… all fields are empty and there is no ‘failed’ or ‘succeeded’ message. And no email is received from the form.

Thanks for clarifying.

In the Network tab on your browser, do you see that the POST request is actually made to the submit.php file? After all, if the data is just submitted to the form page, then it will not work.

Also, is all the error handling and showing code from the contact form template still in-tact? If the code that handles the error message is gone, then of course you won’t see any error message.

Besides that, if you say the page reloads, that implies that the submit.php code executes successfully and redirects back to the form page. Does that match what you see? Because the submit.php will always submit with a message, and I don’t see any changes in your code that could interfere with that.

6 Likes

Thank you so much! I double checked and I had a mistake in the css so I couldnt view the error messages. Now I can and have and resolved the issue (some hidden fields were not populating and preventing validations!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.