Skip to main content
daveharr1s0n
Inspiring
August 4, 2023
Question

How do I send Email with attachment on form submission using PHP?

  • August 4, 2023
  • 4 replies
  • 1592 views

Hello PHP pros,

 

This one's probably a simple one for those of you versed in php (which I'm not). I'm trying to add "upload file" capability to an existing form. The form works, I just don't know what I have to add to the following code so that a user can add an attachment to a message.

 

I've tried a few things from what I've read online, but I must be missing something.

 

Any help would be greatly appreciated!

 

Thanks!

 

Dave

 

 

 

<?php
// NOTE: this page must be saved as a .php file.
// And your server must support PHP 5.3+ PHP Mail().
// Define variables and set to empty values
$result = $message = $human = "";
$errName = $errMessage = $errHuman = "";
if ( isset( $_POST[ "submit" ] ) ) {
$message = $_POST[ 'message' ];
$human = intval( $_POST[ 'human' ] );
//valid address on your web server
$from = 'webmaster@daveharrison.info';
//your email address where you wish to receive mail
$to = 'dave@daveharrisonwebdesign.com';
$subject = 'MESSAGE FROM YOUR WEB SITE';
$headers = "From:$from\r\nReply-to:$email";
$body = "Message: $message";
//Check if message is entered
if ( empty( $_POST[ "message" ] ) ) {
$errMessage = "Please enter your message.";
} else {
$message = test_input( $_POST[ "message" ] );
}
//Check if simple anti-bot test is entered
if ( empty( $_POST[ "human" ] ) ) {
$errHuman = "Please enter the sum.";
} else {
if ( $human !== 13 ) {
$errHuman = 'Wrong answer. Please try again.';
}
}
// If there are no errors, send the email & output results to the form
if ( !$errMessage && !$errHuman ) {
if ( mail( $to, $subject, $body, $from ) ) {
$result = '<div class="alert alert-success"><h2><span class="glyphicon glyphicon-ok"></span> Message sent!</h2><h3>Thank you for contacting us. Someone will be in touch with you soon.</h3></div>';
} else {
$result = '<div class="alert alert-danger"><h2><span class="glyphicon glyphicon-warning-sign"></span> Sorry there was a form processing error.</h2> <h3>Please try again later.</h3></div>';
}
}
}
//sanitize data inputs
function test_input( $data ) {
$data = trim( $data );
$data = stripslashes( $data );
$data = htmlspecialchars( $data );
$data = ( filter_var( $data, FILTER_SANITIZE_STRING ) );
return $data;
}
//end form processing script
?>

<!DOCTYPE html>
<html lang="en">
<head>
<title>test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<style>
/* Set height of the grid so .sidenav can be 100% (adjust if needed) */
.row.content {
height: 1500px
}
/* Set gray background color and 100% height */
.sidenav {
background-color: #FFFFFF;
height: 100%;
}
/* Set black background color, white text and some padding */
footer {
background-color: #FFFFFF;
color: white;
padding: 15px;
}

/* On small screens, set height to 'auto' for sidenav and grid */
@media screen and (max-width: 767px) {
.sidenav {
height: auto;
padding: 15px;
}
.row.content {
height: auto;
}
}
.carouselWidth {
width: 95%;
margin-right: auto;
margin-left: auto;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row content">
<div class="col-sm-3 sidenav"> </div>
<div class="col-sm-6">


<div class="row">

</div>



<p><small>DROP ME A LINE SOMETIME!</small></p>
<div class="center-block">

<!--begin HTML Form-->
<form role="form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<!--when submit button is clicked, show results here-->
<div class="form-group"> <?php echo $result;?> </div>
<div class="form-group">
<textarea class="form-control" rows="3" name="message" requiredplaceholder="What's new?"><?php echo $message;?></textarea>
<span class="required small"><?php echo $errMessage;?></span> </div>
<div class="form-group">
<div class="col-sm-4">
<h6 class="human">A number between 1 and 1,806,010</h6>
<input type="text" class="form-control" id="human" name="human" placeholder="Your Answer" value="<?php echo $human;?>">
<span class="required small"><?php echo $errHuman;?></span><br>
<button type="submit" id="submit" name="submit" class="btn btn-success">SUBMIT</button>
&nbsp;
<button type="reset" id="reset" name="reset" class="btn btn-success">RESET</button>
</div>
</div>

<!--end Form-->
</form>
<!--end col block--></div>
</div>
<div class="col-sm-3 sidenav"> </div>
</div>
</div>
<footer class="container-fluid"> </footer>
</body>
</html>

This topic has been closed for replies.

4 replies

B i r n o u
Legend
August 17, 2023
quoteBirnou likes to wind down at the weekend by swapping his breeches for a dress.

By @osgood_

the weekend !

B i r n o u
Legend
August 17, 2023

Back from vacation... lol

quote

Up until now, I honestly thought L e n a  and B I R N O U were different people who worked together.  But now I wonder...

By @Nancy OShea

 

[abuse removed by Moderator]

Community Expert
August 11, 2023

In addition to what propose @Nancy OShea , I would add that PHPMailer remains today an excellent solution to manage its mails, and even its SMTP.

 

However, some servers may consider it a threat, so don't be scared if it does. Well, stay alert, these are still powerful tools that can be sniffed at for malicious purposes.

 

But far be it from me to frighten you.

 

To use send attachments, to mail, explore the basic offered by PHPMailer, https://github.com/PHPMailer/PHPMailer/blob/master/examples/send_file_upload.phps

 

You will however need to install the dependencies and I would only know too advise you the use of composer https://getcomposer.org for this purpose.

 

If you've never used composer, now might be the time to do so, and it's actually very easy to use, and so useful.

This little article should be able to enlighten you https://alexwebdevelop.com/phpmailer-tutorial/

This movie can be useful too https://app.pluralsight.com/course-player?clipId=1d6168e3-b3ad-47bb-a3a4-1d8b3b03ef32

 

Once composer installed, you'll have to install PHPMailer, for that open a terminal and just enter, in the appropriate root folder : 

 

composer requires phpmailer/phpmailer

 

 

Everything is said on the PHPmailer github https://github.com/PHPMailer/PHPMailer/ scroll down the page, and just below the installation procedure, you even have a little appetizer script.. .

Don't forget to visit the all examples page https://github.com/PHPMailer/PHPMailer/tree/master/examples

Legend
August 11, 2023
quote

You will however need to install the dependencies and I would only know too advise you the use of composer https://getcomposer.org for this purpose.

 


By @L e n a

 

From what l can remember the folders/scripts needed to use phpmailer are available to download on github it was, l think, so you don't have to install composer and deploy it via the terminal.

 

I've used it in the past and there's no way l would have installed composer or spun up workfiles via the terminal, far too much dependency on this kind of workflow to produce something so simple.

 

Edited:

I have just checked, and yes, phpmailer it's still available to download as a zip file so for simplicity l would go with that unless you particularly like installing extra stuff to get stuff which can be downloaded directly, many do, or more likely don't actually know it can be done simpler.

 

Maybe not even use phpmailer at all, theres plenty of solutions just using the php mail function , which is obviously available to the OP as they are currently using it to process their form.

Nancy OShea
Community Expert
Community Expert
August 4, 2023

For reference:

https://www.php.net/manual/en/features.file-upload.post-method.php

 

PHPMailer can process forms with file attachments.

https://github.com/PHPMailer/PHPMailer

 

Nancy O'Shea— Product User & Community Expert