Build a PHP contact form
Check submitted email and phone values, keep valid entries after errors, and hand the message to your existing PHP mail transport.
Working example
ParseAPISet up ParseAPI
Set PARSEAPI_KEY in your server environment. Enable the PHP cURL extension.
export PARSEAPI_KEY='YOUR_SECRET_API_KEY'Build the form and its server handler
A contact form needs more than a successful browser check. Build a PHP page that validates the submitted contact details on the server, shows errors beside the relevant fields, and keeps the person's other entries. A valid submission can then use your existing mail transport.
1. Keep the submitted values
The form collects a name, email, optional phone number and message. A national phone number also needs its country. Keep these original values when re-rendering an error; use the normalized results for the message your application prepares.
The handler keeps submitted text in values. Render it back into the field with HTML escaping, while marking only the field that needs correction:
<label for="email">Email</label>
<input id="email" name="email" type="email" autocomplete="email" maxlength="254"
value="<?= htmlspecialchars($values['email'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?>"
aria-invalid="<?= isset($errors['email']) ? 'true' : 'false' ?>"
aria-describedby="email-error" required>The complete app includes a session-bound CSRF token, input limits and HTML escaping. Neither browser validation nor a hidden field replaces the server checks.
2. Check the email on the server
The HTTP helper reads the secret PARSEAPI_KEY from your server environment. It uses PHP cURL and selects API 2.3.0 on every request:
function lookup(string $path, array $params = []): array
{
$key = trim(getenv('PARSEAPI_KEY') ?: '');
if ($key === '' || str_starts_with($key, 'parse_public_') || str_starts_with($key, 'parse_app_')) {
throw new \RuntimeException('Set PARSEAPI_KEY to a secret key on the server.');
}
$url = rtrim(getenv('PARSEAPI_BASE_URL') ?: 'https://api.parseapi.com', '/') . $path;
if ($params) $url .= '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986);
$curl = curl_init($url);
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => ['X-API-Key: ' . $key, 'X-API-Version: 2.3.0', 'Accept: application/json'],
]);
try {
$body = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
if ($body === false || $status < 200 || $status >= 300) throw new \RuntimeException('Lookup failed.');
$answer = json_decode($body, true, flags: JSON_THROW_ON_ERROR);
if (!is_array($answer)) throw new \UnexpectedValueException('Unexpected response.');
return $answer;
} finally {
curl_close($curl);
}
}Call Email with the submitted address:
$email = $lookup('/email/' . rawurlencode(trim($values['email'])));Read the parsed address and validation facts:
$replyTo = $email['email'];
$valid = $email['valid'];
$domainValid = $email['domain_valid'];This app requires a valid address and a confirmed domain result before handing a message to its mail transport. A null domain result asks the person to try again; it is not an invalid-address verdict. A spelling suggestion stays separate until the person edits the field.
Core validation does not establish mailbox delivery or ownership. This form does not request metered mailbox verification. See the Email reference.
3. Normalize the optional phone
Skip the lookup when the phone field is empty. For a national number, pass the selected country; a number beginning with + carries its own calling code.
$phone = $lookup('/phone/' . rawurlencode(trim($values['phone'])),
$phoneCountry === null ? [] : ['country' => $phoneCountry]);The returned international number can go into the message body:
$normalizedPhone = $phone['valid'] ? $phone['phone'] : null;An invalid phone result stays a field error. A failed request leaves the details unchecked and sends nothing. Phone parsing does not establish ownership or current reachability.
4. Use your existing mail transport
Use your configured sender address for From, and the checked reply address for Reply-To:
$headers = ['From' => $delivery['from'], 'Reply-To' => $replyTo,
'Content-Type' => 'text/plain; charset=UTF-8'];The complete example uses PHP's existing mail transport:
$accepted = mail($to, 'Website contact request', $body, $headers);Only a true return value produces the acceptance message. Transport acceptance does not guarantee inbox delivery. Failed validation, a failed request, missing mail configuration or rejected delivery keeps the original form entries visible.
Set CONTACT_TO and CONTACT_FROM to addresses you control only when your existing PHP mail transport is configured and you intend to accept submissions. Without those settings, the app never claims to have sent a message.
Each submission uses one Email request and, when supplied, one Phone request. The app makes one attempt per lookup with a ten-second timeout. Errors stop the submission before delivery. The sample phone-country list is deliberately short; replace it with the countries your form serves.
Complete example
Use the complete implementation as a reference when adding this feature to your app. It includes the validation and failure handling around the calls above.
View and copy the complete source
Try the complete example on your computer
After completing the setup above, save the source in your application folder and start the app:
php -S 127.0.0.1:8000 php-contact-form.phpOpen 127.0.0.1:8000 to use the form. The server keeps your secret key out of the page.
For every field and parameter, see Email API reference and Phone API reference.
Build something else
- Check an email as someone types
- Verify email addresses on a Node.js server
- Build a contact review step for inbound emails
- Validate a phone number in your form