I've managed to get a photo to be uploaded to the server and then written to the database thanks to quite a bit of help but I need to be able to upload three files and each needs to be written to the database accordingly. So at the moment only photo1 is being uploaded and written, I'd like to create another form input for photo2 and 3 and have them also written and uploaded. Sorry I'm almost a complete beginner with php, any help will be hugely appreciated! thanks in advance.
<?php
session_start();
include_once('../php/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_POST['title'], $_POST['content'], $_FILES['photo1'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
$name = $_FILES['photo1']['name'];
$tmp_name = $_FILES['photo1,']['tmp_name'];
$target = '../lifestyle/'.$name;
if (move_uploaded_file($tmp_name, $target)) {
$stmt = $pdo->prepare('INSERT INTO article (article_title, article_content, photo_1, photo_2) VALUES (?,?,?,?)');
$stmt->execute(array($title,$content,$name,));
header('Location: index.php');
exit();
}
}
?>
<form action="add.php" method="post" autocomplete="off" enctype="multipart/form-data"/>
<<input type="text" name="title" id="title"/>
<textarea name="content"></textarea></dt>
<input type="file" name="photo1" >
<input type="submit" id="add article"/>
</form>
Use attribute multiple and make some sort of array of the name:
<input type="file" name="photo[]" multiple >
OR
<input type="file" name="photo[]">
<input type="file" name="photo[]">
<input type="file" name="photo[]">
http://php.net/manual/en/features.file-upload.multiple.php
Related
This question already has answers here:
Multiple file upload in php
(14 answers)
Closed 1 year ago.
Could someone please assist as I would like to upload multiple images to the server as well the image names to the database.
The below code works for uploading the images to the server:
View:
<form action="<?php echo URLROOT; ?>/posts/add" method="post" enctype='multipart/form-data'>
<input type="file" name="file[]" multiple>
<input type="submit" name=submit value="Submit">
</form>
Controller:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// Count total files
$countfiles = count($_FILES['file']['name']);
// Looping all files
for($i=0;$i<$countfiles;$i++){
$filename = $_FILES['file']['name'][$i];
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'][$i], dirname(__DIR__)."/img/".$filename);
}
} else {
// Load view with errors
$this->view('posts/add');
}
}
I am also able to upload the 3 image names when using the below code with 3 separate inputs:
View:
<form action="<?php echo URLROOT; ?>/posts/add" method="post">
<input type="file" name="image1">
<input type="file" name="image2">
<input type="file" name="image3">
<input type="submit" name=submit value="Submit">
</form>
Controller:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// Sanitize POST array
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$data = [
'user_id' => $_SESSION['user_id'],
'image1' => trim($_POST['image1']),
'image2' => trim($_POST['image2']),
'image3' => trim($_POST['image3']),
];
// Validated
if($this->postModel->addPost($data)){
flash('post_message', 'Post Added');
redirect('posts');
} else {
die('Something went wrong');
}
} else {
$data = [
'image1' => '',
'image2' => '',
'image3' => ''
];
$this->view('posts/add', $data);
}
}
Could someone please advise on how I could combine the code, in order to use a single file input for uploading the images to server, as well as the image names to the database?
Complete Code
<form method='post' action='' enctype='multipart/form-data'>
<input type="file" name="file[]" id="file" multiple>
<input type='submit' name='submit' value='Upload'>
</form>
PHP
<?php
if(isset($_POST['submit'])){
$imageName =$_FILES['file']['name'];
// Count total files
$countfiles = count($_FILES['file']['name']);
// Looping all files
for($i=0;$i<$countfiles;$i++){
$filename = $_FILES['file']['name'][$i];
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'][$i],'upload/'.$filename);
//insert code
$query = "insert into images(images) values('".$imageName."')";
mysqli_query($con,$query);
}
}
?>
Use this input code -
<input type="file" name="image[]" id="file" multiple>
And count file in php file then use loop for iterating file like-
$counts = count($_FILES['image']['name']);
for($i=0;$i<$counts;$i++){
//uploading code here
}
I have a mobile web app form where I access the mobile device camera and capture a photo along with some other details captured within other fields in the form. Using php I save the information captured in the form to a mysql database sucessfully, but the image is not stored. I have searched for a resolution but cannot find anything on using php with
<input type="file" accept="image/*;capture=camera">
to store the image in a database. The database field is currently blob but this can change if needed.
The form works perfectly for all other data, so the issue is with my lack of understanding of how to handle images or files with php. can anyone help or point me in the right direction please. The basis of my code is pasted below.
The form save is working fine as the bus_name input saves to the database, but the bus_img record is blank.
HTML
<div data-role="page" id="view_record">
<div data-role="header">
Back
<div data-role="main" class="ui-content">
<form method="post" enctype="multipart/form-data" action="saveRecord.php">
<label for="bus_name">Business Name:</label>
<input type="text" name="bus_name" id="bus_name" placeholder="Enter Business Name">
<label for="bus_type">Business Type:</label>
<input type="text" name="bus_type" id="bus_type" placeholder="Enter Business Type">
<label for="bus_tel">Business Tel:</label>
<input type="text" name="bus_tel" id="bus_tel" placeholder="Enter Business Tel No">
<label for="bus_img">Business Photo:</label>
<input type="file" name="bus_img" id="bus_img" accept="image/*;capture=camera">
<label for="comments">Comments:</label>
<textarea name="comments" id="comments" placeholder="Enter Comments"></textarea>
<input type="submit" value="Submit">
</form>
</div>
</div>
</div>
PHP
<?php
$bus_img = $bus_name = "";
$servername = "";
$username = "";
$password = "";
$dbname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());}
$bus_img = $_FILES["bus_img"];
$bus_img = mysqli_real_escape_string($conn, $bus_img);
$bus_name = $_POST["bus_name"];
$sql = "INSERT INTO tblLead(leadImage, occupantName)
VALUES ('$bus_img','$bus_name')";
if (mysqli_query($conn, $sql))
{
} else
{
echo "Error: " . $sql . mysqli_error($conn);
}
mysqli_close($conn);
exit();
}
?>
ANy help much appreciated. Thanks
Firstly, file handling requires $_FILES and not $_POST.
Your form tag does not contain a proper enctype to handle files.
As per the manual's example on files handling:
<form enctype="multipart/form-data" action="__URL__" method="POST">
Reference:
http://php.net/manual/en/features.file-upload.post-method.php
Then you need to escape that (file) data and there are a few ways to do this.
One of which being mysqli_real_escape_string($conn, $file)
Reference:
http://php.net/manual/en/mysqli.real-escape-string.php
Something you should also be using against all your data as it is presently open to an SQL injection.
I.e. and by replacing:
$bus_img = $_POST["bus_img"];
with:
$bus_img = $_FILES["bus_img"];
$bus_img = mysqli_real_escape_string($conn, $bus_img);
And make sure that the file does not exceed the maximum uploaded size allowed/set on your server.
Use proper error checking also.
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
I want to allow a user the upload an image (file) for their profile picture, on my website. They upload the image via an HTML form, but I am having trouble moving the file to the folder I want it to. I don't want to mess with the php.ini file to change the upload path. I want to use move_uploaded_file(). I try and use $tmp= $_FILES['picture']['tmp_name'] and var_dump($tmp), but It keeps returning a value of (0). So, I think the problem has something to do with that. Here is my code,
Here is my HTML:
<form enctype="multipart/form-data" method="post" action="upload_img.php">
<input type="hidden" name="MAX_FILE_SIZE" value="32768"/>
<input type="text" name="name" value=""/>
<input type="file" name="picture" value="picture"/>
<input type="submit" name="submit" value="upload"/>
</form>
And my PHP:
<?php
define('GW_UPLOADPATH', 'images/');
$picture= $_FILES['picture']['name'];
$name= $_POST['name'];
$tmp= $_FILES['picture']['tmp_name'];
var_dump($picture);
var_dump($name);
var_dump($tmp);
$connect= mysqli_connect(//connect params)
or die('error connecting with the database');
$query= "INSERT INTO pics (pic, name) VALUES ('$picture', '$name')";
$target= GW_UPLOADPATH . $picture ;
if (move_uploaded_file($_FILES['picture']['tmp_name'], $target);))
{
mysqli_query($connect, $query)
or die('error with query');
}
?>
Your issue likely has something to do with php's upload_max_filesize and post_max_size. Check those 2 settings in your php.ini and make sure the file you are trying to upload isn't larger than either of them.
I know there's quite a few topics on this already, and I've read quite a few of them, but to no avail. I have a form for uploading multiple files with descriptions. If the user needs more than one upload/description field, they can click a link to add another via jquery. The code for the form is:
<form action="adm.php?mode=upload" method="post">
<input type="hidden" name="article_id" value="<?php echo $article_id; ?>" />
<input type="hidden" name="new_path" value="<?php echo $new_path; ?>" />
<div id="files">
<div id="file" class="row">
<input type="file" name="file[]" id="file" /><br />
Description:<br />
<textarea name="desc[]" cols="50" rows="5"></textarea>
</div>
</div>
<div>
<input type="submit" name="submit" value="Submit" />
</div>
</form>
Add File
A clone of
<div id="file" class="row">
<input type="file" name="file[]" id="file" /><br />
Description:<br />
<textarea name="desc[]" cols="50" rows="5"></textarea>
</div>
is appended to the files div when add_upload is clicked.
I believe this is correct usage of <input type="file" name="file[]" id="file" /> according to php.net, however the listener script at adm.php?mode=upload never receives the $_FILES array upon submission:
case 'upload' :
$path = request_var('new_path', '');
$article_id = request_var('article_id', 0);
$error = array();
$messages = array();
if(isset($_FILES['file']['tmp_name']))
{
// Number of uploaded files
$num_files = count($_FILES['file']['tmp_name']);
//create the directory if it doesn't exist already
if(!is_dir($path))
{
mkdir($path);
}
/** loop through the array of files ***/
for($i=0; $i < $num_files;$i++)
{
// check if there is a file in the array
if(!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
{
$messages[] = 'No file uploaded';
}
else
{
// copy the file to the specified dir
if(#copy($_FILES['file']['tmp_name'][$i],$path.'/'.$_FILES['file']['name'][$i]))
{
$messages[] = $_FILES['file']['name'][$i].' uploaded';
}
else
{
/*** an error message ***/
$messages[] = 'Uploading '.$_FILES['file']['name'][$i].' Failed';
}
}
}
}
else
{
$messages[] = 'No files set for upload??';
}
$err_msg = $messages;
include($root_path.'pages/header.php');
include($root_path.'pages/error.php');
include($root_path.'pages/column.php');
include($root_path.'pages/footer.php');
exit;
break;
I always get the "No files set for upload??" error because the files aren't being transferred. All of the other values are sent over POST and received with no problem. What am I doing wrong?
Your form declaration in HTML needs to have the enctype property set.
<form enctype="multipart/form-data">
Then use something like livehttpheaders for firefox to see if the data is actually going across. After you add that enctype, there should be something in the $_FILES array on the php side.
I'm using this form to add the title,link of the image and the text of the article to the database.
I'm using type="text" for the image link,now,it's getting borring to upload an image on a external image upload service and copy the link.
I want to upload the image with this for and store THE LINK of the image in the database.
The form:
<?php if (!$_POST["go"]){ ?>
<form method="post" action="">
<input name="article_title" type="text">
<input name="article_image_url" type="text"> <!-- i want here type="file" -->
<textarea name="article_text"></textarea>
<input type="submit" name="go" value="Submit">
</form>
<?php
} else {
$date=date("Y.m.d");
$title = $_POST["article_title"];
$image_url = $_POST["article_image_url"];
$text = $_POST["text"];
$sql="INSERT INTO articles (title,image_url,text,date) VALUES ('$title', '$image_url', '$text', '$date')";
if (mysql_query($sql)){
echo "done";}
else {echo "error<br>" . mysql_error();}}
?>
Please help me with this :)
ps:sorry for my English :$
The first thing you should do, and it seems you are clueless about SQL escaping, is add following before you access the first $_POST var:
$_POST = array_map("mysql_real_escape_string", $_POST);
Then you seemingly want to use a file upload for the image. If so change the url field to:
<input type=file name=image>
This uploaded file will show up in $_FILES. Use it like this, preferrably after you've read the other fields from $_POST:
if ($img = $_FILES["image"]["tmp_name"]) {
$image_url = md5_file($img) . ".jpeg";
move_uploaded_file($img, "./upload/$image_url");
$image_url = "http://www.example.org/where/$image_url";
}
There are lot's of security concerns with that. But that's out of scope here, so I hardwired it to .jpeg. There's lots of information in the manual and its comments: http://de2.php.net/manual/en/features.file-upload.php