Upload multiple images in php - php

i am creating a page called events i have created a form which submits on post file, this is my form code, `
Adding Staff
<div class="box">
<label>Heading</label>
<input type="text" name="heading" id="heading"/>
</div>
<div class="box" style="margin-left: 120px">
<label>Description 1</label>
<textarea cols="30" rows="5" name="description_1" id="description_1"></textarea>
</div>
<div class="box">
<label>Description 2</label>
<textarea cols="30" rows="5" name="description_2" id="description_2"></textarea>
</div>
<div class="clear"> </div>
<div class="box">
<label>Upload Images</label>
<input type="file" name="picture" id="picture"/>
<label>Is Rename <input type="checkbox" name="is_rename"> </label>
</div>
<div class="clear"> </div>
<div class="box" style="width: 100px; margin-left: 350px;">
<input style="padding: 4px" type="submit" name="submit" value="submit">
</div>`
This is my post
<?php
ob_start();
session_start();
include_once "../../classes/addClasses.php";
$heading = $_POST['heading'];
$description_1 = $_POST['description_1'];
$description_2 = $_POST['description_2'];
$picture = $_POST['picture'];
$target_dir = "../../../uploads/";
$target_file = $target_dir . basename($_FILES["picture"]["name"]);
print_r($_FILES);
if( isset( $_POST['is_rename'] ) )
$file_name = time().'-'.basename($_FILES["picture"]["name"]);
else
$file_name = basename($_FILES["picture"]["name"]);
if(empty($_FILES['picture']['name'])){
echo "please select a file to upload";
?>
<script>window.location.href="http://localhost/learner-pack/admin/admin/add_events.php?error=empty"</script>
<?php
}
$target_file = $target_dir . $file_name;
if (move_uploaded_file($_FILES["picture"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["picture"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
if (file_exists($target_file)) {
echo "Sorry, file '".$file_name."' already exists.";
}elseif (move_uploaded_file($_FILES["picture"]["tmp_name"], $target_file)) {
echo "The file " . $file_name . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
/*$created_by = $_POST['created_by'];
$updated_by = $_POST['updated_by'];
$current_date = $_POST['current_date'];
$updated_date = $_POST['updated_date'];
$visitor_counter = $_POST['visitor_counter'];*/
if($admin->addingEvents($heading,$description_1,$description_2, $file_name))
{
header('Location: ../view_events.php?added=true');
}
else
{
echo "Error";
}
?>
please help me to store multiple images in table using one field and retireve them to view on events page when i fetch one row so that all images on that row are fetchable

Related

Form with Upload file attachment

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

Is it possible to have multiple enctypes on an html form?

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.

PHP FileUpload is not working

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.

Dynamic single file upload issue?

I have a form that generates multiple single file uploads. They currently upload fine but the upload file keeps overwriting $_SESSION['file'][0] in the array .
<?php
if(isset($_SESSION['UploadCount'])){
for($i=0;$i<=$_SESSION['UploadCount'];$i++){ ?>
<div class="form-group col-md-6">
<span class="control-label">Upload:</span>
<div class="form-control file-input">
<label for="Attachment">
<span class="btn btn-primary">
<input type="file" name="Attachment<?php echo $i; ?>" value="<?php echo $i; ?>"id="Attachment" onchange="this.form.submit();"/>
Choose File
</span>
</label>
<input class="file-name" type="text" readonly="readonly" placeholder="<?php if(isset($_SESSION['file'][$i])){ echo $_SESSION['file'][$i]; } else { echo "No file selected"; } ?>" />
</div><br>
<?php if(isset($_SESSION['UploadError'][$i])){ ?><span class="error"><?php echo $_SESSION['UploadError'][$i]; ?></span><?php } ?>
</div>
<div class="form-group col-md-12">
<label for="Topic" class="control-label">Topic Description</label>
<textarea class="form-control" name="Topic" cols="20" rows="3"><?php if(isset($_SESSION['Topic'])){ echo $_SESSION['Topic']; } ?></textarea>
</div><?php } } ?>
The php to do upload is:
for($i=0;$i<=$_SESSION['UploadCount'];$i++){
if(isset($_FILES["Attachment".$i]["name"])){
if($_FILES["Attachment".$i]["name"])
{
$uperror = "";
include ($_SERVER['DOCUMENT_ROOT'].'/Core/MultiUpload.php');
if($uperror==""){
$_SESSION['file'][$i] = basename($_FILES["Attachment".$i]["name"]);
$_SESSION['stored'][$i] = $target_file;
} else {
$_SESSION['UploadError'][$i] = $uperror;
}
header( "Location: ".$hostname."/consultation/?page=".$Page."&assign=".$Assign ) ;
exit;
}
}
}
MultiUpload.php file is:
<?php
$uploadfoldercheck = "../Uploads/".$_SESSION['CompanyName']."/";
$uploadfoldercheck = str_replace(' ', '_', $uploadfoldercheck);
if (!file_exists($uploadfoldercheck))
{
mkdir($uploadfoldercheck, 0755, true);
$copy_index = $uploadfoldercheck."/index.php";
copy('../Uploads/index.php', $copy_index);
}
$filename = "../Uploads/".$_SESSION['CompanyName']."/".$_SESSION['UserID']."/";
$filename = str_replace(' ', '_', $filename);
if (!file_exists($filename))
{
mkdir($filename, 0755, true);
$copy_index = $filename."/index.php";
copy('../Uploads/index.php', $copy_index);
}
$target_file = $filename . basename($_FILES["Attachment".$i]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
$uperror = "Sorry, file already exists:".$target_file;
$uploadOk = 0;
}
// Check file size
if ($_FILES["Attachment"]["size"] > 2000000) {
$uperror = "File to large. Max 2MB.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "pdf" ) {
$uperror = "Sorry, only PDF files are allowed.";
$uploadOk = 0;
}
if($uploadOk=="1")
{
if (move_uploaded_file($_FILES["Attachment".$i]["tmp_name"], $target_file)) {
} else {
$uperror = "Unable to load File!";
}
}
?>
Upload count gets initiliased:
if(!isset($_SESSION['UploadCount'])){
$_SESSION['UploadCount']=3;
}

i tried to upload a file to upload folder but getting failure message

my directory is looks like this
->source files
--css
--upload
add_file.php
upload.php
my code is as follows
upload.php
<form role="form" method="post" enctype="multipart/form-data" action="add_file.php">
<div class="form-group">
<label for="filecaption">
Caption :
</label>
<input type="text" name="f_caption" class="form-control"/>
</div>
<div class="form-group">
<label for="Choose a File">
Caption :
</label>
<input type="file" name="uploaded_file" class="form-control"/>
</div>
<div class="form-group">
<input type="submit" name="upload" value="Upload" class="form-control btn btn-warning"/>
</div>
</form>
add_file.php
<?php
if(isset($_FILES['uploaded_file']))
{
$f_name= $_FILES['uploaded_file']['name'];
$temp_name= $_FILES['uploaded_file']['tmp_name'];
if(!$temp_name)
{
die("no file uploaded..please try again");
}
else
{
$path = "upload/" . $f_name;
if( move_uploaded_file($f_name, $path))
{
echo "success";
}
else
{
echo "failure";
}
}
}
?>
The problem is from the add.php.
Try this
<?php
if(isset($_FILES['uploaded_file'])) {
$f_name= $_FILES['uploaded_file']['name'];
$temp_name= $_FILES['uploaded_file']['tmp_name'];
if(!$temp_name)
{
die("no file uploaded..please try again");
}
else
{
$path = "upload/" . $f_name;
if( move_uploaded_file($temp_name, $path))
{
echo "success";
}
else
{
echo "failure";
}
}
}
?>
The problem is that you were moving from the f_name instead of the temp_location.

Categories