php send a file attachment inbuild script [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to send email with attachment using PHP?
hello iam new to php please let me know is any script or link for ( php script to send mail with file multiple attachments) and the html form also to how to connect this form or any inbuilt script so that i can upload to my server.
i already try in many ways by coping the codes and pasting them and changing there path but still it get many errors so please let me know if there inbuilt script easily upload to my server
<?php
if($_GET['name']== '' || $_GET['email']=='' || $_GET['email']=='' || $_GET['Message']=='' )
{
?>
<form action="check3.php" method="get" name="frmPhone">
<fieldset>
<legend style="color:#000">Contact </legend>
<table width="100%">
<tr>
<td width="29%">
<label for="name" <?php if(isset($_GET['Submit']) && $_GET['name']=='') echo "style='color:red'"; ?>>Name* </label> </td> <td width="71%">
<input id="name" name="name" type="text" style="width:50%" value=" <?php echo $_GET['name']; ?>"/> </td> </tr> <tr> <td>
<label for=" email" <?php if(isset($_GET['Submit']) && $_GET['email']=='') echo "style='color:red'"; ?>>Email* </label> </td> <td>
<input id="email" name="email" type="text" style="width:50%" value=" <?php echo $_GET['email']; ?>"/> </td> </tr>
</table>
</fieldset>
<fieldset>
<legend style="color:#000">Inquiry </legend>
<table width="100%">
<tr> <td width="41%" valign="top">
<label for="Message" <?php if(isset($_GET['Submit']) && $_GET['Message']=='') echo "style='color:red'"; ?>>Message*</label> </td> <td width="59%"> <textarea name="Message" rows="5" style="width:90%" id="Message"> <?php echo $_GET['Message']; ?> </textarea> </td><div align="center">Photo
<input name="photo" type="file" size="35" />
</div></td>
</tr>
<tr>
<input name="Submit" type="submit" value="Submit" />
</form> </td> </td>
</form>
</tr>
<?php
}
else
{
$to = 'abhi326#gmail.com';
$subject = 'Customer Information';
$message = '
Name: '.$_GET['name'].'
Email Address: '.$_GET['email'].'
Message: '.$_GET['Message'];
$headers = 'From:'.$_GET['email'];
mail($to, $subject, $message, $headers);
$connection=mysql_connect("db2173.perfora.net", "dbo311409166", "malani2002") or die(mysql_error());
$query = mysql_query("INSERT INTO `feedback` ( `name` , `email` , `Message` , `photo` ) VALUES ('".$_GET['name']."', '".$_GET['email']."', '".$_GET['Message']."')");
define ("MAX_SIZE","75");
if(isset($_FILES['photo']['name']) && $_FILES['photo']['name']<>"") {
$typ = $_FILES['photo']['type'];
if($typ == "image/g if" || $typ == "image/png" || $typ == "image/jpeg" || $typ == "image/pg if" || $typ == "image/ppng" || $typ =="image/JPEG")
{
$uploaddir = "contacts/";
$uploadimages = $uploaddir.basename($_FILES['photo']['name']);
if(move_uploaded_file($_FILES['photo']['tmp_name'], $uploadimages)) {
echo "File successfully copied";
$sql="INSERT INTO contacts (Photo, Beschrijving)
VALUES ('$uploadimages',
'$_POST[images]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
mysql_close($con);
}
}
else {echo "Copy unsuccessful"; }
}
else {
echo "Incorrect file type";
}
}
else {
echo "No file selected";
}
echo "Thank you! ";
}
?>
thanks and regards
abhi

The script you're lookingfor is phpMailer.
This script can be downloaded and is easily added to your PHP programs. It makes sending emails from PHP extremely easy, including adding attachments.
Hope that helps.

Related

Why is my png files updated into database as pdf and how to correct it?

I know, my question must be really basic, but I decided to ask since when I go through this site, I couldn't find the solution from the previous similar problems.
Here it is, I have a system where a user have to upload their resume and their profile picture into the system in order to create their account. The registration is successful, however, their profile picture is not displayed and when I check in my database, the name of their resume and their profile picture is the same although when I checked inside the uploaded files respectively, the resume and picture are inside their respective folders.
Here what my DB looks like:
and here is my adduser.php
<?php
//To Handle Session Variables on This Page
session_start();
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("db.php");
//If user Actually clicked register button
if(isset($_POST)) {
$user_name = mysqli_real_escape_string($conn, $_POST['user_name']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$nationality = mysqli_real_escape_string($conn, $_POST['nationality']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$race = mysqli_real_escape_string($conn, $_POST['race']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$contactno = mysqli_real_escape_string($conn, $_POST['contactno']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$highest_qualification = mysqli_real_escape_string($conn, $_POST['highest_qualification']);
$university = mysqli_real_escape_string($conn, $_POST['university']);
$major = mysqli_real_escape_string($conn, $_POST['major']);
$current_position = mysqli_real_escape_string($conn, $_POST['current_position']);
$position_applied = mysqli_real_escape_string($conn, $_POST['position_applied']);
$current_monthly_salary = mysqli_real_escape_string($conn, $_POST['current_monthly_salary']);
$expected_monthly_salary = mysqli_real_escape_string($conn, $_POST['expected_monthly_salary']);
$prefered_working_location = mysqli_real_escape_string($conn, $_POST['prefered_working_location']);
$avaibility = mysqli_real_escape_string($conn, $_POST['avaibility']);
$malay = mysqli_real_escape_string($conn, $_POST['malay']);
$english = mysqli_real_escape_string($conn, $_POST['english']);
$mandarin = mysqli_real_escape_string($conn, $_POST['mandarin']);
$other = mysqli_real_escape_string($conn, $_POST['other']);
$aboutme = mysqli_real_escape_string($conn, $_POST['aboutme']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$password = base64_encode(strrev(md5($password)));
//sql query to check if email already exists or not
$sql = "SELECT email FROM users WHERE email='$email'";
$result = $conn->query($sql);
//if email not found then we can insert new data
if($result->num_rows == 0) {
//This variable is used to catch errors doing upload process. False means there is some error and we need to notify that user.
$uploadOk = true;
// Code for image
$folder_dir = "uploads/logo/";
$base = basename($_FILES['image']['name']);
$imageFileType = pathinfo($base, PATHINFO_EXTENSION);
$file = uniqid() . "." . $imageFileType;
$filename = $folder_dir .$file;
if(file_exists($_FILES['image']['tmp_name'])) {
if($imageFileType == "jpg" || $imageFileType == "png") {
if($_FILES['image']['size'] < 500000) { // File size is less than 5MB
move_uploaded_file($_FILES["image"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
$_SESSION['uploadError'] = "Wrong Format. Only jpg & png Allowed";
$uploadOk = false;
}
} else {
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
// Code for resume
$folder_dir = "uploads/resume/";
$base = basename($_FILES['resume']['name']);
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
$file1 = uniqid() . "." . $resumeFileType;
$filename = $folder_dir .$file1;
if(file_exists($_FILES['resume']['tmp_name'])) {
if($resumeFileType == "pdf"|| $resumeFileType == "doc") {
if($_FILES['resume']['size'] < 500000) {
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
$_SESSION['uploadError'] = "Wrong Format. Only PDF Allowed";
$uploadOk = false;
}
} else {
//File not copied to temp location error.
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
//If there is any error then redirect back.
if($uploadOk == false) {
header("Location: register-candidates.php");
exit();
}
$hash = md5(uniqid());
//sql new registration insert query
$sql="INSERT INTO users (user_name, ic_no, gender, email, password, address, nationality, contactno, highest_qualification, university, major, current_position,
position_applied, current_monthly_salary, expected_monthly_salary, prefered_working_location, avaibility, malay, english, mandarin, other, logo, resume, hash, aboutme) VALUES
('$user_name', '$ic_no', '$gender', '$email', '$password', '$address', '$nationality', '$contactno', '$highest_qualification', '$university', '$major', '$current_position',
'$position_applied', '$current_monthly_salary', '$expected_monthly_salary', '$prefered_working_location', '$avaibility', '$malay', '$english', '$mandarin',
'$other', '$file', '$file1', '$hash', '$aboutme')";
if($conn->query($sql)===TRUE) {
// Send Email
// $to = $email;
// $subject = "Job Portal - Confirm Your Email Address";
// $message = '
// <html>
// <head>
// <title>Confirm Your Email</title>
// <body>
// <p>Click Link To Confirm</p>
// Verify Email
// </body>
// </html>
// ';
// $headers[] = 'MIME-VERSION: 1.0';
// $headers[] = 'Content-type: text/html; charset=iso-8859-1';
// $headers[] = 'To: '.$to;
// $headers[] = 'From: hello#yourdomain.com';
// //you add more headers like Cc, Bcc;
// $result = mail($to, $subject, $message, implode("\r\n", $headers)); // \r\n will return new line.
// if($result === TRUE) {
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
// $_SESSION['registerCompleted'] = true;
// header("Location: login.php");
// exit();
// }
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
$_SESSION['registerCompleted'] = true;
header("Location: login-candidates.php");
exit();
} else {
//If data failed to insert then show that error. Note: This condition should not come unless we as a developer make mistake or someone tries to hack their way in and mess up :D
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
//if email found in database then show email already exists error.
$_SESSION['registerError'] = true;
header("Location: candidate-register.php");
exit();
}
$conn->close();
} else {
//redirect them back to register page if they didn't click register button
header("Location: candidate-register.php");
exit();
}
?>
and also to let you guys see where this php goes, it's in register-candidates.php
<form method="post" id="registerCandidates" action="adduser.php" enctype="multipart/form-data">
<table border="0" cellpadding="5" cellspacing="0">
<p>
<tr> <td colspan="2">
<label for="user_name" type="text" id="user_name" placeholder="user_name" style="color:black;"><b>Full Name *</b></label><br />
<input name="user_name" class="form-control" type="text" maxlength="50" style="width: 560px" required />
</td> </tr>
</p>
<p>
<tr> <td>
<label for="ic_no" type="text" id="ic_no" placeholder="ic_no" style="color:black;"><b>NRIC *</b></label><br />
<input name="ic_no" class="form-control" type="text" maxlength="50" style="width: 235px" required />
</td>
<td>
<label for="nationality" type="text" id="nationality" placeholder="Nationality" style="color:black;"><b>Nationality</b></label><br />
<input name="nationality" class="form-control" type="text" id="nationality" maxlength="50" style="width: 235px" />
</td>
</tr>
</p>
<p>
<tr> <td>
<label for="gender" type="text" id="gender" placeholder="Gender" style="color:black;"><b>Gender</b></label><br />
<select name = "gender" class ="form-control" type ="text" id="gender" maxlength="50" style="width: 235px"> <br>
<option value="">-- select one --</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</td>
<td>
<label for="race" style="color:black;"><b>Race</b></label><br/>
<select name = "race" class ="form-control" type ="text" id="race" maxlength="50" style="width: 235px"> <br>
<option value="">-- select one --</option>
<option value="Malay">Malay</option>
<option value="Chinese">Chinese</option>
<option value="Indian">Indian</option>
<option value="Others">Others</option>
</select>
</td> </tr>
</p>
<p>
<tr> <td>
<label for="contactno" type="text" id="contactno" placeholder="contactno" style="color:black;"><b>Contact Number *</b></label><br />
<input name="contactno" class="form-control" type="text" maxlength="11" style="width: 235px" />
</td>
<td>
<label for="email" type="text" id="email" placeholder="Email" style="color:black;"><b>Email</b></label><br />
<input name="email" class="form-control" type="text" maxlength="50" style="width: 235px" />
</td> </tr>
</p>
<?php
//If User already registered with this email then show error message.
if(isset($_SESSION['registerError'])) {
?>
<div class="form-group">
<label style="color: red;">Email Already Exists! Choose A Different Email!</label>
</div>
<?php
unset($_SESSION['registerError']); }
?>
<?php if(isset($_SESSION['uploadError'])) { ?>
<div class="form-group">
<label style="color: red;"><?php echo $_SESSION['uploadError']; ?></label>
</div>
<?php unset($_SESSION['uploadError']); } ?>
<p>
<tr> <td colspan="2">
<label for="address" type="text" id="address" placeholder="Address" style="color:black;"><b>Current Address</b></label><br />
<textarea class="form-control" rows="4" id="address" name="address" maxlength="100" style="width: 560px"></textarea>
</td> </tr>
</p>
<p>
<tr>
<td colspan="2">
<label for="highest_qualification" type="highest_qualifiation" id="highest_qualification" placeholder="Highest Qualification" style="color:black;"><b>Highest Qualification</b></label><br/>
<select name = "highest_qualification" class="form-control " type="text" id="highest_qualification" maxlength="50" style="width: 235px"> <br>
<option value="">-- select one --</option>
<option value="PhD">PhD</option>
<option value="Master">Master/Postgraduate</option>
<option value="Bachelor">Bachelor/Undergraduate</option>
<option value="Diploma">Diploma</option>
</select>
</td></tr>
</p>
<p>
<tr><td colspan="2">
<label for="university" type="text" id="university" placeholder="University" style="color:black;"><b>University</b></label><br/>
<input name="university" class="form-control" type="text" id="university" maxlength="50" style="width: 235px" /
<tr> <td colspan="2">
<label for="major" type="text" id="major" placeholder="Major" style="color:black;"><b>Major *</b></label><br />
<input name="major" type="text" class="form-control" maxlength="100" style="width: 560px" />
</td> </tr>
<tr> <td colspan="2">
<label for="current_position" type="text" id="current_position" placeholder="Current Position" style="color:black;"><b>Current Position *</b></label><br />
<input name="current_position" type="text" class="form-control" maxlength="100" style="width: 560px" />
</td> </tr>
<tr> <td colspan="2">
<label for="position_applied" type="text" id="position_applied" placeholder="Position Applied" style="color:black;"><b>Position Applied*</b></label><br />
<input name="position_applied" type="text" class="form-control" maxlength="100" style="width: 560px" />
</td> </tr>
<tr> <td>
<label for="current_monthly_salary" type="text" id="current_monthly_salary" placeholder="Current Monthly Salary" style="color:black;"><b>Current Monthly Salary</b></label><br />
<input name="current_monthly_salary" type="text" class="form-control" maxlength="50" style="width: 235px" />
</td>
<td>
<label for="expected_monthly_salary" type="text" id="expected_monthly_salary" placeholder="Expected Monthly Salary" style="color:black;"><b>Expected Monthly Salary</b></label><br />
<input name="expected_monthly_salary" type="text" class="form-control" maxlength="50" style="width: 235px" />
</td> </tr>
<tr> <td colspan="2">
<label for="preferred_working_location" type="text" id="preferred_working_location" placeholder="Preferred working Location" style="color:black;"><b>Preferred working location?</b></label><br />
<input name="preferred_working_location" type="text" class="form-control" maxlength="100" style="width: 560px" />
</td> </tr>
<tr> <td colspan="2">
<label for="availability" type="availability" id="availability" placeholder="availability" style="color:black;"><b>Availability</b></label><br/>
<select name = "availability" class="form-control " type="text" id="availability" maxlength="50" style="width: 235px"> <br>
<option value="">-- select one --</option>
<option value="Immediately">Immediately</option>
<option value="One Month">One Month</option>
<option value="Two Month">Two Month</option>
<option value="Three Month">Three Month</option>
</select>
</td> </tr>
<tr><td colspan="2">
<label for="language" type="text" id="language" placeholder="Language Proficiency" style="color:black;"><b>Language Proficiency</b></label><br />
<p>Proficiency level 0-poor; 10-excellent</p>
<table border="2" bordercolor="gray" align="center">
<tr>
<td>
<label for="malay" type="text" id="malay" placeholder="Malay" style="color:black; width:200px"><b>Malay</b></label><br />
</td>
<td>
<input name="malay" type="text" class="form-control" maxlength="100" style="width: 200px" />
</td>
</tr>
<tr>
<td>
<label for="english" type="text" id="english" placeholder="English" style="color:black; width:200px"><b>English</b></label><br />
</td>
<td>
<input name="english" type="text" class="form-control" maxlength="100" style="width: 200px" />
</td>
</tr>
<tr>
<td>
<label for="mandarin" type="text" id="mandarin" placeholder="Mandarin" style="color:black; width:200px"><b>Mandarin</b></label><br />
</td>
<td>
<input name="mandarin" type="text" class="form-control" maxlength="100" style="width: 200px" />
</td>
</tr>
<tr>
<td>
<label for="other" type="text" id="other" placeholder="Other" style="color:black; width:200px"><b>Others</b></label><br />
</td>
<td>
<input name="other" type="text" class="form-control" maxlength="100" style="width: 200px" />
</td>
</tr>
</table>
<!--about me -->
<tr> <td colspan="2">
<label for="aboutme" type="text" id="aboutme" style="color:black;"><b>About Me</b></label><br />
<p>Summarize your employement history (Not more than 100 words)</p>
<textarea class="form-control" rows="6" id="aboutme" name="aboutme" maxlength="400" style="width: 560px" placeholder="Example: Early 30s. Master's Degree in Business Administration and Degree in Accounting.
Total 19 years of working experience in Sales & Business Development in various industries. Good Exposure in Regional Sales & Business Development and etc. Is willing to travel locally and overseas"></textarea>
</td> </tr>
</p>
<tr>
<td>
<label style="color:black;">Latest passport photo</label>
<input type="file" name="image" class="form-control" id="profile-img" required>
<img src="" id="profile-img-tag" width="200px" />
</td>
</tr>
<tr>
<td>
<label style="color:black;">File format PDF and doc only!</label>
<input type="file" name="resume" class="form-control" required>
</td>
</tr>
</table>
<br/>
<table>
<tr>
<td>
<input class="form-control" type="password" id="password" name="password" style= "width:235px"placeholder="Password *" required>
</td>
<br/>
<td>
<input class="form-control" type="password" id="cpassword" name="cpassword" style= "width:235px" placeholder="Confirm Password *" required>
</td>
</tr>
</table>
<br/>
<br/>
<table>
<td class="form-group checkbox">
<label style="color:black;"><input type="checkbox"> I hereby declare all informations are true and in current situation. Any discrepancies will result in penalty or termination</label>
</td>
</table>
<table>
<td class="form-group">
<button class="btn btn-flat btn-success">Register</button>
</td>
</table>
</form>
so, this is basically what I have and I don't know what else should I do so that the image stored is in png and I can call the image properly. Thank you in advance for all the kind helps
So, after going through my source code before, I now realizes my mistake was that I didn't differentiate the files for my image and resume, and since resume was placed last, the code read to save my image as pdf as well. Here is the source code that I have already repaired.
<?php
//To Handle Session Variables on This Page
session_start();
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("db.php");
//If user Actually clicked register button
if(isset($_POST)) {
$user_name = mysqli_real_escape_string($conn, $_POST['user_name']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$nationality = mysqli_real_escape_string($conn, $_POST['nationality']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$race = mysqli_real_escape_string($conn, $_POST['race']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$contactno = mysqli_real_escape_string($conn, $_POST['contactno']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$highest_qualification = mysqli_real_escape_string($conn, $_POST['highest_qualification']);
$university = mysqli_real_escape_string($conn, $_POST['university']);
$major = mysqli_real_escape_string($conn, $_POST['major']);
$current_position = mysqli_real_escape_string($conn, $_POST['current_position']);
$position_applied = mysqli_real_escape_string($conn, $_POST['position_applied']);
$current_monthly_salary = mysqli_real_escape_string($conn, $_POST['current_monthly_salary']);
$expected_monthly_salary = mysqli_real_escape_string($conn, $_POST['expected_monthly_salary']);
$prefered_working_location = mysqli_real_escape_string($conn, $_POST['prefered_working_location']);
$avaibility = mysqli_real_escape_string($conn, $_POST['avaibility']);
$malay = mysqli_real_escape_string($conn, $_POST['malay']);
$english = mysqli_real_escape_string($conn, $_POST['english']);
$mandarin = mysqli_real_escape_string($conn, $_POST['mandarin']);
$other = mysqli_real_escape_string($conn, $_POST['other']);
$aboutme = mysqli_real_escape_string($conn, $_POST['aboutme']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$password = base64_encode(strrev(md5($password)));
//sql query to check if email already exists or not
$sql = "SELECT email FROM users WHERE email='$email'";
$result = $conn->query($sql);
//if email not found then we can insert new data
if($result->num_rows == 0) {
//This variable is used to catch errors doing upload process. False means there is some error and we need to notify that user.
$uploadOk = true;
// Code for image
if(is_uploaded_file ( $_FILES['image']['tmp_name'] )) {
$folder_dir = "../uploads/logo/";
$base = basename($_FILES['image']['name']);
$imageFileType = pathinfo($base, PATHINFO_EXTENSION);
$file = uniqid() . "." . $imageFileType;
$filename = $folder_dir .$file;
if(file_exists($_FILES['image']['tmp_name'])) {
if($imageFileType == "jpg" || $imageFileType == "png") {
if($_FILES['image']['size'] < 500000) { // File size is less than 5MB
//If all above condition are met then copy file from server temp location to uploads folder.
move_uploaded_file($_FILES["image"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
header("Location: edit-company.php");
exit();
}
} else {
$_SESSION['uploadError'] = "Wrong Format. Only jpg & png Allowed";
header("Location: edit-company.php");
exit();
}
}
} else {
$uploadOk = false;
}
// Code for resume
$folder_dir = "uploads/resume/";
$base = basename($_FILES['resume']['name']);
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
$file1 = uniqid() . "." . $resumeFileType;
$filename = $folder_dir .$file1;
if(file_exists($_FILES['resume']['tmp_name'])) {
if($resumeFileType == "pdf"|| $resumeFileType == "doc") {
if($_FILES['resume']['size'] < 500000) {
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
$_SESSION['uploadError'] = "Wrong Format. Only PDF Allowed";
$uploadOk = false;
}
} else {
//File not copied to temp location error.
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
//If there is any error then redirect back.
if($uploadOk == false) {
header("Location: register-candidates.php");
exit();
}
$hash = md5(uniqid());
//sql new registration insert query
$sql="INSERT INTO users (user_name, ic_no, gender, email, password, address, nationality, contactno, highest_qualification, university, major, current_position,
position_applied, current_monthly_salary, expected_monthly_salary, prefered_working_location, avaibility, malay, english, mandarin, other, logo, resume, hash, aboutme) VALUES
('$user_name', '$ic_no', '$gender', '$email', '$password', '$address', '$nationality', '$contactno', '$highest_qualification', '$university', '$major', '$current_position',
'$position_applied', '$current_monthly_salary', '$expected_monthly_salary', '$prefered_working_location', '$avaibility', '$malay', '$english', '$mandarin',
'$other', '$file', '$file1', '$hash', '$aboutme')";
if($conn->query($sql)===TRUE) {
// Send Email
// $to = $email;
// $subject = "Job Portal - Confirm Your Email Address";
// $message = '
// <html>
// <head>
// <title>Confirm Your Email</title>
// <body>
// <p>Click Link To Confirm</p>
// Verify Email
// </body>
// </html>
// ';
// $headers[] = 'MIME-VERSION: 1.0';
// $headers[] = 'Content-type: text/html; charset=iso-8859-1';
// $headers[] = 'To: '.$to;
// $headers[] = 'From: hello#yourdomain.com';
// //you add more headers like Cc, Bcc;
// $result = mail($to, $subject, $message, implode("\r\n", $headers)); // \r\n will return new line.
// if($result === TRUE) {
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
// $_SESSION['registerCompleted'] = true;
// header("Location: login.php");
// exit();
// }
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
$_SESSION['registerCompleted'] = true;
header("Location: login-candidates.php");
exit();
} else {
//If data failed to insert then show that error. Note: This condition should not come unless we as a developer make mistake or someone tries to hack their way in and mess up :D
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
//if email found in database then show email already exists error.
$_SESSION['registerError'] = true;
header("Location: candidate-register.php");
exit();
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to register page if they didn't click register button
header("Location: candidate-register.php");
exit();
}
?>
Hope this will be useful for other programmers in the future!

Resolve conflict between two simple forms on the same web page

On a membership site that I am developing, once the user has logged in, on his profile page there are two simple forms.
The first is diplayed only if the user has his "district" field NULL in the database. If the "district" field contains any information, the first form is replaced by a table displaying data from that district. The purpose of the form is for the user to select his district from a list, and update his account so he can read local information from his district. After he hits submit, the "district" field in the databsase is updated and then he never sees this form again.
The second one is a basic contact form, thru which the user can easily send an email message to the support team if he needs any help. Once the message has been sent, instead of the form, a success message is displayed until the refresh of the page, when the text field comes back to normal and the user can send another message.
I have tested them and they both work fine separately, but the error I am encountering is that when a user with NULL in his "district" field logs in, or whenever his page is refreshed, the second form automatically sends a blank email to the support team, and is allways showing the success message instead of the text input for the message to be written in. I have setup an error when the second form is submitted empty, but despite this, while the first form is showing, with every refresh, a new blank email is being sent...
After the user has submitted the first form an updated his "district", the second form returns to normal and works just fine... I know that there is a conflict, or I forgot to setup some conditions in the code below. Please be kind, take a look and tell me where do you think the error might be. Any help is welcomed.
<? if($row_user['district'] == NULL ):
if(!isset($_POST['submit2']))
{
foreach($row_user as $field => $value)
{
$_POST[$field] = $value;
}
}
$error2 = 0;
if(isset($_POST['submit2'])){
if(isset($_POST['distr']) && ($_POST['distr']==""))
{
$error2 = 1;
$msg_distr="<br /><span class='error'>Select your district</span>";
}
if($error2 == 0)
{
$update = 'UPDATE users SET ';
if(isset($_POST['distr'])) $update .= 'district = '.GetSQLValueString($_POST['distr'], 'text').', ';
$update = substr_replace($update,"",-2);
$update .= 'WHERE id_user = '.$id_user;
mysql_query($update, $conn) or die(mysql_error());
}
}
?>
The HTML code for the first form is
<form action="" method="post" enctype="multipart/form-data" >
<table width="465px" border="0" cellpadding="5" cellspacing="5">
<tr>
<td width="160" valign="middle" align="left">
<span class="style20"><b>Choose District</b> *</span>
</td>
<td valign="top" align="left">
<select name="distr" onChange="sel_distr(this.value)" class="select" >
<option value="">Choose</option>
<option value="District1" <? if($_POST['distr']=="District1") echo "'selected'"?>>District1</option>
<option value="District2" <? if($_POST['distr']=="District2") echo "'selected'"?>>District2</option>
<option value="District3" <? if($_POST['distr']=="District3") echo "'selected'"?>>District3</option>
<option value="District4" <? if($_POST['distr']=="District4") echo "'selected'"?>>District4</option>
<option value="District5" <? if($_POST['distr']=="District5") echo "'selected'"?>>District5</option>
</select>
<?=$msg_distr?>
</td>
</tr>
<tr>
<td >
<input type="submit" name="submit2" class="submit" value="Insert" />
</td>
</tr>
</table>
</form>
<?endif; ?>
The other form is for sending email messages from this page, just by inserting the message and sending it. the user will not need to insert his name or email.
<?php
$error_message=0;
if ($_POST["email"]<>'') {
if(isset($_POST['comment']) && ($_POST['comment']=="")){
$error_message=1;
$er_msg="<br /><span class='error'>You can't send a blank message</span>";
}
if($error_message == 0){
$ToEmail = 'mail#domain';
$EmailSubject = 'New message from '.$row_user['name'].'';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = "<b>Name:</b> ".$_POST["name"]."<br/>";
$MESSAGE_BODY .= "<b>Email:</b> ".$_POST["email"]."<br/><br/>";
$MESSAGE_BODY .= " ".nl2br($_POST["comment"])."<br/>";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>
<div class="success" style="height:60px;">
<b><?=$row_user['name']?>, Your message was sent!</b> <br/>
A member of our team will contact you soon.
</div>
<?php
}
if($error_message == 1){ ?>
<form action="me.html" method="post">
<input name="name" type="hidden" value="<?=$row_user['name']?>" id="name" size="32">
<input name="email" type="hidden" value="<?=$row_user['email']?>" id="email" size="32"> <br/>
<textarea name="comment" cols="45" rows="6" id="comment" class="input" style="width:90%"></textarea><br/>
<input class="submit" type="submit" name="Submit" value="Send">
</form>
<?=$er_msg?>
<?
}
} else {
?>
<form action="me.html" method="post">
<input name="name" type="hidden" value="<?=$row_user['name']?>" id="name" size="32">
<input name="email" type="hidden" value="<?=$row_user['email']?>" id="email" size="32"> <br/>
<textarea name="comment" cols="45" rows="6" id="comment" class="input" style="width:90%"></textarea><br/>
<input class="submit" type="submit" name="Submit" value="Send">
</form>
<?php
};
?>
Alright, I think this is a minor mistake and you are getting confused because of the too many error counter flags.
Try changing this:
if($error_message == 0){
to:
if($error_message == 0 && $row_user['district'] != NULL){

php email validation (filter_validate_email) Not Working

I know there are numerous questions about this however I just can not seem to pick the error with my coding. I know it is something simple but I can not see it.
I have to create a form which when it is submitted the data will be inputted into MySQL database however the data needs to be validated first. I have 2 issues with this, the first being my email validation is not working using: (filter_var($email, filter_validate_email))
The problem is that when I submit the form it returns true regardless of if the email is valid or not.
If I put (!filter_var($email, filter_validate_email)) it returns false regardless of the input.
The second problem is that when loading the page it initially adds a blank entry into the SQL database and it adds entries that aren’t valid. i.e. if I don’t enter a name when the form is submitted the validation runs and I get the error message “name is required” but it still creates an entry in the table with a blank name.
I am using PHP version 5.3.27
This is for my tafe course i am doing however they are on holidays at the moment so any help would be greatly appreciated.
Coding from file 1:
<body>
<?php
// define variables and set to empty values
$nameErr;
$Name = $Address = $Phone = $Mobile = $Email="example#example.com";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["Name"]))
{$nameErr = "Name is required"; }
else {$Name = test_input($_POST["Name"]);}
if (empty($_POST["Address"]))
{$Address = "";}
else
{$Address = test_input($_POST["Address"]);}
if (empty($_POST["Phone"]))
{$Phone = "";}
else
{$Phone = test_input($_POST["Phone"]);}
if (empty($_POST["Mobile"]))
{$Mobile = "";}
else
{$Mobile = test_input($_POST["Mobile"]);}
if(filter_var($Email, FILTER_VALIDATE_EMAIL)){
echo"Valid Email";
}
else{
echo "Not a Valid Email";
}
echo phpinfo();
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form name="addcontact" method="post" action= "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>", "add-contact.php">
<table border="1" cellpadding="2">
<caption> Add New Caption </caption>
<tr>
<td><label for="Name">Name</label></td>
<td><input type="text" name="Name" size="30" maxlenght="50" tabindex="1"/> <span class="error">*<?php echo $nameErr;?></span>
</td>
</tr>
<tr>
<td><label for="Address">Address</label></td>
<td><textarea name="Address" cols="45" rows="5" tabindex="2"></textarea></td>
</tr>
<tr>
<td><label for="Phone">Phone</label></td>
<td><input type="text" name="Phone" size="20" maxlenght="20" tabindex="3" /> </td>
</tr>
<tr>
<td><label for="Mobile">Mobile</label></td>
<td><input type="text" name="Mobile" size="20" maxlenght="20" tabindex="4" /> </td>
</tr>
<tr>
<td><label for="Email">Email</label></td>
<td><input type="text" name="Email" size="30" maxlenght="50" tabindex="5" /></td>
</tr>
<tr>
<td colspan"2" align="center"><input type="Submit" name="Submit" value="Submit" tabindex="6"/>
</td>
</tr>
</table>
</form>
<?php
include("add-contact.php");
?>
</body>
</html>`
And coding from file 2:
<body>
<?php
$Name = $_POST["Name"];
$Address = $_POST["Address"];
$Phone = $_POST["Phone"];
$Mobile = $_POST["Mobile"];
$Email = $_POST["Email"];
$dbc = mysql_connect("localhost:3306", "root", "webbm01");
if (!$dbc)
die ('Could not connect: ' .mysql_error());
$db_selected = mysql_select_db("tafe", $dbc );
if (!$db_selected)
die ('Could not connect: ' . mysql_error());
$qry
= "INSERT INTO contacts (Name, Address, Phone, Mobile, Email) VALUES ('" . addslashes($Name) . "', '" . addslashes($Address) . "', '" . addslashes($Phone) . "', '" . addslashes($Mobile). "', '" . addslashes($Email) . "')";
$rst = mysql_query($qry, $dbc);
if ($rst)
{
echo "<b><font color='green'>The contact has been added.</font></b>";
}
else
{
echo "<b><font color='red'>Error: ". mysql_error($dbc) . ". The contact could not be added.</font></b>";
}
mysql_free_result($rst);
?>
</body>
</html>
check this code for email validation etc :
<body> <?php
// define variables and set to empty values
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {$nameErr = "Name is required"; }else {$Name = htmlspecialchars($_POST["Name"]);}
if (empty($_POST["Address"])) {$Address = "";}else{$Address = htmlspecialchars($_POST["Address"]);}
if (empty($_POST["Phone"])) {$Phone = "";}else {$Phone = htmlspecialchars($_POST["Phone"]);}
if (empty($_POST["Mobile"])) {$Mobile = "";}else {$Mobile = htmlspecialchars($_POST["Mobile"]);}
if(filter_var($_POST['Email'], FILTER_VALIDATE_EMAIL)){ echo"Valid Email"; }else{ echo "Not a Valid Email"; }
}
?>
<form name="addcontact" method="post" action= "<?php echo $_SERVER["PHP_SELF"];?>">
<table border="1" cellpadding="2"> <caption> Add New Caption </caption> <tr> <td><label for="Name">Name</label></td> <td><input type="text" name="Name" size="30" maxlenght="50" tabindex="1"/> <span class="error">*<?php echo $nameErr;?></span> </td> </tr>
<tr> <td><label for="Address">Address</label></td> <td><textarea name="Address" cols="45" rows="5" tabindex="2"></textarea></td> </tr>
<tr> <td><label for="Phone">Phone</label></td> <td><input type="text" name="Phone" size="20" maxlenght="20" tabindex="3" /> </td> </tr>
<tr> <td><label for="Mobile">Mobile</label></td> <td><input type="text" name="Mobile" size="20" maxlenght="20" tabindex="4" /> </td> </tr> <tr> <td><label for="Email">Email</label></td> <td><input type="text" name="Email" size="30" maxlenght="50" tabindex="5" /></td> </tr> <tr> <td colspan"2" align="center"><input type="Submit" name="Submit" value="Submit" tabindex="6"/> </td> </tr> </table> </form>
</body> </html>`
The validation should happen in the file:
'add-contact.php'
Since this is what the from action is calling on submit.
The initial validators are meaningless since the $_POST array is not initialized.
The reason for the empty SQL insert statement is because you decide to do:
include("add-contact.php");
In the first file and it is running without valid $_POST initialization on each load of the page.
Remove the line include("add-contact.php");
This will stop the blank insertion in the database.
Also remove the action
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
Just try action="add-contact.php".
Email validation is working fine for me.

Email Validator Problems- Putting it all together

I'm very new to PHP coding.
I've done tons of research to try and help me. As you can imagine I've gotten tons of material for help. The problem is when I'm trying to put it all together.
Specifically here is my problem. I've come across:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "e-Mail is Valid";
} else {
echo "Invalid e-Mail";
}
But I have no idea how to implement it. As it stands now the validator checks the fields before the user has time to imput them..... I'm desperate
I'm sure the solution is really simple, but I've spent hours on this and am really desperate for this problem to be solved already.
Here's a link to the page
Here is the code for the page:
<!DOCTYPE html>
<head>
<meta charset='utf-8'>
<title>AWalsh Photography - Contact Me</title>
<link href="style/main_page.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="email_container">
<h1 class="email_head"> Contact Andrew walsh Photography</h1>
<form id="email_form" name="email_form" method="post">
<table>
<tr>
<td><label for="fname">First Name:</label>
</td>
<td><input type="text" name="fname_input" id="fname_input" /><br>
</td>
</tr>
<tr>
<td><label for="lname">Last Name:</label>
</td>
<td><input type="text" name="lname_input" id="lname_input" /><br>
</td>
</tr>
<tr>
<td><label for="email_input">Your Email:</label>
</td>
<td><input type="text" name="email_input" id="email_input" /><br>
</td>
</tr><tr>
<td><label for="email_conf">Re-enter Email:</label>
</td>
<td><input type="text" name="email_conf" id="email_conf" /><br>
</td>
</tr><tr>
<td>
<label for="message_input">Message </label>
</td><td>
<textarea rows="8" cols="45" id="message_input" name="message_input"></textarea>
</td></tr><tr><td></td>
<td>
<input id="submit"type="submit" value="submit" name="submit"/>
</td></tr>
</table>
</form>
<?php
if($_POST['email_imput'] == $_POST['email_conf']){
//stuff to do on success
echo '<h1>Success!!</h1>';
} else {
//stuff to do on failure
echo '<h1>Sorry, The emails you entered do not match</h1>';
}
$email_imput = $_POST['email_imput'];
if (filter_var($email_imput, FILTER_VALIDATE_EMAIL)) {
echo $email_imput . ' is a valid email address.';
} else {
echo $email_imput . ' is not a valid email address.';
}
$message_imput = $_POST['message_imput'];
$msg = "Email address: $email_imput \n" . "Message: $message_imput";
$to = 'myemail#gmail.com ';
$subject = 'AWP_email';
if (filter_var($email_imput)){
mail($to, $subject, $msg, $email);
}
if (mail($to, $subject, $msg, $email)) {
echo("<p>Message successfully sent! Thanks for submitting your message. We will reply to you as soon as possible</p>");
} else {
echo("<h1>Sorry, There was an error in your imput. Please try again.</h1>");
}
?>
<span class="error"><?=$error;?></span>
<form method="post" action="">
<h1> There was an error with your post</h1>
</form>
</div>
</div>
</body>
</html>
Any input would be amazing. Thank you.
You could add a hidden field into the form and check it's value when it's time to send the email.
if (isset($_POST["some_hidden_field"])) {
// put form validation and sending email here
}
else {
// print the form
}
You should first check whether the page has been submitted or not. You might want to try if ($_SERVER['METHOD'] == 'POST') before making any validations

Undefined Index?

I'm working on a very simple, very easy contact form and when i did it on a separate page it worked perfectly, but when i added it to the current website it can't get the $_POST i don't know why. here are the codes
$to ="enter email here";
$name = $_POST["name"];
$email = $_POST["email"];
$header = "From " . $name;
$message = $_POST["message"];
$content = "From: ". $name ."<br /> Email: " . $email ."<br /> Message: " . $message;
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "illegal email";
}
else
{
if (!empty($name) && !empty($message)){
mail($to, $header, $content);
echo"sent <br />";
echo $content;
}else
{
if(empty($email))
{
echo "your email is empty";
}
elseif(empty($name))
{
echo "please enter your name";
}
elseif(empty($message)){
echo "can't send empty messages";
}
}
}
html
<form method="post" action="mail.php">
<table>
<tr>
<td>
Name:
</td>
<td>
<input type="text" name="name" />
</td>
</tr>
<tr>
<td>
Email:
</td>
<td>
<input type="text" name="email"/>
</td>
</tr>
<tr>
<td>
Subject:
</td>
<td>
<input type="text" name="subject"/>
</td>
</tr>
<tr>
<td>
Message: <br /><br/><br/>
</td>
<td>
<textarea style="resize:vertical;" name="message"></textarea>
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit"/>
</td>
</tr>
</table>
</form>
thanks in advance and sorry if its a repeat
Check that the PHP is actually executing by adding something like this to the top:
echo "Testing PHP...";
If you do not see that output after submitting a form, check that you are posting the form to the right file. For example, you might need to use:
<form method="post" action="/mail.php">
or
<form method="post" action="/php/mail.php">
...code depending on your website structure.
It's certainly not $_POST that's broken, so it must be something either server related or an error in your code.
Do you have any other PHP on the website your importing the form to? If so you need to make sure that it isn't affecting it in any way.
One more thing to check, it has been reported that a PHP update accidently changed the upload limit size from "8M" to "10MB". Have a scan through your php.ini file and make sure that their isn't any unwanted "MB" instead of "M" in your upload limit.
One final suggestion I can give if you still haven't found the cause after this, is try using:
<?php var_dump($_POST); ?>
which should reveal what's really there.

Categories