In the below code its is uploading all file type but i need only doc and pdf file
i want to upload only doc and pdf file help me friends may i know how to do that
tomorrow is my project submission i donn't know what to do help me friends
i'm getting code from other sites but i couldn't understand anything
<?php
if(isset($_POST['name']))
{
$name=$email=$phone=$uploadresume="";
$nameErr=$emailErr=$phoneErr=$uploadresumeErr="";
function test_input($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
if ($_SERVER['REQUEST_METHOD']=="POST"){
$valid=true;
//name validaton
if(empty($_POST["name"]))
{
$nameErr="* Name is Required";
$valid=false;
}
else
{
$name=test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = " Only letters and white space allowed";
$valid=false;
}
}
//Email Address validaton
if(empty($_POST["email"]))
{
$emailErr="* Email is Required";
$valid=false;
}
else
{
$email=test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr=" Enter a valid Email ID";
$valid=false;
}
}
//Mobile no validaton
if(empty($_POST["phone"]))
{
$phoneErr="* Mobile no is Required";
$valid=false;
}
else
{
$phone=test_input($_POST["phone"]);
if(!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone))
{
$phoneErr="*Enter a valid contact no";
$valid=false;
}
}
if(empty($_FILES["filename"]['name']))
{
$uploadresumeErr="* Upload Your Resume";
$valid=false;
}
else
{
$uploadresume=test_input($_POST["filename"]);
}
if($valid)
{
$to = "example#example.co.in";
// Change this to your site admin email
$from = "$_POST[email]";
$subject = "Applied for DataEntry FROM $_POST[name] ";
//Begin HTML Email Message where you need to change the activation URL inside
// Get all the values from input
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
// Now Generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// Now Store the file information to a variables for easier access
$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$file_name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
// Now here we setting up the message of the mail
$message = "
\n\n Applied For DataEntry
\n\n Name: $name
\n\n Email: $email_address
\n\n Phone: $phone";
// Check if the upload succeded, the file will exist
if (file_exists($tmp_name)){
// Check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// Now Open the file for a binary read
$file = fopen($tmp_name,'rb');
// Now read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// Now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
// Next, we'll build the message body note that we insert two dashes in front of the MIME boundary when we use it
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// Now we'll insert a boundary to indicate we're starting the attachment we have to specify the content type, file name, and disposition as an attachment, then add the file content and set another boundary to indicate that the end of the file has been reached
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$file_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
// Thats all.. Now we need to send this mail... :)
if (#mail($to, $subject, $message, $headers))
{
?>
<div>
<center>
<h1>Your Data Has been submitted we will contact you soon !!</h1>
</center>
</div>
<?php
}else
{
?>
<div>
<center>
<h1>Error !! Unable to send yor data..</h1>
</center>
</div>
<?php
}
}
}
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<label>Name:</label>
<input type="text" name="name" value="<?php echo $_POST["name"]?>"/>
<?php echo $nameErr?> <br />
<br />
<label>Email-ID:</label>
<input type="text" name="email" value="<?php echo $_POST["email"]?>"/>
<?php echo $emailErr?> <br />
<br />
<label>Phone No:</label>
<input type="text" name="phone" value="<?php echo $_POST["phone"]?>"/>
<?php echo $phoneErr?> <br />
<br />
<label for="tele">upload Resume</label>
<input type="file" name="filename" id="tele"/>
<?php echo $uploadresumeErr?> <br />
<br />
<input style="display:block; margin-left:35em;"type="submit" value="Submit"/>
</form>
You should check the MIME type of the file that was uploaded and then do a check if the allowed type is there or not.
Checking the MIME type..
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = finfo_file($finfo, $_FILES['file']['tmp_name']);
echo $mimetype;
Your $allowedrules array
$allowedrules = array(
'application/msword',
'text/pdf',
);
You must do a check if your $mimetype exists on this array. If it is there, then it is a legit upload.
Related
I am trying to send an email from a contact page. the functionality is working fine, I am able to send mails from the html page but the only issue that I am facing is I am unable to see the Status div(success or failed).
Initially the page was redirecting to php file without any status message. I have added page redirect to the actual mailsend.html using header() in php. Now I want to have a status after the send operation whether mail has sent or not.
Below is the code snippet. Please help. Thanks in advance.
mailSend.html code:
<?php if(!empty($statusMsg)){ ?>
<p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p>
<?php } ?>
<form action="example.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="text" name="name" class="form-control" value="" placeholder="Name" required="">
</div>
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="email" name="email" class="form-control" value="" placeholder="Email address" required="">
</div>
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="text" name="subject" class="form-control" value="" placeholder="Subject" required="">
</div>
<div class="form-group">
<textarea name="message" class="form-control" placeholder="Write your message here" required="" style = 'border :0.5px solid '></textarea>
</div>
<div class="form-group">
<input type="file" name="attachment" class="form-control" style = 'border :0.5px solid; height: auto;'>
</div>
<div class="submit">
<input type="submit" name="submit" class="btn" value="SUBMIT" style= 'float : right;'>
</div>
</form>
example.php code:
<?php
//first we leave this input field blank
$recipient = "";
//if user click the send button
if(isset($_POST['submit'])){
//access user entered data
$recipient = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$sender = "From: xyz#gmail.com";
//if user leave empty field among one of them
if(empty($recipient) || empty($subject) || empty($message)){
?>
<!-- display an alert message if one of them field is empty -->
<div class="alert alert-danger text-center">
<?php echo "All inputs are required!" ?>
</div>
<?php
}else{
$uploadStatus = 1;
// Upload attachment file
if(!empty($_FILES["attachment"]["name"])){
// File path config
$targetDir = "uploads/";
$fileName = basename($_FILES["attachment"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
$uploadedFile = $targetFilePath;
}else{
$uploadStatus = 0;
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$uploadStatus = 0;
$statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
}
}
if($uploadStatus == 1){
// Recipient
$toEmail = 'abc#gmail.com';
// Sender
$from = 'xyz#gmail.com';
$fromName = 'example';
// Subject
$emailSubject = 'Contact Request Submitted by '.$recipient;
// Message
$htmlContent = '<h2>Contact Request Submitted</h2>
<p><b>Name:</b> '.$recipient.'</p>
<p><b>Email:</b> '.$sender.'</p>
<p><b>Subject:</b> '.$subject.'</p>
<p><b>Message:</b><br/>'.$message.'</p>';
// Header for sender info
$headers = "From: $fromName"." <".$from.">";
if(!empty($uploadedFile) && file_exists($uploadedFile)){
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($uploadedFile,"rb");
$data = #fread($fp,filesize($uploadedFile));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $recipient;
// Send email
$mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
// Delete attachment file from the server
#unlink($uploadedFile);
}else{
// Set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
// Send email
$mail = mail($toEmail, $emailSubject, $htmlContent, $headers);
}
// If mail sent
if($mail){
$statusMsg = 'Your contact request has been submitted successfully !';
$msgClass = 'succdiv';
?>
<!-- display a success message if once mail sent sucessfully -->
<div class="alert alert-success text-center">
<!--<?php echo "Your mail successfully sent to $recipient"?>-->
<!--readfile('submitResume.html');-->
<?php
header('Location: mailSend.html') ;
echo "Your mail successfully sent to $recipient"
?>
</div>
<?php
$recipient = "";
$postData = '';
}else{
$statusMsg = 'Your contact request submission failed, please try again.';
?>
<!-- display an alert message if somehow mail can't be sent -->
<div class="alert alert-danger text-center">
<?php echo "Failed while sending your mail!" ?>
</div>
<?php
}
}
}
}
?>
You are sending to a .html page, which does not process PHP code by default, the server just serves it unless specifically configured on the server. Rename the page from mailSend.html to mailSend.php and it should resolve it. Make sure to change your code to send to .php page.
For further reading see here
You would need to pass the message itself or a way for the script to know which message to show. The easiest way would be to pass it via $_GET, by attaching it to the end of the URL you are trying to redirect. Like so:
$target_url = mailSend.php;
$get_data = '?statusMsg=' . urlencode($statusMsg) . '&$msgClass=' . urlencode($msgClass);
header( 'Location: ' . $target_url . $get_data );
Which you can then recover on mailSend.php via the global $_GET variable. Such as:
$statusMsg = urldecode($_GET['statusMsg']);
$msgClass= urldecode($_GET['msgClass']);
There are other ways to get the data from one page to another but that I will leave it up to you to do research. As it is out of scope for a simple answer.
So I am trying to mail a form with attachment but when I include $header in my mail it fails to send: mail("mohd.gadiwala#techmatters.com", $subject, $message, $headers)
and when I remove $header from my code mail is being sent but the image attachment being send is text data and not the actual attachment image png form.Everything is crammed up w/o boundary I tried code from this website: Click Me
What am I doing wrong in my code below?:
<?php
if(isset($_POST['submit']) && $_POST['submit']=='Submit')
{
$to="siva.garre#livait.net";
$subject="File sent by ".$_POST['name'];
// get the sender's name and email address
// we'll just plug them a variable to be used later
$from = stripslashes($_POST['name'])."<".stripslashes($_POST['email']).">";
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['comment'];
// generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
if($_FILES['filename']['tmp_name'] != ''){
// store the file information to variables for easier access
$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$file_name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
}
// here we'll hard code a text message
// again, in reality, you'll normally get this from the form submission
if($tmp_name != ''){
$message = "nn Name: $name nn Email: $email_address nnMessage: nn $message nnHere is your file: $file_name";
}
else{
$message = "nn Name: $name nn Email: $email_address nnMessage: nn $message.";
}
// if the upload succeded, the file will exist
if($tmp_name != ''){
if (file_exists($tmp_name)){
// check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// open the file for a binary read
$file = fopen($tmp_name,'rb');
// read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// now we encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
}
}
// now we'll build the message headers
$headers = "From: $fromrn";
if( $tmp_name != '' ){
$headers .= "MIME-Version: 1.0rn" .
"Content-Type: multipart/mixed;rn" ;
// next, we'll build the message body
// note that we insert two dashes in front of the
// MIME boundary when we use it
$message = "This is a multi-part message in MIME format.nn" .
"Content-Type:text/plain;charset=iso-8859-1" .
"Content-Transfer-Encoding: 7bitnn" .
$message . "nn";
// now we'll insert a boundary to indicate we're starting the attachment
// we have to specify the content type, file name, and disposition as
// an attachment, then add the file content and set another boundary to
// indicate that the end of the file has been reached
$message .=
"Content-Type: ".$type."" .
" name=".$file_name."n" .
//"Content-Disposition: attachment;n" .
//" filename="{$fileatt_name}"n" .
"Content-Transfer-Encoding: base64nn" .
$data . "nn" ;
}
// now we just send the message
if (mail("mohd.gadiwala#techmatters.com", $subject, $message, $headers))
echo "<div class='msg msg-ok'><p><strong>Message Sent</strong></p></div><br><br>";
else
echo "<div class='msg msg-ok'><p><strong>Message sending failed</strong></p></div><br><br>";
}
?>
<html>
<body>
<form id="comment" action="atta.php" method="post" enctype="multipart/form-data">
<label>Name <span></span></label>
<input type="text" name="name" id="name">
<label>Email <span></span></label>
<input type="text" name="email" id="email">
<label>Comment <span></span></label>
<input type="text" name="comment" id="email">
<label>Upload file <span></span></label>
<input type="file" name="filename" id="file">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
$headers .= "MIME-Version: 1.0\r\n"; //use \r\n
Hope it helps :)
This question already has answers here:
Multiple file upload in php
(14 answers)
Closed 8 years ago.
So I have searched through a lot of questions similar to this but cannot seem to find a solution.
I have a contact form and I want it to be able to send multiple images. The code I have now has three input fields for pictures but right now I have only figured out how to get one of the pictures to upload and send. I am pretty sure I need some kind of loop or array but that is not a strong point of mine.
HTML
<form action="test.php" method="post" autocomplete="on" enctype="multipart/form-data" accept-charset='UTF-8'>
<fieldset><label for="Name">Name <sup>*</sup></label>
<input name="name" placeholder="full name" id="Name" required="" autofocus><br>
<label for="email">E-mail <sup>*</sup></label>
<input type="email" name="email" placeholder="youremail#domain.com" id="email" required=""><br>
<label for="phoneNumber">Phone # <sup>*</sup></label>
<input type="tel" name="phone" placeholder="XXX-XXX-XXXX" id="phoneNumber" required=""><br>
</fieldset>
<fieldset>
<label for="year">Year <sup>*</sup></label>
<input type="text" name="year" placeholder="year of car" id="year" required=""><br>
<label for="make">Make <sup>*</sup></label>
<input type="text" name="make" placeholder="make of car" id="make" required=""><br>
<label for="model">Model <sup>*</sup></label>
<input type="text" name="model" placeholder="model of car" id="model" required=""><br>
</fieldset>
<label for="State" class="state">State <sup>*</sup></label><br>
<input type="text" class="state" name="state" id="state" placeholder="Do not enter if you are human">
<fieldset>
<legend>Add Photos <sup>*</sup></legend>
<input type="file" name="attachment" required=""><br>
<input type="file" name="attachment"><br>
<input type="file" name="attachment"><br>
</fieldset>
<label for="comments">Comments</label><br>
<textarea style="float: left;" rows="4" name="comment" id="comments" placeholder="additional comments"></textarea>
<br>
<input class="button" type="submit" name="submit" value="Send" class="button">
<p class="required"><sup>*</sup> denotes a required field.</p>
</form>
PHP
<?php
$to = '';
$name = $_POST['name'];
$email = $_POST ['email'];
$phone = $_POST['phone'];
$year = $_POST['year'];
$make = $_POST['make'];
$model = $_POST['model'];
$comment = $_POST['comment'];
$state = $_POST['state'];
$message = "
Name: $name
E-mail: $email
Phone: $phone
Year: $year
Make: $make
Model: $model
Message: $comment
";
if($_POST['state'] != ''){
echo "It appears you are a bot!";
exit();
}
else{
//process the rest of the form
}
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
/* Start of headers */
$headers = "From: $name $email";
if (file($tmpName)) {
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
/* a boundary string */
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
/* Encoding file data */
$data = chunk_split(base64_encode($data));
/* Adding attchment-file to message*/
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
$flgchk = mail ("$to", "$subject", "$message", "$headers");
if($flgchk){
echo "A email has been sent. We will get back to you as soon as
possible.";
}
else{
echo "Error in Email sending";
}
?>
All three of your fields are named "attachment". Give them unique names like "attachment1", "attachment2", etc.
Then use this on your upload:
for ($x = 1; $x <= $numberOfFiles; ++$x) {
$tmpName = $_FILES['attachment'.$x]['tmp_name'];
$fileType = $_FILES['attachment'.$x]['type'];
$fileName = $_FILES['attachment'.$x]['name'];
// do your upload here
}
You could even do it in a loop like this, which would allow you to add more file fields (maybe with JavaScript) without changing the backend code, as long as you kept the naming pattern consistent.
$x = 1;
while (isset($_FILES['attachment'.$x])) {
$tmpName = $_FILES['attachment'.$x]['tmp_name'];
$fileType = $_FILES['attachment'.$x]['type'];
$fileName = $_FILES['attachment'.$x]['name'];
// do your upload here
++$x;
}
That just increments x on each cycle, and checks to see if a file was sent with that name.
You should probably also include some checking on the size and type of files, before someone fills your inbox with huge files and/or cyber-nasties.
UPDATE: This should be a mostly-complete solution for you. I'm not able to test it for you at the moment so it may not work straight out of the box, but it should at least point you in the right direction. In this code snippet it sets up the initial part of the email first, then loops through and adds each file one at a time.
<?php
$to = '';
$name = $_POST['name'];
$email = $_POST ['email'];
$phone = $_POST['phone'];
$year = $_POST['year'];
$make = $_POST['make'];
$model = $_POST['model'];
$comment = $_POST['comment'];
$state = $_POST['state'];
$message = "Name: $name
E-mail: $email
Phone: $phone
Year: $year
Make: $make
Model: $model
Message: $comment";
if($_POST['state'] != ''){
echo "It appears you are a bot!";
exit();
}
/* Start of headers */
$headers = "From: $name $email";
/* a boundary string */
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
/* Loop through files */
$x = 1;
while (isset($_FILES['attachment'.$x])) {
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
/* Skip invalid files */
if (!file($tmpName)) {
++$x;
continue;
}
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
/* Encoding file data */
$data = chunk_split(base64_encode($data));
/* Adding attchment-file to message*/
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
++$x;
}
/* Close the message */
$message .= "--{$mimeBoundary}--\n";
$flgchk = mail ("$to", "$subject", "$message", "$headers");
if($flgchk){
echo "A email has been sent. We will get back to you as soon as possible.";
} else {
echo "Error in Email sending";
}
?>
After submitting the form it shows
"Your Data Has been submitted we will contact you soon !!"
at the same time, the form inputs fields remains in the Page(Still submiited data exist on the fields)
How can I clear the data in input fields after submitted
Here is my code :
<?php
if(isset($_POST['name']))
{
include_once("config.php");
$name=$email=$phone=$uploadresume="";
$nameErr=$emailErr=$phoneErr=$uploadresumeErr="";
function test_input($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
if ($_SERVER['REQUEST_METHOD']=="POST"){
$valid=true;
//name validaton
if(empty($_POST["name"]))
{
$nameErr="* Name is Required";
$valid=false;
}
else
{
$name=test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = " Only letters and white space allowed";
$valid=false;
}
}
//Email Address validaton
if(empty($_POST["email"]))
{
$emailErr="* Email is Required";
$valid=false;
}
else
{
$email=test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr=" Enter a valid Email ID";
$valid=false;
}
}
//Mobile no validaton
if(empty($_POST["phone"]))
{
$phoneErr="* Mobile no is Required";
$valid=false;
}
else
{
$phone=test_input($_POST["phone"]);
if(!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone))
{
$phoneErr="*Enter a valid contact no";
$valid=false;
}
}
if(empty($_FILES["filename"]['name']))
{
$uploadresumeErr="* Upload Your Resume";
$valid=false;
}
else
{
$fname_arr = explode('.',$_FILES["filename"]['name']);
$fileext = $fname_arr[count($fname_arr)-1];
$ext_arr = array('doc','pdf');
if(in_array($fileext,$ext_arr))
{
$uploadresume=test_input($_POST["filename"]);
}
else{
$uploadresumeErr="* Upload only doc or pdf files.";
$valid=false;
}
}
if($valid)
{
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO jobopening(name, email, phone,applieddate,Appliedjob)
VALUES('$_POST[name]','$_POST[email]','$_POST[phone]', now(),'dataentry')") or die (mysql_error());
// Get the inserted ID here to use in the activation email
$id = mysql_insert_id();
$to = "example#example.co.in";
// Change this to your site admin email
$from = "$_POST[email]";
$subject = "Applied for DataEntry FROM $_POST[name] ";
//Begin HTML Email Message where you need to change the activation URL inside
// Get all the values from input
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
// Now Generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// Now Store the file information to a variables for easier access
$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$file_name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
// Now here we setting up the message of the mail
$message = "
\n\n Applied For DataEntry
\n\n Name: $name
\n\n Email: $email_address
\n\n Phone: $phone";
// Check if the upload succeded, the file will exist
if (file_exists($tmp_name)){
// Check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// Now Open the file for a binary read
$file = fopen($tmp_name,'rb');
// Now read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// Now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
// Next, we'll build the message body note that we insert two dashes in front of the MIME boundary when we use it
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// Now we'll insert a boundary to indicate we're starting the attachment we have to specify the content type, file name, and disposition as an attachment, then add the file content and set another boundary to indicate that the end of the file has been reached
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$file_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
// Thats all.. Now we need to send this mail... :)
if (#mail($to, $subject, $message, $headers))
{
?>
<div><center><h1>Your Data Has been submitted we will contact you soon !!</h1></center></div>
<?php
}else
{
?>
<div>
<center>
<h1>Error !! Unable to send yor data..</h1>
</center>
</div>
<?php
}
}
}
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<label>Name:</label>
<input type="text" name="name" value="<?php echo $_POST["name"]?>"/>
<?php echo $nameErr?> <br />
<br />
<label>Email-ID:</label>
<input type="text" name="email" value="<?php echo $_POST["email"]?>"/>
<?php echo $emailErr?> <br />
<br />
<label>Phone No:</label>
<input type="text" name="phone" value="<?php echo $_POST["phone"]?>"/>
<?php echo $phoneErr?> <br />
<br />
<label for="tele">upload Resume</label>
<input type="file" name="filename" id="tele"/>
<?php echo $uploadresumeErr?> <br />
<br />
<input style="display:block; margin-left:35em;"type="submit" value="Submit"/>
</form>
Store $_POST in a variable inside
if(isset($_POST['name']))
{
$post_val=$_POST;
---------
Then,Unset $post_val after sending email
if (#mail($to, $subject, $message, $headers))
{
unset($post_val);
?>
Show the values from $_post_val
<input type="text" name="name" value="<?php echo $_post_val["name"]?>"/>
<input type="text" name="email" value="<?php echo $_post_val["email"]?>"/>
<input type="text" name="phone" value="<?php echo $_post_val["phone"]?>"/>
You are setting the value of the fields using the $_POST variable. Once the form is submitted the $_POST array gets populated. So when the page is loaded after submitting , the values of the inputs are set. You need to remove them.
Change
<input type="text" name="name" value="<?php echo $_POST["name"]?>"/>
<input type="text" name="email" value="<?php echo $_POST["email"]?>"/>
<input type="text" name="phone" value="<?php echo $_POST["phone"]?>"/>
to
<input type="text" name="name" value=""/>
<input type="text" name="email" value=""/>
<input type="text" name="phone" value=""/>
After Inserting data into data base and sending email, You should Redirect to the same page
header("location:".$_SERVER['PHP_SELF']);
In the below code i have validation for all fields
Without validation in upload resume i can upload the file
Validations are working but i can't upload the file
may i know how to do validation in upload file:
<?php
if(isset($_POST['name']))
{
$name=$email=$phone=$uploadresume="";
$nameErr=$emailErr=$phoneErr=$uploadresumeErr="";
function test_input($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
if ($_SERVER['REQUEST_METHOD']=="POST"){
$valid=true;
//name validaton
if(empty($_POST["name"]))
{
$nameErr="* Name is Required";
$valid=false;
}
else
{
$name=test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = " Only letters and white space allowed";
$valid=false;
}
}
//Email Address validaton
if(empty($_POST["email"]))
{
$emailErr="* Email is Required";
$valid=false;
}
else
{
$email=test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr=" Enter a valid Email ID";
$valid=false;
}
}
//Mobile no validaton
if(empty($_POST["phone"]))
{
$phoneErr="* Mobile no is Required";
$valid=false;
}
else
{
$phone=test_input($_POST["phone"]);
if(!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone))
{
$phoneErr="*Enter a valid contact no";
$valid=false;
}
}
if(empty($_POST["filename"]))
{
$uploadresumeErr="* Upload Your Resume";
$valid=false;
}
else
{
$uploadresume=test_input($_POST["filename"]);
}
if($valid)
{
$to = "example#example.co.in";
// Change this to your site admin email
$from = "$_POST[email]";
$subject = "Applied for DataEntry FROM $_POST[name] ";
//Begin HTML Email Message where you need to change the activation URL inside
// Get all the values from input
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
// Now Generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// Now Store the file information to a variables for easier access
$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$file_name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
// Now here we setting up the message of the mail
$message = "
\n\n Applied For DataEntry
\n\n Name: $name
\n\n Email: $email_address
\n\n Phone: $phone";
// Check if the upload succeded, the file will exist
if (file_exists($tmp_name)){
// Check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// Now Open the file for a binary read
$file = fopen($tmp_name,'rb');
// Now read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// Now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
// Next, we'll build the message body note that we insert two dashes in front of the MIME boundary when we use it
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// Now we'll insert a boundary to indicate we're starting the attachment we have to specify the content type, file name, and disposition as an attachment, then add the file content and set another boundary to indicate that the end of the file has been reached
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$file_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
// Thats all.. Now we need to send this mail... :)
if (#mail($to, $subject, $message, $headers))
{
?>
<div>
<center>
<h1>Your Data Has been submitted we will contact you soon !!</h1>
</center>
</div>
<?php
}else
{
?>
<div>
<center>
<h1>Error !! Unable to send yor data..</h1>
</center>
</div>
<?php
}
}
}
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<label>Name:</label>
<input type="text" name="name" value="<?php echo $_POST["name"]?>"/><?php echo $nameErr?>
<br />
<br />
<label>Email-ID:</label>
<input type="text" name="email" value="<?php echo $_POST["email"]?>"/><?php echo $emailErr?>
<br />
<br />
<label>Phone No:</label>
<input type="text" name="phone" value="<?php echo $_POST["phone"]?>"/><?php echo $phoneErr?>
<br />
<br />
<label for="tele">upload Resume</label>
<input type="file" name="filename" id="tele"/><?php echo $uploadresumeErr?>
<br /><br />
<input style="display:block; margin-left:35em;"type="submit" value="Submit"/>
</form>
For validation of file use the below code :
if(empty($_FILES["filename"]['name']))
{
$uploadresumeErr="* Upload Your Resume";
$valid=false;
}
else
{
$uploadresume=test_input($_POST["filename"]);
}