How to change the upload folder in php? - php

i have this php code for a form with attachment;
i need to change upload folder, with email.
I mean: now, if anyone upload a file it goes to a directory, but i want that this form sends the file to my email adress.
Is this possibile?
Thank You
<?php
// Pear library includes
// You should have the pear lib installed
include_once('Mail.php');
include_once('Mail_Mime/mime.php');
//Settings
$max_allowed_file_size = 100; // size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp");
$upload_folder = './uploads/';
$your_email = 'annie.etoile#gmail.com';
$errors ='';
if(isset($_POST['submit']))
{
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
$type_of_uploaded_file = substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file = $_FILES["uploaded_file"]["size"]/1024;
if(empty($_POST['name'])||empty($_POST['email']))
{
$errors .= "\n Name and Email are required fields. ";
}
if(IsInjected($visitor_email))
{
$errors .= "\n Bad email value!";
}
if($size_of_uploaded_file > $max_allowed_file_size )
{
$errors .= "\n Size of file should be less than $max_allowed_file_size";
}
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$errors .= "\n The uploaded file is not supported file type. ".
" Only the following file types are supported: ".implode(',',$allowed_extensions);
}
if(empty($errors))
{
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path))
{
if(!copy($tmp_path,$path_of_uploaded_file))
{
$errors .= '\n error while copying the uploaded file';
}
}
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$user_message = $_POST['message'];
$to = $your_email;
$subject="New form submission";
$from = $your_email;
$text = "A user $name has sent you this message:\n $user_message";
$message = new Mail_mime();
$message->setTXTBody($text);
$message->addAttachment($path_of_uploaded_file);
$body = $message->get();
$extraheaders = array("From"=>$from, "Subject"=>$subject,"Reply-To"=>$visitor_email);
$headers = $message->headers($extraheaders);
$mail = Mail::factory("mail");
$mail->send($to, $headers, $body);
//redirect to 'thank-you page
header('Location: thank-you.html');
}
}
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File upload form</title>
<!-- define some style elements-->
<style>
label,a, body
{
font-family : Arial, Helvetica, sans-serif;
font-size : 12px;
}
</style>
<!-- a helper script for vaidating the form-->
<script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>
</head>
<body>
<?php
if(!empty($errors))
{
echo nl2br($errors);
}
?>
<form method="POST" name="email_form_with_php"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" enctype="multipart/form-data">
<p>
<label for='name'>Name: </label><br>
<input type="text" name="name" >
</p>
<p>
<label for='email'>Email: </label><br>
<input type="text" name="email" >
</p>
<p>
<label for='message'>Message:</label> <br>
<textarea name="message"></textarea>
</p>
<p>
<label for='uploaded_file'>Select A File To Upload:</label> <br>
<input type="file" name="uploaded_file">
</p>
<input type="submit" value="Submit" name='submit'>
</form>
<script language="JavaScript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator = new Validator("email_form_with_php");
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email","Please enter a valid email address");
</script>
<noscript>
<small><a href='http://www.html-form-guide.com/email-form/php-email-form-attachment.html'
>How to attach file to email in PHP</a> article page.</small>
</noscript>
</body>
</html>

Related

PHP email attachment file

i have created finally this code for a contact form and there is one thing missing as i want to but maximum size 5 MB and when if tried function if($file_size > 5000000){$fileErr = "max allowed size is 5 mb";} else{$check6 = 1;} but it didn't work and the code is not working but if i remove this function everything else will work great so any help with that and when i solve this problem i will add the code here so everyone can get a benefit from that .... and here is the code below
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<!-- Start PHP CODE -->
<?php
// Show errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = $fileErr = $fileErr2 = $result = "" ;
// when we press submit do the following
if(isset($_POST['submit']))
{
// define contact form variables
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$design = $_POST['design'];
$country = $_POST['country'];
$comment = $_POST['comment'];
$human = $_POST['human'];
// define Checks variables
$check1 = $check2 = $check3 = $check4 = $check5 = $check6 = "";
// Let's do some checks
// Checking the First Name
if(empty($_POST["fname"])){
$fnameErr = "Name is Required";
}else{
$fname = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
}else{
$check1 = 1;
}
}
// Checking the Last Name
if(empty($_POST["lname"])){
$lnameErr = "Name is Required";
}else{
$lname = test_input($_POST["lname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
}else{
$check2 = 1;
}
}
//Checking the Email Adress
if(empty($_POST["email"])){
$emailErr = "Email is Required";
}else{
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}else{
$check3 = 1;
}
}
//Checking the Anti-Spam Question
if(empty($_POST["human"])){
$humanErr = "Please Enter the Answer";
}else{
if ($human != 4){
$humanErr = "Please check your answer";
}else{
$check4 = 1;
}
}
// checking the attachment
if(isset($_FILES) && (bool) $_FILES) {
$allowedExtensions = array("pdf","doc","docx");
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
$file_type = $file['type'];
$file_size = $file['size'];
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
$fileErr = "File $file_name has the extensions $ext which is not allowed";
}else{
$check5 = 1;
}
if($file_size > 5000000){
$fileErr = "Max allowed size is 5 MB";
} else {
$check6 = 1;
}
array_push($files,$file);
}
// define email variables
$to = 'eng.bolaraafat#gmail.com';
$from = "qyas.ae- contact form";
$subject = 'Contact Form';
$message = 'From: '.$fname .$lname."\r\n".
'E-mail: '.$email."\r\n".
'Telephone: '.$tel."\r\n".
'Designation: '.$design."\r\n".
'Country Appled From: '.$country."\r\n".
'Message: '.$comment."\r\n"."\r\n";
$headers = "From: $from";
// 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 = "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";
$message .= "--{$mime_boundary}\n";
// preparing attachments
if(!empty($_FILES["my_file"])){
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x]['tmp_name'],"rb");
$data = fread($file,filesize($files[$x]['tmp_name']));
fclose($file);
$data = chunk_split(base64_encode($data));
$name = $files[$x]['name'];
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$name\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$name\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}}else{
$fileErr = "Please Attach your Resume";
}
// Emailing the Contents if all Checks are correct
if($check1 && $check2 && $check3 && $check4 && $check5 && $check6 == 1){
mail($to, $subject, $message, $headers);
$result = "Message Sent Sucessfully";
}else{
$result = "Message Can't be sent";
}
} }
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!-- END OF PHP CODE -->
<h2>Contact Form</h2>
<p><span style="color: red" >*Required fields</span></p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data" accept-charset="UTF-8">
First Name:<input type="text" name="fname"><span style="color: red" >* <?php echo $fnameErr ?> </span><br><br>
Last Name:<input type="text" name="lname"><span style="color: red" >* <?php echo $lnameErr ?></span> <br><br>
E-mail:<input type="text" name="email"><span style="color: red" >* <?php echo $emailErr ?></span> <br><br>
Telephone:<input type="text" name="tel"><br><br>
Designation:<select name="design">
<option value="Architectural Engineer">Architectural Engineer</option>
<option value="Structural Engineer">Structural Engineer</option>
<option value="Draughts-man">Draughts-man</option>
<option value="Receptionist">Receptionist</option>
<option value="Secertary">Secertary</option>
</select><br><br>
Country Applied From:<select name="country">
<option value="">Country...</option>
<option value="Afganistan">Afghanistan</option>
<option value="Albania">Albania</option>
</select><br><br>
Message:<textarea name="comment"></textarea> <br><br>
Upload Your Resume:<input type="file" name="my_file"><span style="color: red; margin-left: -60px;" >*<?php echo $fileErr ?></span><br><br>
<label>*What is 2+2? (Anti-spam)</label>
<input name="human" placeholder="Type Here"><span style="color: red" >*<?php echo $humanErr ?></span><br><br>
<input type="submit" name="submit" value="Submit">
<input type="reset" value="Clear"><br><br>
<strong><?php echo $result ?></strong>
</form><br>
</body>
</html>
You have set $check5=1 when allowedExtensions is true. Next to it, you check file_size. When your file_size > 5MB, check5 was not reset or change. So if your attachment is proper & file_size > 5mb system will try to send email with attachment (which you don't want) as check5==1. So to stop it you need to set check5=0 when file_size > 5MB.
Please update your code like :
if($file_size > 5000000){
$fileErr .= "Max allowed size is 5 MB";
} else {
$check6 = 1;
array_push($files,$file);
}
Hope this is clear
Your condition is correct and your code is also working fine. Please recheck.
Try PHPMailer, I am using it there will be no problem.
<?php
/**
* PHPMailer simple file upload and send example
*/
$msg = '';
if (array_key_exists('userfile', $_FILES)) {
// First handle the upload
// Don't trust provided filename - same goes for MIME types
// See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name']));
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
// Upload handled successfully
// Now create a message
// This should be somewhere in your include_path
require '../PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom('from#example.com', 'First Last');
$mail->addAddress('whoto#example.com', 'John Doe');
$mail->Subject = 'PHPMailer file sender';
$mail->Body = 'My message body';
// Attach the uploaded file
$mail->addAttachment($uploadfile, 'My uploaded file');
if (!$mail->send()) {
$msg .= "Mailer Error: " . $mail->ErrorInfo;
} else {
$msg .= "Message sent!";
}
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PHPMailer Upload</title>
</head>
<body>
<?php if (empty($msg)) { ?>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000"> Send this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>
<?php } else {
echo $msg;
} ?>
</body>
</html>

Check if email address exist in database and captcha code is correct if not give alert and dont save data in database

i wrote a code for a form in which i added a two validation first one is through email and second one is through email. when user enter's the email address which already exist in a data base it will show an error. the problem which i faced is that when user enter's a new email address and wrong captcha code than it will show an error but at the same time it will save that into the data base also. Here's the complete code is given
<?php
include('../config/connection.php');
//DATABASE INSERT QUERY
if(isset($_POST['submit']))
{
$finame = $_POST['finame'];
$email = $_POST['email'];
$user_message = $_POST['message'];
$b="SELECT * from form WHERE email='".$_POST['email']."'";
$res = mysql_query($b);
$tot = mysql_fetch_assoc($res);
if(empty($tot) || empty($_SESSION['6_letters_code'] ) ||
strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) == 0)
{
$sel = "insert into ".form." set finam='".$_POST['finam']."',lnam='".$_POST['lnam']."',dob='".$_POST['dob']."',cntn='".$_POST['cntn']."',fanam='".$_POST['fanam']."',str='".$_POST['str']."',email='".$_POST['email']."',passw='".$_POST['passw']."'";
mysql_query($sel);
}
//-------------------------------Captcha--------------------
$your_email ='yourname#your-website.com';// <<=== update to your email address
session_start();
$errors = '';
$finame = '';
$email = '';
$user_message = '';
///------------Do Validations-------------
if(!empty($tot))
{
$errors .= "\n Re-enter the captcha code...!!! ";
$msg .="Email adreess already exist";
}
if(IsInjected($email))
{
$errors .= "\n Bad email value!";
}
if(empty($_SESSION['6_letters_code'] ) ||
strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
{
// strcmp()
$errors .= "\n The captcha code does not match!";
}
if(empty($errors))
{
//send the email
$to = $your_email;
$subject="New form submission";
$from = $your_email;
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$body = "A user $name submitted the contact form:\n".
"Name: $finame\n".
"Email: $email \n".
"Message: \n ".
"$user_message\n".
"IP: $ip\n";
$headers = "From: $from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to, $subject, $body,$headers);
header('Location: ../admin/sign-in1.php');
}
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="jsDatePick_ltr.min.css" />
<script type="text/javascript" src="jsDatePick.min.1.3.js"></script>
<script type="text/javascript">
window.onload = function(){
new JsDatePick({
useMode:2,
target:"inputField",
dateFormat:"%d-%M-%Y"
});
};
</script>
<title>Form</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
<script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>
</head>
<body>
<div style="width:100%; height:170px; margin:auto;">
<div class="abc">
<h1 style="margin:5% 0 0 5%; width:10%; color:#FFF;">Form</h1>
<!--</form>-->
<?php
$sel = "select * from home";
$a=mysql_query($sel);
$fetch = mysql_fetch_array($a);
?>
<div class="sample"> <?php echo $fetch['home4'];?></div>
<div class="main" style="margin:4% 0 0 0;">
Home
About us
Gallery
Contact us
</div>
</div>
</div>
<div style=" width:100%; margin:5% 0 0 0; height:auto;">
<div style="margin:auto; width:80%">
<form method="post" class="w3-container" onSubmit="alert('Thank you. You are registered now input your login id and passwprd to make changes on index and another pages...')" >
<div class="w3-group">
<input class="w3-input blue-l4" pattern="[A-Za-z]{3,}" title="only alphabets" value="<?php echo $_POST['finam'] ?>" type="text" name="finam"required>
<label class="w3-label">First-Name</label>
</div>
<div class="w3-group">
<input class="w3-input blue-l4" pattern="[A-Za-z]{3,}" title="only alphabets" value="<?php echo $_POST['lnam'] ?>" type="text" name="lnam"required>
<label class="w3-label">Last name</label>
</div>
<div class="w3-group">
<input class="w3-input blue-l4" type="text" size="12" readonly id="inputField" value="<?php echo $_POST['dob'] ?>" name="dob" placeholder="DD/MM/YY"required>
</div>
<div class="w3-group">
<input class="w3-input blue-l4" type="text" pattern="[A-Za-z]{3,}" title="only alphabets" value="<?php echo $_POST['fanam'] ?>" name="fanam"required>
<label class="w3-label">Father's name</label>
</div>
<div class="w3-group">
<?php
if(!empty($msg)){
echo "<p class='err'>".nl2br($msg)."</p>";
}
?>
<input class="w3-input blue-l4" value="<?php echo $_POST['email'] ?>" type="email" name="email"required>
<label class="w3-label">Email</label>
</div>
<div class="w3-group">
<input class="w3-input blue-l4" type="password" name="passw" required>
<label class="w3-label">Password</label>
</div>
<div class="w3-group">
<input class="w3-input blue-l4" pattern="[0-9]+" value="<?php echo $_POST['cntn'] ?>" title="only numeric value" type="text" name="cntn"required>
<label class="w3-label">Contact no.</label>
</div>
<div class="clear"></div>
<div class="w3-group">
<select name="str" class="w3-input blue-l4">
<option>--Select Stream--</option>
<?php
$sel = "select * from stream";
$a=mysql_query($sel);
while($fetch = mysql_fetch_array($a))
{
?>
<option><?php echo $fetch['str']?></option>
<?php
}
?>
</select>
</div>
<div class="w3-group">
<?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?>
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
<label for='message'>Enter the code above here :</label><br>
<input class="w3-input blue-l4" id="6_letters_code" name="6_letters_code" type="text"><br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small> </div>
<button class="w3-btn blue-d1" name="submit" value="submit">Submit</button>
</form>
</div>
</div>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
var img = document.images['captchaimg'];
img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
<div class="foot" style="margin-top:4px;">
<div style="margin:2% 0 2% 86%;">
<img style="margin:0 0 12px 12px;" src="index.jpg" width="30" height="30"/>
<img style="margin:0 0 12px 12px;" src="images1.png" width="30" height="30"/>
<img src="googleplus.png" width="50" height="50"/>
</div>
</div>
</div>
</body>
</html>
Several comments here. First, and maybe the most important, you're using mysql_* functions, which are deprecated and is no longer maintained. You should seriously consider converting to MySQLi or PDO, which has prepared statements (that protects you against SQL-inection). mysql_* is bad practice.
Furthermore, you are mixing variable-names in your code. You're using both $_POST['finam'] and $_POST['finame'], which I assume are one and the same. Be careful with your names!
And you're inserting the password in plain text -- this is also a security issue! You should really hash your password, so that it's never stored in plain text (in case of a hacker accessing your database).
As for your question: You are inserting into the database with a series of or-operators in your if-statement. This means as long as one of them returns TRUE, it'll run the query and insert the email.
I'm not really sure how you do your CAPTCHA-validating, but I think this code will work more as intended.
<?php
session_start();
include('../config/connection.php');
//DATABASE INSERT QUERY
if (isset($_POST['submit'])) {
$finame = $_POST['finam'];
$lname = $_POST['lnam'];
$dob = $_POST['dob'];
$passw = $_POST['passw'];
$email = $_POST['email'];
$fanam = $_POST['fanam'];
$cntn = $_POST['cntn'];
$user_message = $_POST['message'];
$str = $_POST['str'];
$errors = '';
///------------Do Validations-------------
// Checking if the email exists in the database
$res = mysql_query("SELECT * FROM form WHERE email=$email");
// If the number of rows from the result is greater than 0, the email is already in our database
if (mysql_num_rows($res) > 0) {
$errors .= "\n Email exists!";
$emailAvailable = false;
} else {
$emailAvailable = true;
}
if (!$emailAvailable)) {
$errors .= "\n Re-enter the captcha code...!!! ";
$msg .= "Email adreess already exist";
}
if (IsInjected($email)) {
$errors .= "\n Bad email value!";
$badEmail = false;
} else {
$badEmail = true;
}
if (empty($_SESSION['6_letters_code'] ) || strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0) {
// strcmp()
$errors .= "\n The captcha code does not match!";
$captcha = false;
} else {
$captcha = true;
}
///------------If all is well, inserting the email-------------
if ($emailAvailable && $captcha && $badEmail) {
// $sel = "insert into ".form." set finam='".$_POST['finam']."',lnam='".$_POST['lnam']."',dob='".$_POST['dob']."',cntn='".$_POST['cntn']."',fanam='".$_POST['fanam']."',str='".$_POST['str']."',email='".$_POST['email']."',passw='".$_POST['passw']."'";
$sel = "INSERT INTO form (finam, lnam, dob, cntn, fanam, str, email, passw) VALUES ($finame, $lname, $dob, $cntn, $fanam, $str, $email, $passw)";
mysql_query($sel);
}
//-------------------------------Captcha--------------------
$your_email ='yourname#your-website.com';// <<=== update to your email address
if(empty($errors)) {
//send the email
$to = $your_email;
$subject = "New form submission";
$from = $your_email;
$ip = $_SERVER['REMOTE_ADDR'];
$body = "A user $name submitted the contact form:\n".
"Name: $finame\n".
"Email: $email \n".
"Message: \n ".
"$user_message\n".
"IP: $ip\n";
$headers = "From: $from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to, $subject, $body,$headers);
header('Location: ../admin/sign-in1.php');
}
}
// Function to validate against any email injection attempts
function IsInjected($str) {
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if (preg_match($inject,$str)) {
return true;
} else {
return false;
}
}
?>
As you can see, I also updated your INSERT-query, it was kind of messy.

Website html form with image attachment ...cant get the attachment via email

I am trying to make a form that user can upload their own image through the website contact form...however, i can receive the input wordings but not the attachment...does anyone can point out the error?
//Settings
$max_allowed_file_size = 10000; // size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp");
$upload_folder = './uploads/'; //<-- this folder must be writeable by the script
$your_email = 'tcc#hotmail.com';//<<-- update this to your email address
$errors ='';
if(isset($_POST['submit']))
{
//Get the uploaded file information
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file = substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file = $_FILES["uploaded_file"]["size"]/1024;
///------------Do Validations-------------
if(empty($_POST['name'])||empty($_POST['email']))
{
$errors .= "\n Name and Email are required fields. ";
}
if(IsInjected($visitor_email))
{
$errors .= "\n Bad email value!";
}
if($size_of_uploaded_file > $max_allowed_file_size )
{
$errors .= "\n Size of file should be less than $max_allowed_file_size";
}
//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$errors .= "\n The uploaded file is not supported file type. ".
" Only the following file types are supported: ".implode(',',$allowed_extensions);
}
//send the email
if(empty($errors))
{
//copy the temp. uploaded file to uploads folder
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path))
{
if(!copy($tmp_path,$path_of_uploaded_file))
{
$errors .= '\n error while copying the uploaded file';
}
}
}}
?>
//send the email
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//define the receiver of the email
$to = 'tcc#hotmail.com';
//define the subject of the email
$subject = 'Decor';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('./uploads/'.$_POST[$path_of_uploaded_file])));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
Name: <?php echo $_POST['name']; ?>
Email: <?php echo $_POST['email']; ?>
Picture Name: <?php echo $_POST['picname']; ?>
Description: <?php echo $_POST['description']; ?>
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 7bit
Name: <?php echo $_POST['name']; ?><br/>
Email: <?php echo $_POST['email']; ?><br/>
Picture Name: <?php echo $_POST['picname']; ?><br/>
Description: <?php echo $_POST['description']; ?><br/>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: data:image/jpg; name="photo.jpg "
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$sent = mail($to, $subject, $message, $headers) ;
if ($sent) {
header("Location: http://www.tcc.hk/vday2014/thanks.php");
exit();
} else {
print "We encountered an error sending your mail";
}
}
?>
<?
///////////////////////////Functions/////////////////
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File upload form</title>
<!-- define some style elements-->
<style>
label,a, body
{
font-family : Arial, Helvetica, sans-serif;
font-size : 12px;
}
</style>
<!-- a helper script for vaidating the form-->
<script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>
</head>
<body>
<?php
if(!empty($errors))
{
echo nl2br($errors);
}
?>
<form method="POST" name="email_form_with_php"
onsubmit="return validateForm()"
>
<p>
<label for='name'>Name: </label><br>
<input type="text" name="name" >
</p>
<p>
<label for='email'>Email: </label><br>
<input type="text" name="email" >
</p>
<p>
<label for='message'>Message:</label> <br>
<textarea name="message"></textarea>
</p>
<p>
<label for='uploaded_file'>Select A File To Upload:</label> <br>
<input type="file" name="uploaded_file">
</p>
<input type="submit" value="Submit" name='submit'>
</form>
<script language="JavaScript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator = new Validator("email_form_with_php");
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email","Please enter a valid email address");
</script>
<noscript>
<small><a href='http://www.html-form-guide.com/email-form/php-email-form-attachment.html'
>How to attach file to email in PHP</a> article page.</small>
</noscript>
</body>
</html>
Form (same doc)
<form method="POST" name="email_form_with_php"
onsubmit="return validateForm()"
>
<p>
<label for='name'>Name: </label><br>
<input type="text" name="name" >
</p>
<p>
<label for='email'>Email: </label><br>
<input type="text" name="email" >
</p>
<p>
<label for='message'>Message:</label> <br>
<textarea name="message"></textarea>
</p>
<p>
<label for='uploaded_file'>Select A File To Upload:</label> <br>
<input type="file" name="uploaded_file">
</p>
<input type="submit" value="Submit" name='submit'>
</form>
Set the enctype attribute in your form to "multipart/form-data" Otherwise, file fields don't work.
In your form you need to add enctype="multipart/form-data"
So i.e:
<form method="POST" name="email_form_with_php"
enctype="multipart/form-data"
onsubmit="return validateForm()"
>

Sending an email form with attachment using PEAR

I have created an HTML from that is using PEAR Mail_Mime. Once the form is submited I get the attachment no problem. The problem I am having is that the input fields (Name, Phone, Email) of the form are not included in the email that I receive. How can I get this info too? I am a Noobie when it comes to PHP so be gentle.
<?php
include('PEAR/Mail.php');
include('PEAR/Mail/mime.php');
$max_allowed_file_size = 900; // size in KB
$allowed_extensions = array("pdf", "doc", "docx", "txt");
$upload_folder = './uploads/'; //<-- this folder must be writeable by the script
$your_email = 'gradysapp#gmail.com';//<<-- update this to your email address
$errors ='';
if(isset($_POST['submit']))
{
//Get the uploaded file information
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file = substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file = $_FILES["uploaded_file"]["size"]/1024;
///------------Do Validations-------------
if(empty($_POST['name'])||empty($_POST['email']))
{
$errors .= "\n Name and Email are required fields. ";
}
if(IsInjected($visitor_email))
{
$errors .= "\n Bad email value!";
}
if($size_of_uploaded_file > $max_allowed_file_size )
{
$errors .= "\n Size of file should be less than $max_allowed_file_size";
}
//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$errors .= "\n The uploaded file is not supported file type. ".
" Only the following file types are supported: ".implode(',',$allowed_extensions);
}
//send the email
if(empty($errors))
{
//copy the temp. uploaded file to uploads folder
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path))
{
if(!copy($tmp_path,$path_of_uploaded_file))
{
$errors .= '\n error while copying the uploaded file';
}
}
//send the email
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$user_message = $_POST['message'];
$to = $your_email;
$subject="New form submission";
$from = $your_email;
$text = "A user $name has sent you this message:\n $user_message";
$message = new Mail_mime();
$message->setTXTBody($text);
$message->addAttachment($path_of_uploaded_file);
$body = $message->get();
$extraheaders = array("From"=>$from, "Subject"=>$subject,"Reply-To"=>$visitor_email);
$headers = $message->headers($extraheaders);
$mail = Mail::factory("mail");
$mail->send($to, $headers, $body);
//redirect to 'thank-you page
header('Location: careers_thank-you.html');
}
}
///////////////////////////Functions/////////////////
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
Here is the form if there is anything wrong in the code here.
<?php
if(!empty($errors))
{
echo nl2br($errors);
}
?>
<form method="POST" name="email_form_with_php"
action="php-form-action.php" enctype="multipart/form-data">
<p>
<label for='name'>Name: </label><br>
<input type="text" name="name" >
</p>
<p>
<label for='email'>Email: </label><br>
<input type="text" name="email" >
</p>
<p>
<label for='phone'>Phone: </label><br>
<input type="text" name="phone" >
<p>
<label for='position'>Which position are you applying for? </label><br>
<input type="text" name="position" >
<p>
<label for='resume_uploaded_file'>Please attach your resume or work history.</label><br>
<input type="file" name="uploaded_file">
<span class="smallNote">(PDF or Word Document)</span>
<p>
<label for='letter_uploaded_file'>Please attach your cover letter.</label><br>
<input type="file" name="letter_uploaded_file">
<span class="smallNote">(PDF or Word Document)</span>
<p>
<input type="submit" value="Submit" name='submit'>
</form>
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$user_message = $_POST['message'];
$to = $your_email;
$subject="New form submission";
$from = $your_email;
$text = "A user $name has sent you this message:\n $user_message";
I think you just need to add a couple more lines:
$phone = $_POST["phone"];
$text = "A user $name has sent you this message:\n $user_message";
$text .= "Phone: " . $phone . "\n";
$text .= "Email: " . $visitor_email . "\n";

contact form submitting error

if anyone can just go through my code and find possible error, I've tried everything, but I just can't find mistake. My form validates just fine, but when it comes to submit and redirect to next page, it just reloads...
<?php
$your_email ='(i have removed e-mail)';
session_start();
$errors = '';
$name = '';
$visitor_email = '';
$user_message = '';
if(isset($_POST['submit']))
{
$name = $_POST['form-name'];
$visitor_email = $_POST['form-email'];
$subject_email = $_POST['form-subject'];
$user_message = $_POST['form-message'];
$user_id = $_POST['form-id'];
$telephone = $_POST['form-telephone'];
///------------Do Validations-------------
if(empty($name)||empty($visitor_email))
{
$errors .= "\n Morate popuniti polja ime i e-mail. ";
}
if(IsInjected($visitor_email))
{
$errors .= "\n Pogresno unet e-mail!";
}
if(empty($_SESSION['6_letters_code'] ) ||
strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
{
//Note: the captcha code is compared case insensitively.
//if you want case sensitive match, update the check above to
// strcmp()
$errors .= "\n Verifikacioni kod je pogresno unet!";
}
if(empty($errors))
{
//send the email
$to = $your_email;
$subject = "Nova poruka: $subject_email";
$from = $_POST['form-name'];
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$body = "Posetilac $name je poslao poruku sa web-sajta:\n".
"Ime: $name\n".
"Email: $visitor_email \n".
"Poruka: \n ".
"$user_message\n".
"Broj licne karte: $user_id\n".
"Broj telefona: $telephone\n".
"IP: $ip\n";
$headers = "From: $from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to, $subject, $body, $headers);
header('Location: slanje_uspesno.html');
}
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<link href="css/main.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script language="JavaScript" src="js/gen_validatorv31.js" type="text/javascript"></script>
</head>
<body>
<div id="header">
<div id="container_header">
<div id="logo"></div>
</div>
</div>
<div id="container_kontakt">
<div id="kontakt_email">
<div id="kontakt_middle">
<div id="forma">
<div class="errors_kontakt">
<?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?>
<div id='form_errorloc' class='err'></div>
</div>
<form id="form" method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<ul id="form_list">
<li><label>Vaše ime:</label><input type="text" id="form-name" name="form-name" value='<?php echo htmlentities($name) ?>'/></li>
<li><label>Vaš e-mail:</label><input type="text" id="form-email" name="form-email" value='<?php echo htmlentities($visitor_email) ?>'/></li>
<li><label>Naziv poruke:</label><input type="text" id="form-subject" name="form-subject" /></li>
<li><label>Broj telefona:</label><input type="text" id="form-telephone" name="form-telephone" maxlength="12" /></li>
<li><label>Broj lične karte:</label><input type="text" id="form-id" name="form-id" maxlength="6" /></li>
<li><label>Vaša poruka:</label><textarea name="form-message"><?php echo htmlentities($user_message) ?></textarea></li>
<li><label for="6_letters_code">Verifikacioni broj:</label><img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' > <input id="6_letters_code" class="captcha_code" maxlength="6" name="6_letters_code" type="text" ></li>
<li><label> </label><input type="submit" id="submit" value="POŠALJI" class="submit"></li>
</ul>
</form>
<script language="JavaScript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator = new Validator("form");
//remove the following two lines if you like error message box popups
frmvalidator.EnableOnPageErrorDisplaySingleBox();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("form-name","req","Unesite Vaše ime");
frmvalidator.addValidation("form-email","req","Unesite Vašu e-mail adresu");
frmvalidator.addValidation("form-email","email","Unesite validnu e-mail adresu");
frmvalidator.addValidation("form-id","req","Unesite Vaš broj lične karte");
frmvalidator.addValidation("form-telephone","req","Unesite Vaš broj telefona");
frmvalidator.addValidation("6_letters_code","req","Verifikacioni kod je pogresno unet");
</script>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
var img = document.images['captchaimg'];
img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
</div>
</div>
<div id="footer">
</div>
</body>
</html>
You are checking if $_POST['submit'] is ever submitted. Looking at your code, it is never submitted as your submit button doesn't have a name attribute:
<input type="submit" id="submit" value="POŠALJI" class="submit">
It needs to be:
<input type="submit" name="submit" id="submit" value="POŠALJI" class="submit">
There is your problem:
<input type="submit" id="submit" value="POŠALJI" class="submit">
There is no input with the name attribute submit.
Change it to:
<input type="submit" id="submit" name="submit" value="POŠALJI" class="submit">

Categories