multiple image upload how to make it? - php

I have a code which works fine if I want to upload one image into my MySQL and server.
PHP code:
if(isset($_POST['btnsave']))
{ foreach($_FILES['user_image']['tmp_name'] as $key => $tmp_name ){
$username = $_POST['user_name'];
$userjob = $_POST['user_job'];
$imgFile = $key.$_FILES['user_image']['name'][$key];
$tmp_dir = $_FILES['user_image']['tmp_name'][$key];
$imgSize = $_FILES['user_image']['size'][$key];
}
if(empty($username)){
$errMSG = "Please Enter Username.";
}
else if(empty($userjob)){
$errMSG = "Please Enter Your Job Work.";
}
else if(empty($imgFile)){
$errMSG = "Please Select Image File.";
}
else
{
$upload_dir = 'user_images/';
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
$userpic = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions)){
if($imgSize < 5000000) {
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else{
$errMSG = "Sorry, your file is too large.";
}
}
else{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
if(!isset($errMSG))
{
$stmt = $DB_con->prepare('INSERT INTO tbl_users(userName,userProfession,userPic) VALUES(:uname, :ujob, :upic)');
$stmt->bindParam(':uname',$username);
$stmt->bindParam(':ujob',$userjob);
$stmt->bindParam(':upic',$userpic);
if($stmt->execute())
{
$successMSG = "new record successfully inserted ...";
header("refresh:5;index.php");
}
else
{
$errMSG = "error while inserting....";
}
}
}
Html code:
<?php
if(isset($errMSG)){
?>
<div class="alert alert-danger">
<span class="glyphicon glyphicon-info-sign"></span> <strong><?php echo $errMSG; ?></strong>
</div>
<?php
}
else if(isset($successMSG)){
?>
<div class="alert alert-success">
<strong><span class="glyphicon glyphicon-info-sign"></span> <?php echo $successMSG; ?></strong>
</div>
<?php
}
?>
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<table class="table table-bordered table-responsive">
<tr>
<td><label class="control-label">Username.</label></td>
<td><input class="form-control" type="text" name="user_name" placeholder="Enter Username" value="<?php echo $username; ?>" /></td>
</tr>
<tr>
<td><label class="control-label">Profession(Job).</label></td>
<td><input class="form-control" type="text" name="user_job" placeholder="Your Profession" value="<?php echo $userjob; ?>" /></td>
</tr>
<tr>
<td><label class="control-label">Profile Img.</label></td>
<td><input class="input-group" type="file" name="user_image[]" accept="image/*" multiple /></td>
</tr>
<tr>
<td colspan="2"><button type="submit" name="btnsave" class="btn btn-default">
<span class="glyphicon glyphicon-save"></span> save
</button>
</td>
</tr>
</table>
</form>
How can I make it code to use for multiple upload? For all images which I would upload I would make the same values except 'userPic'- the same name for a file at my server. Can you help me out please?
I found one more problem! Maybe you guys can help me?
If I'm trying to upload for example 6 images, one of theme is bigger than maxsize its popups the error but every other files which was uploaded just before it went to upload folder. How to delete this files if i get an error?
second questions is how to resize images? any code?

Put everything inside the foreach block.
if(isset($_POST['btnsave']))
{ foreach($_FILES['user_image']['tmp_name'] as $key => $tmp_name ){
$username = $_POST['user_name'];
$userjob = $_POST['user_job'];
$imgFile = $key.$_FILES['user_image']['name'][$key];
$tmp_dir = $_FILES['user_image']['tmp_name'][$key];
$imgSize = $_FILES['user_image']['size'][$key];
if(empty($username)){
$errMSG = "Please Enter Username.";
}
else if(empty($userjob)){
$errMSG = "Please Enter Your Job Work.";
}
else if(empty($imgFile)){
$errMSG = "Please Select Image File.";
}
else
{
$upload_dir = 'user_images/';
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
$userpic = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions)){
if($imgSize < 5000000) {
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else{
$errMSG = "Sorry, your file is too large.";
}
}
else{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
if(!isset($errMSG))
{
$stmt = $DB_con->prepare('INSERT INTO tbl_users(userName,userProfession,userPic) VALUES(:uname, :ujob, :upic)');
$stmt->bindParam(':uname',$username);
$stmt->bindParam(':ujob',$userjob);
$stmt->bindParam(':upic',$userpic);
if($stmt->execute())
{
$successMSG = "new record succesfully inserted ...";
header("refresh:5;index.php");
}
else
{
$errMSG = "error while inserting....";
}
}
}}

Related

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.

Uncaught PDOException

When I run the following code I get this error:
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\xampp\htdocs\pizda\aids\admin\addnew.php:73 Stack trace: #0
on line 73
<?php
error_reporting( ~E_NOTICE ); // avoid notice
require_once 'dbconfig.php';
if(isset($_POST['btnsave']))
{
$NaslovSrpski = $_POST['NaslovSrpski'];
$NaslovEngleski = $_POST['NaslovEngleski'];
$TekstSrpski = $_POST['TekstSrpski'];
$TekstEngleski = $_POST['TekstEngleski'];
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if(empty($NaslovSrpski)){
$errMSG = "Please Enter Username.";
}
else if(empty($NaslovEngleski)){
$errMSG = "Please Enter Your Job Work.";
}
else if(empty($TekstSrpski)){
$errMSG = "Please Enter Your Job Work.";
}
else if(empty($TekstEngleski)){
$errMSG = "Please Enter Your Job Work.";
}
else if(empty($imgFile)){
$errMSG = "Please Select Image File.";
}
else
{
$upload_dir = '../uploads/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
// rename uploading image
$userpic = rand(1000,1000000).".".$imgExt;
// allow valid image file formats
if(in_array($imgExt, $valid_extensions)){
// Check file size '5MB'
if($imgSize < 5000000) {
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else{
$errMSG = "Sorry, your file is too large.";
}
}
else{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
// if no error occured, continue ....
if(!isset($errMSG))
{
$stmt = $DB_con->prepare('INSERT INTO Obavestenja(NaslovSrpski,NaslovEngleski,TekstSrpski,TekstEngleski, Slika) VALUES(:naslovs, :naslove, :teksts, tekste, :upic)');
$stmt->bindParam(':naslovs',$NaslovSrpski);
$stmt->bindParam(':naslove',$NaslovEngleski);
$stmt->bindParam(':teksts',$TekstSrpski);
$stmt->bindParam(':tekste',$TekstEngleski);
$stmt->bindParam(':upic',$userpic);
if($stmt->execute())
{
$successMSG = "new record succesfully inserted ...";
header("refresh:5;index.php"); // redirects image view page after 5 seconds.
}
else
{
$errMSG = "error while inserting....";
}
}
}
include 'header.php';
?>
<div class="container">
<div class="page-header">
<h1 class="h2">add news. <a class="btn btn-default" href="index.php"> <span class="glyphicon glyphicon-eye-open"></span> view all </a></h1>
</div>
<?php
if(isset($errMSG)){
?>
<div class="alert alert-danger">
<span class="glyphicon glyphicon-info-sign"></span> <strong><?php echo $errMSG; ?></strong>
</div>
<?php
}
else if(isset($successMSG)){
?>
<div class="alert alert-success">
<strong><span class="glyphicon glyphicon-info-sign"></span> <?php echo $successMSG; ?></strong>
</div>
<?php
}
?>
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<table class="table table-bordered table-responsive">
<tr>
<td><label class="control-label">NaslovSrpski</label></td>
<td><input class="form-control" type="text" name="NaslovSrpski" placeholder="NaslovSrpski" value="<?php echo $NaslovSrpski; ?>" /></td>
</tr>
<tr>
<td><label class="control-label">NaslovEngleski</label></td>
<td><input class="form-control" type="text" name="NaslovEngleski" placeholder="NaslovEngleski" value="<?php echo $NaslovEngleski; ?>" /></td>
</tr>
<tr>
<td><label class="control-label">TekstSrpski</label></td>
<td><textarea class="form-control" type="text" name="TekstSrpski" placeholder="TekstSrpski" value="<?php echo $TekstSrpski; ?>" /></textarea></td>
</tr>
<tr>
<td><label class="control-label">TekstEngleski</label></td>
<td><textarea class="form-control" type="text" name="TekstEngleski" placeholder="TekstEngleski" value="<?php echo $TekstEngleski; ?>" /></textarea></td>
</tr>
<tr>
<td><label class="control-label">Profile Img.</label></td>
<td><input class="input-group" type="file" name="user_image" accept="image/*" /></td>
</tr>
<tr>
<td colspan="2"><button type="submit" name="btnsave" class="btn btn-default">
<span class="glyphicon glyphicon-save"></span> save
</button>
</td>
</tr>
</table>
</form>
You're missing a ":" in tekste's placeholder:
$stmt = $DB_con->prepare
('INSERT INTO Obavestenja' .
' (NaslovSrpski,NaslovEngleski,TekstSrpski,TekstEngleski, Slika)' .
' VALUES (:naslovs, :naslove, :teksts, :tekste, :upic)');
# ":" was missing here ----------------^

How to upload multiple images with php and sql

I can upload one image at a time with my code, however it I have added multiple="multiple" and it lets me highlight more than one image to upload but only one image gets uploaded to the sql database.
Here is my form below -
<form action="upload_image.php" method="post" enctype="multipart/form-data">
<p>Select files:<br /><input type="file" name="image[]" multiple="multiple"/></p>
<p>
Choose an album<br />
<select name="album_id">
<?php
foreach ($albums as $album) {
echo '<option value="', $album['id'], '">', $album['name'], '</option>';
}
?>
</select>
</p>
<p><input type="submit" value="Upload" /></p>
</form>
and my PHP side looks like this -
<?php
if (isset($_FILES['image'], $_POST['album_id'])) {
$image_name = $_FILES['image']['name'];
$image_size = $_FILES['image']['size'];
$image_temp = $_FILES['image']['tmp_name'];
$image_dimension = $_FILES['image']['dimension'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$image_ext = strtolower(end(explode('.', $image_name)));
$album_id = $_POST['album_id'];
$errors = array();
if (empty($image_name) || empty($album_id)) {
$errors[] = 'Something is missing';
} else {
if (in_array($image_ext, $allowed_ext) === false) {
$errors[] = 'File type not allowed';
}
if($image_size > 10485760){
$errors[] = 'Maximum file size is 10MB';
}
if (album_check($album_id) === false) {
$errors[] = 'Couldn\'t upload to that album';
}
}
if (!empty($errors)) {
foreach ($errors as $error) {
echo $error, '<br />';
}
} else {
upload_image($image_temp, $image_ext, $album_id);
header('Location: view_album.php?album_id='.$album_id);
exit();
}
}
Any help on this would be amazing!
Regards
Aaron

How to make the code continue the process if the file upload section is empty PHP MYSQLi

I have a problem with 1 part of upload section, how to make the code continue the process if the upload section is empty? I already make the code, but everytime i skip the file button, it show echo 'ERROR: Ekstensi file tidak di izinkan!'
Here is my code:
insert_form
<form name="pegawai" action="insert-proses.php" method="post" enctype="multipart/form-data">
<table width="700px" align="left" cellpadding="2" cellspacing="0">
<tr>
<td><b>NOKOM</b></td>
<td><b>:</b></td>
<td><input type="text" name="nokom" size="40" required /></td>
</tr>
<tr>
<td><b>NIP</b></td>
<td><b>:</b></td>
<td><input type="text" name="nip" size="40" required /></td>
</tr>
<tr>
<td><b>Nama</b></td>
<td><b>:</b></td>
<td><input type="text" name="nama" size="40" required /></td>
</tr>
<tr>
<td><b>Foto</b></td>
<td><b>:</b></td>
<td><input name="file" type="file" id="file" /></td>
</tr>
<tr>
<td></td>
<td></td>
<td><hr/><input type="submit" name="upload" value="Upload" /></td>
</tr>
</table>
</form>
insert-proses
<?php session_start();
include "config.php";
if(ISSET($_SESSION['superadmin'])) {
if($_POST['upload']) {
$nokom = $_POST['nokom'];
$nip = $_POST['nip'];
$nama = $_POST['nama'];
// Proses upload file
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $_FILES['file']['name']; // Nama File
$file_ext = strtolower(end(explode('.', $file_name))); // Merubah nama file
$file_size = $_FILES['file']['size']; // Size File
$file_tmp = $_FILES['file']['tmp_name']; // Temp File
// Proses pengecekan upload file
if(in_array($file_ext, $allowed_ext) === true) {
if($file_size < 5220350) // Max upload file 5 MB / 1MB = 1044070 {
$lokasi = 'files/'.$nama.'.'.$file_ext;
move_uploaded_file($file_tmp, $lokasi);
$sql = "INSERT INTO pegawai (nokom,nip,nama,fileext,filegambar)
VALUES('$nokom','$nip','$nama','$file_ext','$lokasi')";
if (mysqli_query($conn, $sql)) {
echo "<script>alert('Insert data berhasil! Klik ok untuk melanjutkan');location.replace('pegawai-list.php')</script>";
}
else {
echo "Error updating record: " . mysqli_error($conn);
}
} else
{
echo '<div class="error">ERROR: Besar ukuran file (file size) maksimal 1 Mb!</div>';
}
} else
{
echo '<div class="error">ERROR: Ekstensi file tidak di izinkan!</div>';
}
}
} else
{
echo '<script>alert("Anda bukan Superadmin! Silahkan login menjadi Superadminterlebih dahulu");location.replace("index.php")</script>';
}
?>
Any help will be so thankful. Thanks
Jump over the complete upload part if there is no file uploaded, or better, run the upload part in your script only IF a file is uploaded:
if(isset($_FILES['file']) && is_array($_FILES['file'])) {
// your code to upload and check the file
}

image uploading errors

So I have this issue with my errors not showing up when I test to see if they are showing up when they are supposed to. When I select an file, my script is only supposed to accept image files as well as nothing bigger than 2MB. I haven't written the part that actually uploads the images to the database and the albums that I created but regardless, I should get some sort of error instead of just passing anything through..I need help! Thanks in advance!
Here is the file that processes the image and will eventually upload:
<?php
include 'init.php';
if(!logged_in()){
header('Location: index.php');
exit();
}
include 'template/header.php';
?>
<h3>Upload Image</h3>
<?php
if(isset($FILES['image'], $_POST['album_id'])){
$image_name = $_FILES['image']['name'];
$image_size = $_FILES['image']['size'];
$image_temp = $_FILES['image']['tmp_name'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$image_ext = strtolower(end(explode('.', $image_name)));
$album_id = $_POST['album_id'];
$errors = array();
if (empty($image_name) || empty($album_id)){
$errors[] = 'Something is missing';
} else {
if(in_array($image_ext, $allowed_ext) === false){
$errors[] = 'File type not allowed';
}
if($image_size > 2097152){
$errors[] = 'Maximum file size is 2MB';
}
if(album_check($album_id) === false){
$errors[] = 'Couldn\'t upload to that album';
}
}
if(!empty($errors)){
foreach ($errors as $error){
echo $error, '<br />';
}
} else {
// upload image
}
}
$albums = get_albums();
if(empty($albums)){
echo '<p>You don\'t have any albums. Create an album</p>';
} else {
?>
<form action="" method="post" enctype="multipart/form-data">
<p>Choose a file:<br /><input type="file" name="image" /></p>
<p>
Choose an album:<br />
<select name="album_id">
<?php
foreach ($albums as $album){
echo '<option value="', $album['id'], '">', $album['name'], '</option>';
}
?>
</select>
</p>
<p><input type="submit" value="Upload" /></p>
</form>
<?php
}
include 'template/footer.php';
?>
I think my issue is around my errors but I'm not sure, again any help is appreciated! Thanks!
-TechGuy24
Change if(isset($FILES['image'], $_POST['album_id'])){
To if(isset($_FILES['image'], $_POST['album_id'])){

Categories