/    Sign up×
Bounties /Pin to ProfileBookmark

Can anyone help get simple PHP contact form working please?

+ 1,000
Copy linkTweet thisAlerts:
Jan 17.2024

I need some assistance. About a decade ago I compiled a decent PHP mail script for website contact forms. Apparently, it has been rendered obsolete and now doesn’t work in some places. I need some help figuring out why the start of this new one doesn’t work at all. It’s not even showing the basic page, errors, nothing, just a white screen. It’s now all on this one page that I’ll attach next. Please let me know what you see! Thank you!

This occurred on a free hosting platform (000webhost) which stinks for many reasons. I guess they claimed they enforced PHP v8 across the board and that’s what broke my original. Funny though, I use the original form/script over at GoDaddy in multiple places and it still works fine there… Now migrating to another free host on this one (awardspace) which offers user ability to downgrade php from like V5 on. I just need to get something working…

<?php

$errors = [];
$errorMessage = '';

if (!empty($_POST)) {
   $name = $_POST['name'];
   $email = $_POST['email'];
   $message = $_POST['message'];

   if (empty($name)) {
       $errors[] = 'Name is empty';
   }

   if (empty($email)) {
       $errors[] = 'Email is empty';
   } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
       $errors[] = 'Email is invalid';
   }

   if (empty($message)) {
       $errors[] = 'Message is empty';
   }

   if (empty($errors)) {
       $toEmail = '[email protected]';
       $emailSubject = 'New email from your contact form';
       $headers = ['From' => $email, 'Reply-To' => $email, 'Content-type' => 'text/html; charset=utf-8'];
       $bodyParagraphs = ["Name: {$name}", "Email: {$email}", "Message:", $message];
       $body = join(PHP_EOL, $bodyParagraphs);

       if (mail($toEmail, $emailSubject, $body, $headers)) {

           $errorMessage = "Thanks! We'll get right back to you!";
       } else {
           $errorMessage = 'Oops, something went wrong. Please try again later';
       }

   } else {

       $allErrors = join('<br/>', $errors);
       $errorMessage = "<p style='color: red;'>{$allErrors}</p>";
   }
}

?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Ebony and Ivory Music Studio - General Contact</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta property="fb:app_id" content="">
<meta property="og:title" content="Ebony and Ivory Music Studio - General Contact">
<meta property="og:type" content="website">
<meta property="og:image" content="http://ebonyandivorymusic.org/images/1897.jpg">    
<meta property="og:url" content="http://ebonyandivorymusic.org">
<meta property="og:description" content="Barbara Roth, of Cincinnati, Colerain, Groesbeck, Cheviot, Montfort Heights, Anderson, Clermont, Batavia, Price Hill, Ohio, piano and violin teacher with 50 years experience.">
<meta name="description" content="Barbara Roth, of Cincinnati, Colerain, Groesbeck, Cheviot, Montfort Heights, Anderson, Clermont, Batavia, Price Hill, Ohio, piano and violin teacher with 50 years experience.">
<meta name="author" content="Nathan Roth" >
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Custom styles for this template -->
<link href="css/newnav86.css" rel="stylesheet">
<link href="css/w38.css" rel="stylesheet">
<style>
body,h1,h2,h3,h4,h5,h6 {font-family: "Lato", sans-serif}
.w3-bar,h1,button {font-family: "Montserrat", sans-serif}
.fa-anchor,.fa-coffee {font-size:200px}
        form { width: 100%; }
        form p { margin: 0px 0px 25px 20px; }
        label {
            display: block;
            font-family: "Calibri", "Times New Roman", Times, serif;
            font-size: 1em;
            line-height: 1.421875em;
            color: #FEF8E6;
        }
        textarea {
            width: 380px;
            height: 150px;
        }
        @media screen and (max-width: 769px) { textarea {
            width: 240px;
            height: 120px;
        } }
        .textInput { width: 300px; }
        @media screen and (max-width: 769px) { .textInput { width: 125px; } }
        .sendButton { border:1px solid #000000!important; color: #FEF8E6; background-color: #666666; }
        .sendButton:hover { border:1px; color:#000000; background-color: #FEF8E6; }
        .warning {
            font-family: "Calibri", "Times New Roman", Times, serif;
            font-size: 1em;
            line-height: 1.21875em;
            font-weight: bold;
            color: #FF0000;
        }
        .success {
            font-family: "Calibri", "Times New Roman", Times, serif;
            font-size: 1em;
            line-height: 1.21875em;
            font-weight: bold;
            color: #6E1410;
        }
        .welcome {
            font-family: "Calibri", "Times New Roman", Times, serif;
            font-size: 1.3em;
            line-height: 1.7875em;
            font-weight: bold;
            color: #FEF8E6;
        }
        form .website{ display:none; } /* hide because is spam protection */
</style>
<script>google recaptcha script</script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-89258336-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-xxxxxxx-1');
</script>


</head>

<body>
    
<!-- Navbar -->
<?php include("includes/newnavnavigation.inc.php"); ?>

<div class="content">
<!-- Header -->
<header id="header" class="w3-container w3-center">
  <h1 class="w3-jumbo"><img src="images/header.jpg" alt="Ebony and Ivory Music Studio Header Image"></h1>
</header>

<div class="w3-row-padding w3-padding-64 w3-container" style="margin-top: -60px; margin-left: 0px;">
  <div class="w3-content" style="margin-left: 0px;">
    <div class="w3-twothird" style="margin-left: 0px;">
    
            <h2>Thank you for visiting! Ask a general question or contact me to set up an introductory lesson!</h2>
            
            <?php
            if (!empty($errors)) {
               $allErrors = join('<br/>', $errors);
               $errorMessage = "<p style='color: red;'>{$allErrors}</p>";
            }
            echo((!empty($errorMessage)) ? $errorMessage : '')
            ?>
            
            <form method="post" name="contact" id="contact" class="w3-container w3-card-4">
            <p><input name="website" type="text" class="website"></p>
              <p>
                <label for="name">Name:</label>
                <input placeholder="Enter your name" name="name" type="text" value="<?= $inputs['name'] ?? '' ?>" class="textInput" id="name">
              </p>
              <p>
                <label for="email">Email:</label>
                <input placeholder="Enter your email" name="email" type="text" value="<?= $inputs['email'] ?? '' ?>" class="textInput" id="email">
              </p>
              <p>
                <label for="message">Message:</label>
                <textarea placeholder="Write your message" name="message" id="question" cols="25" rows="5"><?= $inputs['message'] ?? '' ?></textarea>
              </p>

            <label for="nickname" aria-hidden="true" class="website"> Nickname
            <input type="text" name="nickname" id="nickname" class="website" tabindex="-1" autocomplete="off">
            </label>

              <p>
                <input type="submit" name="send" id="send" class="sendButton" value="Click to Send Message">
              </p>
            </form>
            
            <br><br>
            
            <img class="centerimage" src="images/facebook_1475422948378.jpg" alt="Image of Barb Teaching">
            
            </div>

    <div class="w3-third w3-center" style="margin-top: 60px;">
      <span style="margin-left: 0px;"><a href="https://lessons.com/oh/cincinnati/violin-lessons/" title="lessons.com" target="_blank"><img src="//cdn.lessons.com/assets/images/tmp/lessons-2018.png" width="100" alt="lessons.com"></a></span><br><br> 
                    <img style="width: 70%; border: 2px solid #6E1410;" src="images/1884.jpg" alt="Headshot for Contact Webpage">
    </div>
  </div>
</div>

<!-- Footer -->
<?php include("includes/newnavfooter.inc.php"); ?>

</div>
 <script src="//cdnjs.cloudflare.com/ajax/libs/validate.js/0.13.1/validate.min.js"></script>
 <script>


     const constraints = {
         name: {
             presence: { allowEmpty: false }
         },
         email: {
             presence: { allowEmpty: false },
             email: true
         },
         message: {
             presence: { allowEmpty: false }
         }
     };

     const form = document.getElementById('contact');
     form.addEventListener('submit', function (event) {

         const formValues = {
             name: form.elements.name.value,
             email: form.elements.email.value,
             message: form.elements.message.value
         };


         const errors = validate(formValues, constraints);
         if (errors) {
             event.preventDefault();
             const errorMessage = Object
                 .values(errors)
                 .map(function (fieldValues) {
                     return fieldValues.join(', ')
                 })
                 .join("\n");

             alert(errorMessage);
         }
     }, false);
 </script>
<script>
// Used to toggle the menu on small screens when clicking on the menu button
function myFunction() {
    var x = document.getElementById("navDemo");
    if (x.className.indexOf("w3-show") == -1) {
        x.className += " w3-show";
    } else { 
        x.className = x.className.replace(" w3-show", "");
    }
}
</script>

</body>
</html>
to post a answer
DebuggingPHPWeb Hosting

2 Replies

Davinci•003 auto-replySure, I'd be happy to help you create a simple PHP contact form. Here's a basic example:

First, let's create the HTML form:

``html

Name:

Email:

Message:



`

Next, let's create the PHP script that will process the form (contact.php):

`php

`

Please replace "[email protected]" with your actual email address. This script sanitizes and validates the input, then sends an email with the form data. If the email is sent successfully, it prints "Email sent successfully". If the email fails to send, it prints "Email sending failed".

Please note that the PHP
mail()` function requires your server to be configured to send mail. If you're testing this on a local server, it may not work. In a live server environment, it should work as long as PHP and the mail server are configured correctly.

Was this helpful?

Copy linkTweet thisAlerts:
@neststayhomeApr 03.2024 — It seems that the PHP script on your webpage is encountering an issue, resulting in a blank screen. To troubleshoot this, first, check if there are any syntax errors in the PHP code, such as missing semicolons or brackets. Additionally, ensure that the PHP version on your hosting platform is compatible with the code. You may also want to enable error reporting in PHP to identify any specific errors or warnings that are occurring. If the issue persists, consider reaching out to your hosting provider for assistance or consulting with a web developer familiar with PHP
×

Success!

Help @rothnd spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 7.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ,
analytics: Fullres
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: Anonymous,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 1000 SATS,

tipper: @Nanditha,
tipped: article
amount: 1000 SATS,
)...