Hello bretheren and programming Gurus? Am new and blank about php and just trying to experiment to get things as i want. Am using the code below but it does not validate data input and also does not redirect to the index page specified in it.I want if the fileds are empty on clicking submit, it must return an error and prompts to fill in all fields.i also want an option where a person can attach files to the form. Kindly correct errors for me in the code and give me a complete fully functional code. Thank you.

<?php

    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];

if(isset($_POST['submit']))

{
    $from_add = "contactform@yourwebsite.com";

    $to_add = "yourname@yourwebsite.com";

    $subject = "Your Subject Name";

    $message = "Name:$name \n Email: $email \n Phone: $phone \n
Message: $message";

    $headers = "From: $from_add \r\n";
    $headers .= "Reply-To: $from_add \r\n";
    $headers .= "Return-Path: $from_add\r\n";
    $headers .= "X-Mailer: PHP \r\n";


    if(mail($to_add,$subject,$message,$headers))
    {
        $msg = "Mail sent";
    }
}

    print "<p>Thank you $name for your message,
we will be in contact shortly. <a href=\"index.php\">Click here</a>
to continue </p>" ;



?>

Dani AI

Generated

Common causes in this thread: missing server-side checks, output sent before a PHP redirect, reusing variables (the input $message overwritten by the email body), and an upload script that looks like raw PHP because the server isn’t parsing the file. Notes below expand on posts from , and and give focused, practical fixes.

Server-side validation + safe redirect (example)

  • Use PHP validation even when client-side checks exist. Validate email with filter_var, trim inputs, collect errors, and stop when errors exist. Avoid reusing $message for both the POST field and the full email body — use a separate variable like $mailBody. Always call exit after sending a header redirect, and check headers_sent() when a redirect silently fails.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $name = trim($_POST['name'] ?? '');
  $email = trim($_POST['email'] ?? '');
  $text = trim($_POST['message'] ?? '');
  $errors = [];
  if ($name === '') $errors[] = 'Name required';
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid e-mail required';
  if ($text === '') $errors[] = 'Message required';

  if (empty($errors)) {
    $safeFrom = 'contact@domain.tld';
    $safeEmail = preg_replace('/[\r\n].*/', '', $email); // block header injection
    $headers = "From: {$safeFrom}\r\nReply-To: {$safeEmail}\r\n";
    $mailBody = "Name: $name\n\n$text";
    if (mail('owner@domain.tld', 'Contact form', $mailBody, $headers)) {
      header('Location: /index.php', true, 303);
      exit;
    }
  }
}
?>

File uploads and the “PHP gabbage” problem

  • If PHP code is printed instead of executed, the file is probably not being parsed: confirm the filename ends with .php and the host supports PHP. Create a quick test.php containing <?php phpinfo(); ?> to verify. For uploads, require enctype="multipart/form-data", check $_FILES['fileAttach']['error'], verify MIME with finfo, limit size and store uploads outside the webroot. Example handling:
if (!empty($_FILES['fileAttach']) && $_FILES['fileAttach']['error']===UPLOAD_ERR_OK) {
  $mime = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $_FILES['fileAttach']['tmp_name']);
  $allowed = ['image/jpeg','image/png','application/pdf'];
  if (in_array($mime,$allowed) && $_FILES['fileAttach']['size'] < 2*1024*1024) {
    $dest = __DIR__.'/uploads/'.uniqid().'-'.basename($_FILES['fileAttach']['name']);
    move_uploaded_file($_FILES['fileAttach']['tmp_name'],$dest);
  }
}

Best practices and troubleshooting

  • Prefer a mail library (PHPMailer) for attachments rather than hand-crafting MIME boundaries. Use headers_sent($file,$line) to debug redirect failures; check server error logs for mail failures; never trust client input; sanitize header fields to prevent injection; keep display_errors off in production.

Recommended Answers

All 5 Replies

You want to redirect automatically ?

i think you have to change the link in your <a> tag but if you want to redirect automatically, you have to user header() function in php .

Hi for client side you can add Javascript for form validation. when the submit button is click it will check your form element if its is empty or not..or if your using html5 just use the new required attribute and for a server side validation use (PHP) just to be sure.

for html5
<input type="text" name="name" required>

for the JS Part something like this

<script language="javascript">
function validate()
{
var x=document.forms["formname"]["name"].value;
if (x==null || x=="" )
  {
  alert("Name is Required");
  return false;
  }
  var x=document.forms["formname"]["email"].value;
else if (x==null || x=="" )
  {
  alert("email is Required");
  return false;
  }
var x=document.forms["formname"]["phone"].value;
else if (x==null || x=="" )
  {
  alert("phone is Required");
  return false;
  }
 var x=document.forms["formname"]["message"].value;
else if (x==null || x=="" )
  {
  alert("message is Required");
  return false;
  }


}
</script>

and for the php validation part just convert it to php:D

usually when you want to redirect to a page automatically you just need to put a header tag after your email been send like

header("Location:index.php");

ok i tried both your suggestions. But the link with file upload appears to appeal more of my desire. thanks to everyone. but one problem. when i hit submit button i get php gabbage on the screen rather than the supposed after send button message. Check it below. i have provided both php file and the html form codes. Any idea how these insects like characters come about? and where do i put my own e-mail address in the php code to which all e-mails can be send to?

Have a look

This PHP gabbage is displayed on the web page when i hit submit

\nReply-To: ".$_POST["txtFormEmail"].""; $strHeader .= "MIME-Version: 1.0\n"; $strHeader .= "Content-Type: multipart/mixed; boundary=\"".$strSid."\"\n\n"; $strHeader .= "This is a multi-part message in MIME format.\n"; $strHeader .= "--".$strSid."\n"; $strHeader .= "Content-type: text/html; charset=utf-8\n"; $strHeader .= "Content-Transfer-Encoding: 7bit\n\n"; $strHeader .= $strMessage."\n\n"; //*** Attachment ***// if($_FILES["fileAttach"]["name"] != "") { $strFilesName = $_FILES["fileAttach"]["name"]; $strContent = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"]))); $strHeader .= "--".$strSid."\n"; $strHeader .= "Content-Type: application/octet-stream; name=\"".$strFilesName."\"\n"; $strHeader .= "Content-Transfer-Encoding: base64\n"; $strHeader .= "Content-Disposition: attachment; filename=\"".$strFilesName."\"\n\n"; $strHeader .= $strContent."\n\n"; } $flgSend = @mail($strTo,$strSubject,null,$strHeader); // @ = No Show Error // if($flgSend) { echo "Mail successfully sent."; } else { echo "Cannot send mail."; } ?>

Html form code

<form action="php_sendmail_upload2.php" method="post" name="form1" enctype="multipart/form-data">  

<table width="343" border="1">
<tr>
<td>To</td>
<td><input name="txtTo" type="text" id="txtTo"></td>
</tr>
<tr>
<td>Subject</td>
<td><input name="txtSubject" type="text" id="txtSubject"></td>
</tr>
<tr>
<td>Description</td>
<td><textarea name="txtDescription" cols="30" rows="4" id="txtDescription"></textarea></td>
</tr>
<tr>
<td>Form Name</td>
<td><input name="txtFormName" type="text"></td>
</tr>
<tr>
<tr>
<td>Form Email</td>
<td><input name="txtFormEmail" type="text"></td>
</tr>
<tr>
<td>Attachment</td>
<td><input name="fileAttach" type="file"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Send"></td>
</tr>
</table>
</form>

What is wrong? is it the php file or the html form?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.