I have a form through which a user can upload images to a server folder, and the path gets saved in the database.
Currently the code that I have works fine when the user has to input only one image; however, I want to do something like the following with the form, so that user can upload more than one image:
<form class="form-horizontal" role="form" action="insertimage.php?id=<?php echo $_GET['id']; ?>" enctype="multipart/form-data" method="post">
<div class="col-md-6">
<div class="form-group">
<label class="col-lg-4 control-label">Select Image 1</label>
<div class="col-lg-6">
<input type="file" name="file" id="fileToUpload">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="col-lg-4 control-label">Select Image 2</label>
<div class="col-lg-6">
<input type="file" name="file1" id="fileToUpload">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="col-lg-4 control-label">Select Image 3</label>
<div class="col-lg-6">
<input type="file" name="file2" id="fileToUpload">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input class="btn btn-primary" value="Save Changes" type="submit" name="submit">
</div>
</div>
</div>
</form>
The PHP code at back end for uploading one image is insertimage.php:
<?php
$file_exts = array("jpg", "bmp", "jpeg", "gif", "png");
$upload_exts = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($upload_exts, $file_exts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
// Enter your path to upload file here
if (file_exists("uploads/" .$_FILES["file"]["name"]))
{
echo "<div class='error'>"."(".$_FILES["file"]["name"].")"." already exists. "."</div>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],"uploads/" . $_FILES["file"]["name"]);
echo "<div class='sucess'>"."Stored in: " . "uploads/" . $_FILES["file"]["name"]."</div>";
` }
}
}
else
{
echo "<div class='error'>Invalid file</div>";
}
?>
Can anyone please tell me how I can support uploading 3 images with help of the above code?
With this you are able to select multiple image with use of ctrl
<input type="file" name="file[]" id="fileToUpload" multiple />
On Server side use loop
for ($1=0;i<count($dataFile);$i++){
//your upload code ;
$_FILES["file"]["name"][$i];//go for each and every i position for all
}
You can use file array for multiple images at a time with multiple attribute in the html line like:
<input type="file" name="file[]" id="fileToUpload" multiple />
This will give you the array of files which you can debug by
print_r($_FILES);
And you also have to change the code that saves the data as there is error that it can only have one file at a time try for loop my debugging with
$_FILES
Related
Have been trying to upload an image and it is not working as expected. The error in the title is being displayed on the form. The image is being inserted via a file in the 'View' and checked in the 'Controller', however, when it comes to the final upload it fails, due to permissions I assume...
I have given both files in the view and controller the correct permissions for uploading files - in FileZilla.
The code is:
FORM - View
<form class="article" id="article-form" name="article" method="post" enctype="multipart/form-data">
<ol>
<li>
<label for="heading">Heading</label> <span id="headingMessage"></span>
<input name="heading" id="heading" class="form-control" type="text" required>
</li>
<li>
<label for="topic">Topic</label> <span id="topicMessage" required></span>
<input name="topic" id="topic" class="form-control" type="text" list="football">
<datalist id="football">
<option value="Scotland"></option>
<option value="England"></option>
<option value="Spain"></option>
</datalist>
</li>
<li>
<label for="summary">Summary</label> <span id="summaryMessage"></span>
<input name="summary" id="summary" class="form-control" type="text">
</li>
<li>
<label for="thumbnail">Thumbnail Link</label> <span id="thumbnailMessage"></span>
<!-- <input name="thumbnail" id="thumbnail" class="form-control" type="text" required> -->
<input type="file" name="file" id="file">
</li>
<li>
<label for="video">Video</label> <span id="videoMessage"></span>
<input name="video" id="video" class="form-control" type="text">
</li>
<li>
<label for="articleText">Text</label>
<textarea name="articleText" id="articleText" class="md-textarea form-control" required></textarea>
</li>
<!-- <li>
<div class="g-recaptcha" data-sitekey="6LcUAnQUAAAAAPeF1u6Hcnf0Y5TfS4-0xitZ7ZeZ"></div>
</li> -->
</ol>
<input class="btn btn-success" id="formButton" type="submit" name="submit"value="Submit" name="submit">
<input class="btn btn-danger" id="formButton" type="reset" value="Reset">
</form>
The controller -
//check image
$target_dir = "../view/pictures";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 0;
$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["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 2;
//$thumbnail = '<img class="img-responsive" id="articleImage" src="'.$_POST["file"].'">';
echo $target_file;
} else {
echo "File is not an image. <hr>";
$uploadOk = 0;
}
}
$thumbnail=$target_file;
include("../model/api-article.php") ;
if($uploadOk>1)
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
$articleTxt = insertArticle($headline, $topic, $summary, $text, $thumbnail,$video,$date,$userId);
} else {
echo "Sorry, there was an error uploading your file.";
}
}else{
echo "Article not inserted - only upload images (PNG, JPEG)";
}
}
Please excuse the indenting
It's may not enough to give permission to the upload file - you need to permit the whole folder where you are uploading your images.
Hello everyone,
I have a table consist of 10 columns which in 4 of them i want to insert the image paths.
can any one guide me how to insert the image paths into database along with other 6 more columns data in a single query and upload the images into server(inside a folder).
here my html code:
<div class="panel-body">
<div class="form-group">
<label style="align-content:center" for="inputdefault">Product full name</label>
<input class="form-control" id="inputdefault" name="name2" type="text">
</div>
<div class="panel-body">
<div class="form-group">
<label style="align-content:center" for="inputdefault">Product category</label>
<input class="form-control" id="inputdefault2" name="name1" type="text">
</div>
<div class="panel-body">
<div class="form-group">
<label style="align-content:center" for="inputdefault">Product qty</label>
<input class="form-control" id="inputdefault3" name="name3" type="text">
</div>
<div class="panel-body">
<div class="form-group">
<label style="align-content:center" for="inputdefault">Picture 1.</label>
<input type="file" id="file3" name="files[]" multiple="multiple" accept="image/*" />
</div>
<div class="form-group">
<label style="align-content:center" for="inputdefault">Picture 2.</label>
<input type="file" id="file3" name="files[]" multiple="multiple" accept="image/*" />
</div>
<div class="form-group">
<label style="align-content:center" for="inputdefault">Picture 3.</label>
<input type="file" id="file3" name="files[]" multiple="multiple" accept="image/*" />
</div>
<div class="form-group">
<label style="align-content:center" for="inputdefault">Picture 4.</label>
<input type="file" id="file3" name="files[]" multiple="multiple" accept="image/*" />
</div>
Here php code :
Note: I did not get image file names in any variable to added into query, everything is working fine here just need to work with images upload and store the path in to database
<?php
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$pname= stripslashes($_REQUEST['name1']);
$pcat= stripslashes($_REQUEST['name2']);
$pprice= stripslashes($_REQUEST['name3']);
$pqty= stripslashes($_REQUEST['qty']);
$pdesc=stripslashes($_REQUEST['description']);
//$spassword=stripslashes($_REQUEST['img']);
$sqlinsert ="INSERT INTO `noorizone`.`products` VALUES ('$pname', '$pcat', '$pprice')";
if($con-> query($sqlinsert)=== true)
{
echo "<center><b style='color:green;'> added successfully... </b>";
echo"</center>";
}
else{
echo "<b style='color:red;'> cant register". $con->error."</b>";
}
}
?>
THANKS IN ADVANCE !!!
This is example for me, you can learn my codes :
$fileImageStatus = ""; // Create your variable for files
if(isset($_FILES['files_status']['name'])){ // Checking value for all input
$fileImageName = array(); // Make an array
for($i = 0; $i < count($_FILES['files_status']['name']); $i++){ // Looping
$imageName = $_FILES['files_status']['name'][$i]; // Give a variable with index from array looped
$uploadPath = '././sistem/users/members/'.$idPenerima.'/unggahan/';
move_uploaded_file($imageTmp, $uploadPath.$imageName); // Path upload
$fileImageName[] = $imageName; // Setting a values from array
}
$fileImageStatus = implode(",", $fileImageName); // Make that values an string
}
// in here you can insert to database with value from $fileImageStatus
I think if you change the name of the file to say file1 instead of file[], you will be fine.
See an example from W3Schools.com
<!DOCTYPE html>
<html>
<body>
<!--
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["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["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
-->
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Here is a Good tutorial on how to upload multiple images into PHP and Mysql
http://www.wdb24.com/how-to-upload-multiple-images-in-php-and-store-in-mysql/
I'm developing a back end for my blog but the code to upload images isn't working as expected.
When i submit it uploads the image and moves it to the designated folder but in the database there is no record inserted. Here is the php for uploading
<?php
session_start();
include('Connections/conn.php');
if (!isset($_SESSION['userid'])) {
header("location:index.php");
}
$suc=" ";
$writer=$_SESSION['my_username'];
if(isset($_POST['submit']))
{
error_reporting(E_ALL ^ E_NOTICE);
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$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;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$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["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.";
}
}
$title=$_POST['title'];
$intro=$_POST['intro'];
$body=$_POST['body'];
$keywords=$_POST['keywords'];
$date=$_POST['date'];
$fileToUpload=$_POST['fileToUpload'];
$sql2="Insert into articles(title,intro,body,keywords,date,writer,fileToUpload)VALUES('$title','$intro','$body','$keywords','$date','$writer','$target_file')"or die(mysqli_error());
$result2 = mysqli_query($db_conn, $sql2);
$suc=" <div class='alert alert-success'>
<span><b>Success</b>: New article posted successfully!</span>
</div>";
}
?>
And here is the form
<form method="POST" action"<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<div class="form-group">
<label>Title</label>
<input type="text" id="title" name="title" class="form-control" required/>
</div>
<div class="form-group">
<label>Intro</label>
<textarea id="intro" name="intro" class="form-control" required></textarea>
</div>
<div class="form-group">
<label>Enter keyword tags</label><br/>
<div>
<input type="text" id="keywords" name="keywords" class="tagsinput" required/>
</div>
</div>
<div class="form-group">
<label>Date</label><br/>
<div>
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-calendar"></span></span>
<input type="text" id="date" name="date" class="form-control datepicker" placeholder="Select Date" required>
</div>
<span class="help-block">Click on input field to select date</span>
</div>
<div class="form-group">
<div>
<label>Picture</label>
<input type="file" multiple class="file" data-preview-file-type="any" name="fileToUpload" id="fileToUpload"/>
</div>
</div>
<div>
<div class="block">
<p>Type the content below, note that you can extend the height of the editor by dragging the bottom border.</p>
<textarea class="summernote" id="body" name="body" placeholder="Enter the body text" required>
</textarea>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<button class="btn btn-danger btn-block" type="reset">Reset</button>
</div>
<div class="col-md-6">
<button class="btn btn-info btn-block" type="submit" name="submit" value="submit">Publish Article</button>
</div>
</div>
</form>
Replace
$fileToUpload=$_POST['fileToUpload'];
with
$fileToUpload=$_FILES['fileToUpload']['name'];
Try this
$sql2="INSERT INTO articles(title,intro,body,keywords,date,writer,fileToUpload)VALUES('$title','$intro','$body','$keywords','$date','$writer','$target_file')");
if (!mysqli_query($db_conn, sql2))
{
echo("Error description: " . mysqli_error($db_conn));
}
else{
echo "Inserted";
}
and my opinion is add the insert code after move_uploaded_file get success
I'm creating a simple mail system in PHP. And I'm stuck in this situation. I want to add a feature where my system can also do a file uploading and transferring. But I don't know how to add the file into mysql database. Any tips would be appreciated
compose.php
<form class="form-horizontal" method="post" action="" id="someForm" enctype="multipart/form-data">
<fieldset>
<!-- Form Name -->
<legend>Compose Mail</legend>
<!-- Text input-->
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="sendto">Send To: </label>
<div class="controls">
<input id="sendto" name="sendto" placeholder="Send To" class="input-xlarge cmps" type="text">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="title">Title: </label>
<div class="controls">
<input id="title" name="title" placeholder="Title/Subject" class="input-xlarge cmps" type="text">
</div>
</div>
<!-- Textarea -->
<div class="control-group">
<label class="control-label" for="body">Message: </label>
<div class="controls">
<textarea id="body" name="body" class="cmps"></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label" for="file">File: </label>
<div class="controls">
<input id="file" name="file" type="file">
</div>
</div>
<button type="submit" id="button" class="btn btn-success" onclick="askForSubmit()">Send!</button>
<button type="submit" id="button" class="btn-danger btn" onclick="askForSave()">Save to drafts</button>
</fieldset>
</form>
<script>
form=document.getElementById("someForm");
function askForSave() {
form.action="http://rsantiago.mbchosting.ph/email/save.php";
form.submit();
}
function askForSubmit() {
form.action="http://rsantiago.mbchosting.ph/email/send.php";
form.submit();
}
</script>
the upload_file.php
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 30000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 30000) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
I just wanna know how to store the file into the database so when the user sends it to another user, it can be downloaded
I am not sure what is wrong with this code, so I was hoping for some helpful input.
The Problem
It will not get the name of the file that I have uploaded nor is it actually uploading it into the defined directory.
The PHP Code
<? include("header.php");
include("sidebar.php");
?>
<h2>Add Raffle</h2>
<?
$name = asql($_POST['name']);
$type = asql($_POST['prize']);
$min_points = asql($_POST['minp']);
$min_cash = asql($_POST['maxu']);
$cons = strtotime($_POST['cons']);
$cone = strtotime($_POST['cone']);
if($_POST['subm'])
{
if ($name == NULL OR $type == NULL OR $min_points == NULL OR $min_cash == NULL) {
print"Please Fill Out All Of The Required Fields<br /><a href='rafadd.php'><img src='img/green_arrow_left.png' alt='Go Back' /></a>"; include"footer.php";
exit();
}
if (!in_array($file['type'], array("image/gif", "image/jpeg", "image/png"))
|| $file['size'] > 20000)
{
if ($_FILES["file"]["error"] > 0)
{
echo "There was an error";
}
else
{
echo "";
$filename = $_FILES["file"]["name"];
if (file_exists("../images/rewards/" . $_FILES["file"]["name"]))
{
unlink("../images/raffles/" . $_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"],
"../images/raffles/" . $_FILES["file"]["name"]);
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../images/raffles/" . $_FILES["file"]["name"]);
}
}
}
else
{
echo "Invalid file";
$updatecontests = mysql_query("INSERT INTO raffles (`id`, `raffle_name`, `raffle_prize`, `buy_in`, `max_entry`, `prize_image`, `start`, `end`) VALUES ('','$name','$type','$min_points','$min_cash','images/raffles/".$filename."','$cons','$cone')") or die(mysql_error());
if($updatecontests){
$create = mysql_query("CREATE TABLE IF NOT EXISTS `".$name."` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` text NOT NULL,
`entries` int(11) NOT NULL,
PRIMARY KEY (`username`(30)),
KEY `id` (`id`)
)");
}
print "You Have Successfully Added this Raffle<br /><br />
<a href='rafadd.php'><img src='img/green_arrow_left.png' alt='Go Back' /></a>";
}
else
{
print"<div class='form'>
<form action='' method='post'><input type=hidden name=subm value=1>";
?>
<div class="element">
<label for="name">Raffle Name: <span class="red">(required)</span></label>
<input id="name" name="name" size="50" />
</div>
<div class="element">
<label for="prize">Raffle Prize: <span class="red">(required)</span></label>
<input id="prize" name="prize" size="50" />
</div>
<div class='element'>
<label for='file'>Prize Image:</label>
<input type='file' name='file' id='file' />
</div>
<div class="element">
<label for="cons">Start Date: <span class="red">(required)</span></label>
<input id="cons" name="cons" size="50" /><img src="images/cal.gif" width="16" height="16" border="0" alt="Pick a date">
</div>
<div class="element">
<label for="cone">End Date: <span class="red">(required)</span></label>
<input id="cone" name="cone" size="50" /><img src="images/cal.gif" width="16" height="16" border="0" alt="Pick a date">
</div>
<div class="element">
<label for="minp">Cost Per Ticket: <span class="red">(required)</span></label>
<input id="minp" name="minp" size="50" />
</div>
<div class="element">
<label for="maxu">Maximum Entries per User: <span class="red">(required 0 for unlimited)</span></label>
<input id="maxu" name="maxu" size="50" />
</div>
<?php
print" <dl class='submit'>
<input type='submit' name='subm' id='subm' value='Submit' />
</dl>
</form>
</div> ";
}
?>
</div><!-- end of right content-->
</div> <!--end of center content -->
<div class="clear"></div>
</div> <!--end of main content-->
<div class="footer">
<div class="left_footer">IN ADMIN PANEL | Powered by INDEZINER</div>
<div class="right_footer"><img src="images/indeziner_logo.gif" alt="" title="" border="0" /></div>
</div>
</div>
</body>
</html>
I have used the file upload snippet in another script and it uploads perfectly so I am not sure why it is not working here.
in the form tag add enctype="multipart/form-data"
<form action='' method='post'enctype="multipart/form-data">
<form action='' method='post'>
is wrong, needs to be:
<form action='' method='post' enctype='multipart/form-data'>
Also, use <?php instead of <?
PS I miss the point where $file is set.
It doesn't look like file is being instantiated anywhere. Did you mean:
if (!in_array($_FILES['file']['type'], array("image/gif", "image/jpeg", "image/png"))
|| $_FILES['file']['size'] > 20000)