I am using contact.php for contact form. I added an attachment field for upload file/image, pdf, docx in contact form using . But i can not integrate php functions for file attachment. I am weak in php, but this is very important for me to add this in my contact form.
Please someone help me. My form code and php code are given below. Thanks in advance.
//** This is html markup
<form id="Frmgroupa" class="form-style" method="post" onsubmit="return validator4(this)" action="contact.php">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">Name of Candidate *</label>
<input type="text" id="name" class="form-control" name="name" placeholder="Name" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['name'] : '' ?>" placeholder="" required autofocus />
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_need">State</label>
<select id="State" class="form-control" name="State" placeholder="" required autofocus>
<option value="UTTAR PRADESH">UTTAR PRADESH</option>
</select>
</div>
</div>
<div class="col-md-6">
<p>Address Proof *</p>
<div class="custom-file mb-3">
<input type="file" class="custom-file-input" id="Address_Proof" name="filename" >
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
<div class="col-md-6">
<p>Identity Proof *</p>
<div class="custom-file mb-3">
<input type="file" class="custom-file-input" id="Identity_Proof" name="filename">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
</div>
<input type="submit" class="btn btn-warning btn-3d" value="SUBMIT" id="submit-button" />
<?php unset($_SESSION['cf_returndata']); ?>
</form>
//* This is the contact.php code
<?php
$myemail = "amit.joshi98#gmail.com";
$subject = "file Upload";
/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Enter your name");
$State = $_POST['State'];
/* If URL is not valid set $website to empty */
if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $website))
{
$website = 'http://google.com';
}
/* Let's prepare the message for the e-mail */
$message = "Hello!
Your contact form has been submitted by:
Name: $name
State: $State
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location: thank-you.html');
exit();
/* Functions we used */
function check_input($data, $problem = '')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
First you need to write the following phrase in the form tag
enctype="multipart/form-data"
Like this ...
<form action="process.php" method="post" enctype="multipart/form-data">
and then in process.php file check submit and save file in your path
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
for limit file Type
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
for last check error and set message for user
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
you can Check if file already exists or Check file size
But i suggest you write an uploader function for the file and use it wherever you want.
In this example, photo file types were used that you can change according to your needs
Related
I'm very new to any web development issues and I couldn't find a solution to this problem. I have a form for uploading files so I use the enctype="multipart/form-data". However, I was also trying to take the fields from the form and encode them in a JSON file and read those out in a table in my html on my webpage. With the default enctype, the JSON encoding works great but obviously the file upload functionality doesn't work and vice versa. I followed a lot of W3Schools tutorials but I'm still lost. Is it possible to use two enctypes or what is the work around to this problem? I'm only uploading my files to localhost, no databases used. I apologize if I give too much info here but my form html looks like:
<form class="modal-content animate" enctype="multipart/form-data" method="post">
<div class="imgcontainer">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
</div>
<div class="container">
<label for="artist"><b>Artist Name</b></label>
<input class="form-control" type="text" placeholder="Enter name of artist" name="artist" required>
<label for="song"><b>Song Name</b></label>
<input class="form-control" type="text" placeholder="Enter name of song." name="song" required>
<label for="instrument"><b>Instrument Type</b></label>
<input class="form-control" type="text" placeholder="Enter type of instrument for tab." name="instrument" required>
<label for="myfile"><b>Tablature</b></label>
<input class="form-control" type="file" placeholder="Select your file." name="myfile" id="myfile" required>
<input type="submit" name="submit" value="Upload Tab PDF" class="w3-hover-purple" style="color:black; background-color:#A9A9A9"></input>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
</div>
</form>
My php code is structured as such:
<?php
$message = '';
$error = '';
if(isset($_POST["submit"])) {
if(empty($_POST["artist"])) {
$error = "<label class='text-danger'>Enter artist</label>";
}
else if(empty($_POST["song"])) {
$error = "<label class='text-danger'>Enter song name</label>";
}
else if(empty($_POST["instrument"])) {
$error = "<label class='text-danger'>Enter instrument</label>";
}
else if(empty($_POST["myfile"])) {
$error = "<label class='text-danger'>Enter file to upload</label>";
}
else {
if(file_exists('tablature.json')) {
$current_data = file_get_contents('tablature.json');
$array_data = json_decode($current_data, true);
$extra = array(
'artist' => $_POST['artist'],
'song' => $_POST['song'],
'instrument' => $_POST['instrument'],
'myfile' => $_POST['myfile']
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('tablature.json', $final_data)) {
$message = "<label class='text-success'>File Appended Successfully.</label>";
}
else {
$error = 'JSON File does not exist';
}
}
}
$target_dir = "Tablature/";
$target_file = $target_dir . basename($_FILES["myfile"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
$error = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$error = "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $target_file)) {
$message = "The file has been uploaded.";
} else {
$error = "Sorry, there was an error uploading your file.";
}
}
}
?>
Finally, on my page I print out my JSON contents on my page like so:
<table style="width:100%">
<tr>
<th>Artist</th>
<td>Song Name</td>
<td>Instrument Type</td>
<td style="float:right; margin-right:100px;">File</td>
</tr>
<?php
$read_data = file_get_contents("tablature.json");
$read_data = json_decode($read_data, true);
print("Working<br>");
foreach($read_data as $row) {
print('<tr><th>'.$row["artist"].'</th><td>'.$row["song"].'</td><td>'.$row["instrument"].'</td><td style="float:right">'.$row["myfile"].'</td></tr>');
}
?>
</table><br>
Any help would be greatly appreciated. Thank you in advance.
I am on Ubuntu. I am trying to take user file upload of small images. I checked the $_FILES it's filled with data. I tried to debug the move command but it doesnot echo anything.
if ($_SERVER['REQUEST_METHOD'] == 'POST' ){
//Now handle everything
if(isset($_POST["submit"])) {
print_r($_FILES);
//Store the image
if(!empty($_FILES['uploaded_file']))
{
$path = "/neel/public/img/";
$path = $path.basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo 'Its working';
} else{
echo 'I am done!!!';
die();
}
}
createnewEvent($conn);
header('Location:/neel/index.php');
}
}
You can check if the file exists by checking its name.
if(!empty($_FILES['file']['name']))
Where file is the name of input field for file.
P. G above here is correct.
Instead of checking, if $_POST['submit']
You should check this:
if(isset($_FILES['uploaded_file']['name']))
Try this code it's a complete sign up form with PHP , Bootstrap
HTML
<div class="container">
<div class="row">
<br>
<h1 class="text-center">Create new account</h1>
<br>
<div class="col-lg-4 col-md-6 col-sm-12">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="name" placeholder="Your Name">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="username" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="password" placeholder="Password">
</div>
<div class="form-group text-center">
<div class='file-input'>
<input type='file' name="profile-img">
<span class='button label' data-js-label>Choose your profile image</span>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success form-control form-control-lg" name="signup" value="Signup">
</div>
</form>
</div>
</div>
</div>
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors;
if (empty($_POST['name'])) {
$errors[] = "Name field is empty";
}
if (empty($_POST['username'])) {
$errors[] = "Username field is empty";
}
if (empty($_POST['password'])) {
$errors[] = "Password field is empty";
}
if (empty($_FILES['profile-img'])) {
$errors[] = "You should upload profile image";
} else{
$img = $_FILES['profile-img'];
$ext = end(explode('.', $img['name']));
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$max_size = 4; //MegaBytes
if (! in_array($ext, $allowed_extensions)) {
$errors[] = "Please , Choose a valid image";
}
$img_size = $img['size'] / 1000000; // By Megabyte
if ($img_size > $max_size) {
$errors[] = "This picture is so large";
}
}
if (!empty($errors)) {
echo '<div class="container">';
foreach ($errors as $error) {
echo '
<div class="alert alert-danger" role="alert">
' . $error . '
</div>
';
}
echo "</div>";
} else {
$username = filter_var(htmlentities(trim($_POST['username'])), FILTER_SANITIZE_STRING);
$name = filter_var(htmlentities(trim($_POST['name'])), FILTER_SANITIZE_STRING);
$password = sha1(filter_var(htmlentities(trim($_POST['password'])), FILTER_SANITIZE_STRING));
// Profile Picture :-
$imgname = uniqid(uniqid()) . #date("Y-m-d") . "." . $ext;
$target_bath = "uploads/imgs/";
$target_bath = $target_bath . basename($imgname);
$orginal_img = $img['tmp_name'];
if (move_uploaded_file($orginal_img, $target_bath)) {
$sql = "INSERT INTO users(name, username, password,profile_picture, r_d) VALUES ('$name', '$username', '$password', '$target_bath', NOW())";
$result = mysqli_query($conn, $sql);
header('location: ./login.php');
}
}
}
The script you've shown shown will only "not echo anything" if $_SERVER['REQUEST_METHOD'] is not "POST". Assuming your description of events is accurate, then the problem is in the form #halojoy has asked that you show here.
I do hope that you are not redirecting the script back to itself. Also you shouldn't attempt to do a redirect after an echo.
I want to start off with that this will be my first post on Stackoverflow, so thanks for helping me in advance.
I'm trying to make a form in which i can enter a name, artist, genre and upload an audio file into a folder.
I have it all setup except for the query doesn't work.
Here is the form:
<form action="upload" method="post" enctype="multipart/form-data">
<label for="musicName" class="col-sm-2 col-form-label col-form-label-lg">Title:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="musicName" id="musicName" required />
</div>
<label for="musicArtist" class="col-sm-2 col-form-label col-form-label-lg">Artist:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="musicArtist" id="musicArtist" required />
</div>
<label for="musicGenre" class="col-sm-2 col-form-label col-form-label-lg">Genre:</label>
<div class="col-sm-10">
<select class="form-control" name="musicGenre" id="musicGenre" required >
<option value="hiphop">Hip Hop</option>
<option value="trap">Trap</option>
<option value="pop">Pop</option>
<option value="edm">EDM/Dance</option>
<option value="rock">Rock</option>
<option value="rnb">RnB</option>
<option value="jazz">Jazz</option>
<option value="country">Country</option>
<option value="metal">Metal</option>
<option value="blues">Blues</option>
<option value="reggae">Reggae</option>
<option value="classical">Classical</option>
</select>
</div>
<label for="fileToUpload" class="col-sm-2 col-form-label col-form-label-lg"></label>
<div class="col-sm-10">
<label for="fileToUpload" class="uploadArea">drop a file to upload<div id="selectedFiles"><p></p></div></label>
<input type="file" name="fileToUpload" id="fileToUpload" class="hidden" multiple>
</div>
<label for="submitSong" class="col-sm-2 col-form-label col-form-label-lg"></label>
<div class="col-sm-10">
<input type="submit" value="Upload Image" id="submitSong" name="submitSong" class="btn btn-primary">
</div>
Then first i do all my checks etc.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$file_name = $_FILES["fileToUpload"]["name"];
$file_tmp = $_FILES["fileToUpload"]["tmp_name"];
$file_size = $_FILES["fileToUpload"]["size"];
$file_type = $_FILES["fileToUpload"]["type"];
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submitSong"])) {
$check = filesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
echo "<script>
alert(`File is not an audio file.`);
window.location.href=`music`;
</script>";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "<script>
alert(`Sorry, file already exists.`);
window.location.href=`music`;
</script>";
$uploadOk = 0;
}
$filesize = 5000000;
// Check file size
if ($_FILES["fileToUpload"]["size"] > $filesize) {
echo "<script>
alert(`Sorry, your file exceeds the limit of" . $filesize . " `);
window.location.href=`music`;
</script>";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "mp3" && $imageFileType != "wav" && $imageFileType != "flac" ) {
echo "<script>
alert(`Sorry, only Mp3, Wav & Flac files are allowed.`);
window.location.href=`music`;
</script>";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "<script>
alert(`Sorry, your file was not uploaded.`);
window.location.href=`music`;
</script>";
And then at last i upload the file and the attributes that came with it
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
if(isset($_POST[`submitSong`]))
{
$song_title = mysqli_real_escape_string($mysqli, htmlentities($_POST[`musicName`]));
$song_artist = mysqli_real_escape_string($mysqli, htmlentities($_POST[`musicArtist`]));
$song_genre = mysqli_real_escape_string($mysqli, htmlentities($_POST[`musicGenre`]));
$current_time = `CURRENT_TIMESTAMP`;
$sql = "INSERT INTO songs (song_name, song_artist, song_genre, uploaded_at, song_link, user_id VALUES
($song_title, $song_artist, $song_genre, $current_time, $file_tmp," . $_SESSION[`userid`] . ")";
// ($song_title, $song_artist, $song_genre, $current_time, $file_tmp," . $_SESSION[`userid`] . ")";
$result = $mysqli->query($sql);
var_dump($result);
// echo "<script>
// alert(`You have succesfully uploaded: ". basename( $_FILES["fileToUpload"]["name"]). " !`);
// window.location.href=`music`;
// </script>";
}
} else {
echo "<script>
alert(`Sorry, there was an error uploading your file.`);
window.location.href=`music`;
</script>";
// echo "Sorry, there was an error uploading your file.<br />";
}
}?>
Any help would be appreciated!
This question already has an answer here:
PHP file uploads doesnot read $_FILES['image'] [duplicate]
(1 answer)
Closed 7 years ago.
Hello I'm trying to create a form which includes an upload file input.
My form is sending data to my database while the file uploaded is stored in the img folder.
Now the form without the upload input works fine. The upload script without the form works fine too. But I can't manage to make them work together. I tried to include the "upload script" in my main form script but it didn't worked. I actually don't khow how this procedure should be done.
What I would like to do is that when I submit the form the data goes in the database and the upload file in my img folder. I think the problem comes somehow from the submit button.
Sorry for posting all my code but I think it's necessary to understand...
This is my addOutfit.php (which sends the data of my form to my database)
require("ajax/db.php");
$message = " ";
if ( $_POST ) {
if (!empty($_POST['type'])){
$title = htmlspecialchars($_POST['title']);
$description = htmlspecialchars($_POST['description']);
$brand = htmlspecialchars($_POST['brand']);
$material = htmlspecialchars($_POST['material']);
$type = htmlspecialchars($_POST['type']);
$color = htmlspecialchars($_POST['color']);
$sql = "INSERT INTO outfit (title, description, brand, material, type, color) VALUES('$title', '$description', '$brand', '$material', '$type', '$color')";
$statement = $pdo->prepare($sql);
$statement->execute(['title' => $title, 'description' => $description, 'brand' => $brand, 'material' => $material, 'type' => $type, 'color' => $color]);
$message = "The item has been added";
} else {
$message = "The type field is compulsory";
}
}
?>
<!--AddOutfit form-->
<div class="container-fluid" id="addOutfitForm" >
<div class="col-xs-12 col-md-10">
<form action ="addOutfit.php" method="post" novalidate>
<?php if ( $message ) { ?>
<h3 style="color: red;"><?=$message?></h3>
<?php } ?>
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" rows="3" name="description"></textarea>
</div>
<div class="form-group">
<label for="type">Type</label>
<input type="text" class="form-control" name="type">
</div>
<div class="form-group">
<label for="brand">Brand</label>
<input type="text" class="form-control" name="brand">
</div>
<div class="form-group">
<label for="color">Color</label>
<input type="text" class="form-control" name="color">
</div>
<div class="form-group">
<label for="material">Material</label>
<input type="text" class="form-control" name="material">
</div>
<div class="form-group" action="upload.php" method="post" enctype="multipart/form-data">
<label for="fileToUpload">Picture</label>
<input type="file" name="fileToUpload" id="fileToUpload">
</div>
<button type="submit" class="btn btn-default" name="submit" value="Upload Image">Send</button>
</form>
</div>
This is my upload.php (my uploading documents script)
<?php
$target_dir = "img/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
Your approach is confusing a bit. You need to check if you have POST request to store the data inside db and check also if you have a file to upload it
if(isset($_POST)) {
// validate and insert the data into db
// if isset $_FILES["fileToUpload"] update the file
if(isset($_FILES) && isset($_FILES["fileToUpload"]['name'])) {
}
}
Also don't forget to add the enctype="multipart/form-data" attribute to the form
<form action ="addOutfit.php" enctype="multipart/form-data" method="post" novalidate>
I think that you just need to add the enctype="multipart/form-data" attribute to your <form> tag.
See http://www.w3schools.com/tags/att_form_enctype.asp
Submitting files only works when the form data is submitted as multipart.
Instead of
<div class="form-group" action="upload.php" method="post" enctype="multipart/form-data"> <label for="fileToUpload">Picture</label>
Have you tried:
<form action ="addOutfit.php" method="post" enctype="multipart/form-data" novalidate>
I'm trying to submit my Bootstrap form using php so that the data entered into the form is emailed to me from the page. Something somewhere is not working though, and unfortunately my php knowledge is lacking (and web searches have so far brought up nothing of use).
When you click submit the modal which the form is in instantly closes (a default HTML thing?). Re-opening the modal displays the the form error messages if you have left forms blank. If you submit the form with all the content present, nothing happens.
So my question is this: What have I done wrong, and how do I fix it to get the email to send? Also, can I stop the modal from closing when content is submitted but not complete?
EDIT: I have implemented the "correct" php for uploading an image, but it gives me an invalid file type even when they are valid. echo $target_file only returns the file_dir suggesting it is failing to ge the name of the file. What have I done wrong?
Here is the php:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$location = $_POST['location'];
$desc = $_POST['desc'];
//Image upload
$target_dir = "/img/gallery/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists. Please rename your image.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 500000) {
echo "Sorry, your file is too large. Google how to reduce an image size or contact us if you need help with this.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$from = 'Gallery Upload Form';
$to = 'email#example.com'; //I've only changed this for stackoverflow
$subject = 'New Gallery Image';
$body = "Name: $name\n Location: $location\n Description: $desc\n \n $file";
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
if (!$_POST['location']) {
$errLocation = 'Please enter where your image was taken';
}
if (!$_POST['desc']) {
$errDesc = 'Please enter a description of your image';
}
if (!$_POST['file']) {
$errFile = 'Please upload your image file';
}
// If there are no errors, send the email
if (!$errName && !$errName && !$errLocation && !$errDesc && $errFile) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! Your image has been submitted.</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later or report this to us.</div>';
}
}
}
?>
And here is the HTML:
<div class="box">
<h2>Upload your picture</h2>
<p>Upload your picture and we'll upload it to the gallery. The best picture each month will be featured as the page background. You can also upload your pictures to our Facebook page with
<font color="darkcyan">#gallery</font>.</p>
<br>
<!-- model content -->
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModalNorm">Upload a Picture</button>
<!-- Modal -->
<div class="modal fade" id="myModalNorm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h3 class="modal-title" id="myModalLabel">Upload Image</h3>
</div>
<!-- Modal Body -->
<div class="modal-body">
<form role="form" method="post" action="index.php">
<div class="form-group">
<label for="name">Your Name</label>
<input class="form-control" placeholder="John Smith" type="text" name="name" required value="<?php echo htmlspecialchars($_POST['name']); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
<div class="form-group">
<label for="location">Location</label>
<input class="form-control" placeholder="South-west bank of Trout Pool." type="text" name="location" value="<?php echo htmlspecialchars($_POST['location']); ?>">
<?php echo "<p class='text-danger'>$errLocation</p>";?>
</div>
<div class="form-group">
<label for="desc">Picture Description</label>
<textarea class="form-control" name="desc" rows="3" placeholder="A picture of a 6lbs trout, my biggest all season."><?php echo htmlspecialchars($_POST['desc']); ?></textarea>
<?php echo "<p class='text-danger'>$errDesc</p>";?>
</div>
<div class="form-group">
<label for="btn-upload">Upload Image File</label>
<input type="file" id="exampleInputFile" name="file" value="<?php echo htmlspecialchars($_POST['file']); ?>">
<?php echo "<p class='text-danger'>$errFile</p>";?>
</div>
<input id="submit" name="submit" type="submit" value="Upload" class="btn btn-primary">
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?php echo $result; ?>
</div>
EDIT: A stupid question - Do you have to configure anything server-side for the email to be sent?
Your uploading a file your html form must have the enctype="multipart/form-data"
attribute.Use $_FILES variable to access information regarding uploaded file.
check these link for more information on $_FILES
http://php.net/manual/en/reserved.variables.files.php
http://www.tutorialsscripts.com/php-tutorials/php-files-variable.php