Create a PHP contact form with multiple image upload - php

I need to create an html contact form which collects some data and uploads 8 images through a PHP script
This is my HTML:
<form action="formmail.php" onsubmit="return controlloform()" id="form" name="form" method="POST" enctype="multipart/form-data">
<input name="email" id="email" placeholder="Email address" type="text" value="" maxlength="40">
<input name="tel" id="tel" type="text" placeholder="Order number" value="" maxlength="20">
<textarea name="msg" placeholder="Message" value="" maxlength="300"></textarea>
Upload a photo:
<p>
<p>
<input name="file" id="file" class="button" type="file" value="">
<p>
<p>
<td colspan="2">
<input type="submit" class="button" value="Submit" />
</td>
</tr>
</table>
</form>
I don't know how to create the upload script, what I need to do is uploading 2 blocks of 4 images, check the extension of the file (only jpg and png allowed) and the size (max 500 kb for image).
I've already found some upload scripts (not 100% suitable for what I need) but I don't know how to include the upload part into the rest of the code
If anyone could help me would be great
Thanks a lot

This code make multiple upload
$total = count($_FILES['photo_file']['name']);
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['photo_file']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['photo_file']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
if you want to check file size insert this code
if ($_FILES["photo_file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
this code make validation
$allowed = array('gif','png' ,'jpg');
$filename = $_FILES['photo_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
$uploadOk = 0;
}

Related

Fetching name of a file and insert it in the same form

I'm triying to fetch the name of a file uploaded and set it as the value of a hidden input on the same form. I've tried this and it uploads the file but dont send the file name.
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152) {
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"../img/plates/".$file_name);
header("Location: backend.php");
}else{
print_r($errors);
}
}
After that i try to inset the $file_name in to the same form as the file input. Something like this
<input name="image" type="file" placeholder="Select photo">
<input type="hidden" value="<?php echo $file_name ?>" name="photo" />
<button type="submit" name="add">ADD NEW ITEM</button>
You cant do it just by php, because php update your page after request and response if you like to get the file name and file in a request you can use java script like this :
$("#imagefile").change(function(){
$("#imagename").val(this.files[0].name);
});
and change your code like this :
<input id="imagefile" name="image" type="file" placeholder="Select photo">
<input id="imagename" type="hidden" value="<?php echo $file_name ?>" name="photo" />
<button type="submit" name="add">ADD NEW ITEM</button>
you can read more at this link :
How to display file name for custom styled input file using jquery?

File upload not working properly in PHP

I have created a file upload in PHP. the max file size is 5MB. I'm trying to upload a file which is 39 MB.
The file upload is working fine for all the files which are of 5MB or less than 5MB, it is even working fine with 30 MB file and returning ERROR: MAX file size limit exceeds. But only in this case 39MB it is returning the below error.
I'm getting below error.
**action.php**
<form class="w3-container " action='file_upload.php' method='post' enctype="multipart/form-data" name="form" id="form-e" role="form">
<DIV id="file_name_div">
<label for="file_name">Enter file name: </label><br>
<input data-validation="filename" autocomplete="off" style="width:30%" class="w3-input w3-border w3-light-grey " type="text" name='file_name' id='file_name' autofocus />
<label for="Role">Enter Role: </label><br>
<input data-validation="role" style="width:30%" class="w3-input w3-border w3-light-grey " type="text" name='role' id='role' autofocus />
</DIV>
<br>
<button type="reset" class="btn btn-info btn-md w3-blue"><span class="glyphicon glyphicon-refresh"></span> Reset</button>
</form>
****file_upload.php****
<?php
session_start();
include_once 'config.php';
$message = '';
$fileName = $_POST['file_name']; //LINE NO 6
$role = $_POST['role']; #role code //LINE NO 7
$dir= "files/$role/"; #uploading file to selected role
foreach ($_FILES as $filename => $filearray) {
if (is_uploaded_file($filearray['tmp_name'])) {
$fileLogicalName = $filearray['name'];
$fileSize = (int) ($filearray['size'] / 1024);
$filePhysicalName = pathinfo("$fileLogicalName"); //Return complete file name with extension
$filePhysicalName['filename']; //The arrray of pathinfo return only file name without extension
if ($fileSize <= 5120) // 5mb/1024
{
//file upload code
}
}
}
?>
try add more size to the file limit
ini_set('memory_limit','1028M');
ini_set('upload_max_filesize','1028M');
ini_set('post_max_siz','1028M');

tmp_name not holding my uploaded file

I am trying to run a php script to upload an image to a location on my server while storing its the location details in my database.
All seems fine except my tmp_name doesn't seem to be getting the file so all I get is the string location in the database pointing to a file not existing in my server. I couldn't figure out this one.
First this is the html markup:
$imgsize=$_POST['MAX_FILE_SIZE'];
$name = $_FILES["file"]["name"];
$location = 'db/farmers_pPix/';
$load_dataFarmerPix="form/".$location.$FNAME.'_'.$LNAME.'_'.$FNO.'-'.$name;
$passport=$load_dataFarmerPix;
...
$tmp_name = $_FILES['file']['tmp_name'];
$error = $_FILES['file']['error'];
if (!empty($name)) {
move_uploaded_file($tmp_name, $load_dataFarmerPix);
if (move_uploaded_file($tmp_name, $load_dataFarmerPix)){
echo '<p style="width:100%; color:#777; font-family:eurof35-webfont;"><h4 class="text-center">Your profle has been created and photo Uploaded</h4></p>';
}
} else {
echo '<p style="width:100%; color:#777; font-family:eurof35-webfont;text-align:center;" class="text-center"><h5>please choose a file</h5></p>';
}
echo '<p style="width:100%; color:#777; font-family:eurof55-webfont;text-align:center;"><h3 class="text-center">Registration Successfull</h3></p>';
}
}
<form enctype="multipart/form-data" id="myform" class="fs-form fs-form-full" autocomplete="off" style="color:#ccc;" action="farmreg2.php" method="post">
...
<li>
<label class="fs-field-label fs-anim-upper" for="q5">Upload a Current Photo? </label>
<input class="fs-anim-lower" style="color:#ccc; padding:1%;" id="id" name="file" type="file" placeholder="Supported formats (jpg,png,bmp,gif)"/>
<input class="fs-anim-lower" id="id" value="30000" name="MAX_FILE_SIZE" type="hidden" placeholder="" required/>
</li>
...
</form>
this file itself is farmreg2.php

basic php5 file upload issue

I'm currently coding the most basic file upload to go to our server from an input type="file" attribute. This is my HTML:
<form enctype="multipart/form-data" action="register-complete.php" method="post">
<h5>Register Now</h5>
<input type="text" class="form-control" name="Username" placeholder="Login Name"/><br />
<input type="text" class="form-control" name="Displayname" placeholder="Display Name"/><br />
<input type="text" class="form-control" name="Email" placeholder="Email" /><br />
<input type="radio" name="Paypal" value="1" /> This is my Paypal email.<br />
<input type="radio" name="Paypal" value="0" /> I do not want payment. I wish to preserve anonymity.<br /><br />
Avatar Picture: <br /><input type="file" name="AvatarPicture" id="AvatarPicture" />*500kb max file size.<br />*Accepted filetypes: .jpg, .png<br /><br />
<input type="text" class="form-control" name="Description" placeholder="Account Description"/><br />
<input type="password" class="form-control" name="Password" placeholder="Password"/><br />
<input type="password" class="form-control" name="PasswordConfirm" placeholder="Confirm Password"/><br />
<p class="text-center"><input type="submit" class="btn btn-primary" value="Register" name="submit" /></p>
</form>
Basically I'm just concerned with the AvatarPicture input, and just get it to upload a file to my server. Here is the PHP code I have to do that.
$username = $_REQUEST["Username"];
$displayname = $_REQUEST["Displayname"];
$email = $_REQUEST["Email"];
$paypal = $_REQUEST["Paypal"];
$target_dir = "images/avipictures/";
$target_file = $target_dir . basename($_FILES["AvatarPicture"]["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["AvatarPicture"]["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.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["AvatarPicture"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
echo "Sorry, only JPG, JPEG, PNG 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["AvatarPicture"]["tmp_name"],$target_file)) {
echo "The file has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
This is literally the same exact thing as the w3schools code to the tee. However I am receiving an internal server 500 error unless I change the "tmp_name" in the move_uploaded_file() to "name", which just leads to the else statement. I've been messing around with this all day and I have just been tearing my hair out at just how simple this bit of code should be but doesnt seem to be at all. Any ideas? (Also, the file_uploads is set to on and the default largest file size is set to 50mb.)
I can't tell what the problem is without a decent log file, but it could be that the directory you're trying to write to doesn't exist or you don't have permission to write to it. Are you sure that the images/avipictures/ directory that you're trying to write to exists, and that the webserver has permission to write to it? If not, you'll need to create the directory and set the permissions on it such that the webserver can write to it.

Issues with Php Music File Uploader

So I'm trying to upload music files with php but the files aren't going to the folder, here's my code what are my mistakes and what am i missing
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="text" placeholder="File Name" name="file_name">
<input type="text" placeholder="Artist Name" name="artist_name">
<textarea rows="5" placeholder="Description" name="description"></textarea>
<input type="submit" class="btn btn-warning bgcolor" name="submit" value="Upload"/>
</form>
<?php
if(isset($_POST['submit'])){
function GetMusicExtension($musictype)
{
if(empty($musictype)) return false;
switch($musictype){
case 'audio/mp3': return '.mp3';
default: return false;
}
}
if (!empty($_FILES["file"]["name"])) {
$file_name=$_FILES["file"]["name"];
$temp_name=$_FILES["file"]["tmp_name"];
$music_type=$_FILES["file"]["type"];
$size = $_FILES['file']['size'];
$ext= GetMusicExtension($music_type);
$musicname = $_POST['file_name'].$ext;
$target_path = "music/".$musicname;
if(move_uploaded_file($temp_name, $target_path)) {
$query = "insert into music(name,artist,description)
values('".$musicname."','".$_POST['artist_name']."','".$_POST['description']."')";
mysqli_query($link,$query) or die("error in $query == ----> ".mysqli_error($link));
}
}else{
exit('<script>alert("Error Saving Data... try again");</script>');
}
}
?>
PS: If i change the mime to an image mime and try uploading it uploads
UPDATE:
If i change post_max_size and upload_max_size it works. Thanks all.

Categories