Ned help with my contact form

I have a contact form on my new website. It is a template I bought back in 2014, so I suspect there m,ight be an upgrade problem (code too old for current version of php on the server). But I do not know enough to find the problem. The php version on the server is 8.1

I don´t get any errors. Just nothing happens when I press send

The website is www.rytmekraft.no

The html code is:

<form id="contact-form" class="checkform" action="#" target="contact-send.php" method="post" >
                      	
                        	<div class="form-row clearfix">
                            	<label for="name" class="req">Navn *</label>
                            	<div class="form-value"><input type="text" name="name" class="name" id="name" value="" /></div>
                        	</div>
                            <div class="form-row clearfix">
                            	<label for="name" class="req">Firma *</label>
                            	<div class="form-value"><input type="text" name="name" class="name" id="name" value="" /></div>
                        	</div>
                        	<div class="form-row clearfix">
                            	<label for="email" class="req">Epost *</label>
                            	<div class="form-value"><input type="text" name="email" class="email" id="email" value="" /></div>
                        	</div>
                            
                        	<div class="form-row clearfix textbox">
                            	<label for="message" class="req">Melding *</label>
                            	<div class="form-value"><textarea name="message" class="message" id="message" rows="15" cols="50"></textarea></div>
                        	</div>
							
							<div id="form-note">
								<div class="alert alert-error">
									<h6><strong>Error</strong>: Please check your entries!</h6>
								</div>
							</div>
                            
                        	<div class="form-row form-submit">
                            	<input type="submit" name="submit_form" class="submit" value="Send" />
                        	</div>
                    
                        	<input type="hidden" name="subject" value="RytmeKraft kontaktform" />
                        	<input type="hidden" name="fields" value="name,email,message," />
                        	<input type="hidden" name="sendto" value="[email protected]" />  
                        
                   	</form> type or paste code here

The php document code is:

<?php

define("[email protected]", $_POST['sendto']);
if (WEBMASTER_EMAIL == '' || WEBMASTER_EMAIL == 'Testemail') {
	die('<div class="alert alert-confirm"> <h6><strong>The recipient email is not correct</strong></h6></div>');	
} 

define("EMAIL_SUBJECT", $_POST['subject']);
if (EMAIL_SUBJECT == '' || EMAIL_SUBJECT == 'Subject') {
	define("EMAIL_SUBJECT",'Contact');	
}

$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$message = stripslashes($_POST['message']);

$custom = $_POST['fields'];
$custom = substr($custom, 0, -1);
$custom = explode(',', $custom);

$message_addition = '';
foreach ($custom as $c) {
	if ($c !== 'name' && $c !== 'email' && $c !== 'message' && $c !== 'subject') {
		$message_addition .= '<b>'.$c.'</b>: '.$_POST[$c].'<br />';
	}
}

if ($message_addition !== '') {
	$message = $message.'<br /><br />'.$message_addition;
}


$message = '<html><body>'.nl2br($message)."</body></html>";
$mail = mail(WEBMASTER_EMAIL, EMAIL_SUBJECT, $message,
     "From: ".$name." <".$email.">\r\n"
    ."Reply-To: ".$email."\r\n"
    ."X-Mailer: PHP/" . phpversion()
	."MIME-Version: 1.0\r\n"
	."Content-Type: text/html; charset=utf-8");


if($mail)
{
echo '
		<div class="alert alert-confirm">
			<h6><strong>Confirm</strong>: Your message has been sent. Thank you!</h6>
		</div>
';
}
else
{
echo '
		<div class="alert alert-error">
			<h6><strong>Error</strong>: Your message has not been send!</h6>
		</div>
';
}

?>

The first define() statement in the php code is incorrect and is not defining a constant named WEBMASTER_EMAIL. All the references to WEBMASTER_EMAIL in the rest of the code produce a fatal error.

Also, these emails are not being sent from the email address that was entered in the form. They are being sent from the mail server at your web hosting and the domain in the From: mail header must correspond to the sending mail server. You can put the entered email address in the Reply-to: mail header, after you have validated that it is only and exactly one properly formatted email address.

While most of the form markup is usable, you should NOT pass the subject, fields, and sendto values through hidden fields in the form, where they can be set to any value and allow a spammer to abuse your mail server. These values should be defined in the php code.

The form has two fields with the same name and id. These attributes must be unique and the php code must reference each field by its name.

As to the php code, most of this is not worth keeping. The post method form processing code should -

  1. Be on the same page as the form. The code for any page should be laid out in this general order - 1) initialization, 2) post method form processing, 3) get method business logic - get/produce data needed to display the page, 4) html document.
  2. Detect if a post method form has been submitted.
  3. Keep the form data as a set in a php array variable, then operate on elements in this array variable throughout the rest of the code.
  4. Trim all the input data before validating it. Once you do item #3 on this list, you can trim all the data at once using a single line of code.
  5. Validate the input data, storing user/validation errors in an array using the field name as the array index.
  6. See php’s filter_var() function with the FILTER_VALIDATE_EMAIL filter flag to validate the email address.
  7. After the end of the validation logic, if there are no errors (the array holding the user/validation errors will be empty), use the submitted data.
  8. Apply htmlentities() to the submitted form data before using it in the email body.
  9. If the mail() call returns a false value, add the failure message to the array holding the user/validation errors.
  10. After the end of the mail sending logic, if there are no errors, redirect to the exact same URL of the current page to cause a get request for that page. This will prevent the browser from trying to resubmit the form data should that page get browsed back to or reloaded.
  11. To display a one-time success message, either store the message of a flag value in a session variable, then test for the session variable, display the message, and clear the session variable at the appropriate location in the html document.
  12. If there are errors, the code will continue on to redisplay the html document, where you will test for and display any errors, either all at once or individually adjacent to the field they correspond to, and display the form, populating the field values with any existing data so that the user doesn’t need to keep reentering values over and over.
  13. Apply htmlentities() to any dynamic value being output in the html document, right before outputting them.

Thank you.

The email issue I found out, so I have created a mail adress on the server where the website is hosted.mnI guess the best thing to do is to scratch the whole thing and start fresh? Any good idea o0n where to go for “ready made” code to use?

Here’s an example that shows the points that were given -

<?php

// initialization
session_start();

$subject = "RytmeKraft kontaktform";
$sendto = "[email protected]";
$sendfrom = "a from email at your web hosting"; // email address at your web hosting account

// failed email log file
$log_file = 'mail.log.txt';

// define expected fields
$fields = [];
$fields['name'] = ['label'=>'Navn','type'=>'text','required'=>true];
$fields['firm'] = ['label'=>'Firma','type'=>'text','required'=>true];
$fields['email'] = ['label'=>'Epost','type'=>'text','required'=>true];
$fields['message'] = ['label'=>'Melding','type'=>'textarea','required'=>true,'rows'=>"15",'cols'=>"50"];

$post = []; // array to hold a trimmed working copy of the form data
$errors = []; // array to hold user/validation errors

// post method form processing
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
	// trim all the input data at once
	$post = array_map('trim',$_POST);

	// validate the input data
	foreach($fields as $field=>$arr)
	{
		// required inputs
		if(($arr['required']??false) && $post[$field] === '')
		{
			$errors[$field] = "{$arr['label']} is required.";
		}
	}

	// email format
	if(empty($errors['email']) && !filter_var($post['email'],FILTER_VALIDATE_EMAIL))
	{
		$errors['email'] = "{$fields['email']['label']} format is not valid.";
	}

	// if no errors, use the input data
	if(!$errors)
	{
		$message = [];
		foreach($fields as $field=>$arr)
		{
			$message[] = "<b>{$arr['label']}</b>: $post[$field]";
		}
		// apply htmlentities to all elements in the message array
		$nessage = array_map('htmlentities',$message);
		// implode the message with new-lines
		$message = implode("\r\n",$message);
		// word wrap the message lines at 70 characters
		$message = wordwrap($message, 70, "\r\n");
		// form the html message
		$message = "<html><body>".nl2br($message)."</body></html>";
		
		$headers = [
			"From"=>$sendfrom,
			"Reply-To"=>$post['email'],
			"X-Mailer"=>"PHP/".phpversion(),
			"MIME-Version"=>"1.0",
			"Content-Type"=>"text/html; charset=utf-8"
			];
			
		if(!mail($sendto, $subject, $message, $headers))
		{
			// fail
			$errors['mail'] = "Your message could not be sent. Site owner has been notified.";
			// log all the actual information about the problem
			$last_error = error_get_last();
			$log_data = [];
			$now = new DateTime();
			$log_data[] = $now->format('Y-m-d H:i:s')."\r\n";
			$log_data[] = "Error: {$last_error['message']}\r\n";
			$log_data[] = "$message\r\n";
			$log_data[] = "--------------\r\n";
			file_put_contents($log_file,$log_data,FILE_APPEND);
		}
	}

	// if no errors, success
	if(!$errors)
	{
		$_SESSION['success_message'] = true;
		die(header("Refresh:0"));
	}
}

// html document - this is an incomplete document and only shows the parts necessary for this demonstration
?>

<?php
// display any success message
if(isset($_SESSION['success_message']))
{?>
<div class="alert alert-confirm">
	<h6><strong>Confirm</strong>: Your message has been sent. Thank you!</h6>
</div>
<?php
unset($_SESSION['success_message']);
}
?>

<?php
// display any errors
if($errors)
{?>
	<div class="alert alert-error">
	<?=implode('<br>',$errors)?>
	</div>
<?php
}
?>

<form id="contact-form" class="checkform" method="post">
<?php
foreach($fields as $field=>$arr)
{
	switch($arr['type'])
	{
	// I doubt you have a need for a class named for each separate field. if not, remove the class attributes from the form field markup
	case 'text':
	?>
	<div class="form-row clearfix">
	<label class="req"><?=$arr['label']?> <?=($arr['required']??false) ? '*' : ''?>
	<div class="form-value"><input type="<?=$arr['type']?>" name="<?=$field?>" class="<?=$field?>" value="<?=htmlentities($post[$field]??'')?>"></label></div>
	</div>
	<?php
	break;
	
	case 'textarea':
	?>
	<div class="form-row clearfix textbox">
	<label class="req"><?=$arr['label']?> <?=($arr['required']??false) ? '*' : ''?>
	<div class="form-value"><textarea name="<?=$field?>" class="<?=$field?>" rows="<?=$arr['rows']?>" cols="<?=$arr['cols']?>"><?=htmlentities($post[$field]??'')?></textarea></label></div>
	</div>
	<?php
	break;
	}
}
?>
<div class="form-row form-submit">
<input type="submit" class="submit" value="Send">
</div>
</form>
Sponsor our Newsletter | Privacy Policy | Terms of Service