So the main problem is that I can't seem to move the images to my designated folder. I have this database that records the name and directory. It seems to work well. It's only the images that fail to move to the folder.
Here's the HTML code:
<div class="form-group" align="left">
<label for="aialbum">Album:</label>
<select class="form-control" id="aialbum" name="aialbum">
<?php
$query = "SELECT * FROM cms_albums";
$showalbums = mysqli_query($con, $query);
while($getalbum = mysqli_fetch_array($showalbums))
{
$album = $getalbum['album_name'];
echo "<option value='$album'>$album</option>";
}
?>
</select>
<br><label for="aipicture">Image/s:</label>
<div class="form-group">
<input type='file' name='aipicture[]' id='aipicture[]' multiple>
</div>
</div>
<div align="right">
<input class="btn btn-default" type='submit' name='aisubmit' value='Submit'>
</div>
Here's my PHP code: (Update)
if(isset($_POST['aisubmit']))
{
$aialbum = $_POST['aialbum'];
$aipicture = $_POST['aipicture'];
$filecount = count($aipicture);
for($i=0; $i<$filecount; $i++)
{
$temp_name = $_FILES[$aipicture[$i]]['tmp_name'];
$org_name = $_FILES[$aipicture[$i]]['name'];
$path = "../img";
move_uploaded_file($temp_name, $path);
$sql = "INSERT INTO cms_album_photos (album_name, picture) VALUES ('$aialbum', 'img/$aipicture[$i]')";
mysqli_query($con, $sql);
}
echo '<script type="text/javascript">';
echo 'window.location.href="home.php";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url=home.php" />';
echo '</noscript>'; exit;
}
Do like this
$target_Path = "asd/".basename( $_FILES['fileToUpload']['name']);
move_uploaded_file( $_FILES['fileToUpload']['tmp_name'], $target_Path );
improve your code from this
$temp_name = $_FILES[$aipicture[$i]]['tmp_name'];
$org_name = $_FILES[$aipicture[$i]]['name'];
To this
$temp_name = $_FILES[$aipicture]['tmp_name'][$i];
$org_name = $_FILES[$aipicture]['name'][$i];
Hope this help!
Related
On my website, I have a form which allows the user to modify a selected item. As a part of this modification, they are allowed the upload (or delete) images associated with the item.
It seems that very specific images are causing my form to not post (I make this assumption because the loading indicator for my browser is pending).
From further inspection, although it does create a file, it's size is 0B. This is concurrent with the fact that the output of $_FILE['tree-photos']['size'][0] is 0. It seems that the image isn't even being attempted to be uploaded as a specific error code is not given by $_FILE['tree-photos']['error'][0] (returns 0).
I have changed all the appropriate file permissions required and the upload_max_size and post_max_size values accordingly. Interestingly, other files from the same folder which follow the exact same naming scheme and are larger upload fine. It seems random which photos trigger the form to not submit, but it is consistent what images do and don't submit.
File extensions are not the problem either, they are consistient.
Here is my code (I have been told off before for not posting all my code so sorry if a lot of it is not required):
<?php
include("../content/head.php");
include("../functions.php");
if (!isset($_SESSION['admin'])) {
header("Location: ../admin/admin.php?page=login");
exit();
}
$id = $_REQUEST['treeID'];
$tree_sql = "SELECT * FROM trees WHERE treeID=" . $id;
$tree_query = mysqli_query($dbconnect, $tree_sql);
$tree_rs = mysqli_fetch_assoc($tree_query);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$com_name = test_input($_POST['com_name']);
$sci_name = test_input($_POST['sci_name']);
$height = test_input($_POST['height']);
$origin = test_input($_POST['origin']);
$description = test_input($_POST['description']);
$type = test_input($_POST['type']);
if(isset($_FILES['tree-photos']['name'][0])) {
if (!empty($_FILES['tree-photos']['name'][0])) {
for ($i = 0; $i < count($_FILES['tree-photos']['name']); $i++) {
$location = '../images/' . $sci_name .'/' . $sci_name . "_" . uniqid() . "." . strtolower(pathinfo($_FILES['tree-photos']['name'][$i], PATHINFO_EXTENSION));
move_uploaded_file($_FILES['tree-photos']['tmp_name'][$i], $location);
}
}
}
if ($tree_rs["photo"] == "noimage") {
$updatesql = "UPDATE trees SET photo='$sci_name' WHERE treeID=".$id;
}
$_SESSION['err'] = $_FILES['tree-photos']['error'][0];
$updatesql = "UPDATE trees SET com_name='$com_name', sci_name='$sci_name', height='$height', origin='$origin', description='$description', type='$type' WHERE treeID=".$id;
$updatequery = mysqli_query($dbconnect, $updatesql);
}
$tree_sql = "SELECT * FROM trees WHERE treeID=" . $id;
$tree_query = mysqli_query($dbconnect, $tree_sql);
$tree_rs = mysqli_fetch_assoc($tree_query);
include("../content/navigation.php");
?>
<div id="main-container">
Back
<h1><?php echo $_SESSION['err']; ?></h1>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])."?treeID=".$id;?>" method="post" enctype="multipart/form-data">
<p>Common Name</p>
<input name="com_name" type="text" value="<?php echo $tree_rs['com_name']; ?>">
<p>Scientific Name</p>
<input name="sci_name" type="text" value="<?php echo $tree_rs['sci_name']; ?>">
<p>Height Name</p>
<input name="height" type="number" value="<?php echo $tree_rs['height']; ?>">
<p>Origin</p>
<input name="origin" type="text" value="<?php echo $tree_rs['origin']; ?>">
<p>Type</p>
<select name="type">
<option value="Deciduous">Deciduous</option>
<option value="Evergreen">Evergreen</option>
</select>
<p>Description</p>
<textarea name="description"><?php echo $tree_rs['description']; ?></textarea>
<p>Add Photos</p>
<input name="tree-photos[]" type="file" multiple>
<?php $tree_rs['photo']; ?>
<?php
if ($tree_rs['photo'] != "noimage") { ?>
<div class="edit-images-container"> <?php
$path = "../images/".$tree_rs['photo']."/";
$images = glob("$path*.{jpg,jpeg,png,gif,bmp}", GLOB_BRACE);
foreach($images as $image) { ?>
<div class="image-editable-container">
<img class="editable-image" data-source="<?php echo $tree_rs['sci_name']; ?>" data-id="<?php echo $tree_rs["treeID"]; ?>" src="<?php echo $image?>" alt="<?php echo $tree_rs['com_name'] . " - " . $tree_rs['description']; ?>">
<img class="editable-image-delete" src="../images/delete.svg" alt="Delete Button">
</div>
<?php } ?> </div> <?php
} else { ?>
<p>No Images Currently</p>
<?php }
?>
<input type="submit" value="Submit">
</form>
</div>
<?php include("../content/footer.php"); ?
Edit: Included some images that work and don't work for me, would be interesting if its the same for you.
Edit 2: It seems that after restarting the server I am able to upload around 15 items, including ones I couldn't before. After that, though new random images are un-uploadable. This might be a config issue.
I have a form with uploading multiple files.
When I upload let's say two images and when I click submit, the images are displayed properly, but when I edit some other input and click submit button, the images are gone.
Here's my code:
<?php
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT * FROM posts WHERE id = $id";
$result = $db->query($query);
while($row = $db->fetch_object($result)) {
$id = $row->id;
$title = $row->title;
$body = $row->body;
$status = $row->status;
}
if(isset($_POST['submit'])) {
$title = $_POST['title'];
$body = $_POST['body'];
$image = $_POST['image'];
$status = $_POST['status'];
//if($_FILES['image']['tmp_name']) {
if(!empty($_FILES['image']['name'])) { //Edit
// delete old image
$query = "SELECT * FROM postimage WHERE post_id = $id";
$select_image = $db->query($query);
while($row = $db->fetch_object($select_image)) {
$old = $row->filename;
unlink('../uploads/' . $old);
}
$query = "DELETE FROM postimage WHERE post_id = $id";
$delete_images = $db->query($query);
foreach($_FILES['image']['tmp_name'] as $key => $tmp_name) {
$filename = rand(100,999)."-".$_FILES['image']['name'][$key];
$filetmp = $_FILES['image']['tmp_name'][$key];
if(move_uploaded_file($filetmp, '../uploads/' . $filename)) {
$query = "INSERT INTO postimage(post_id, filename) ";
$query .= "VALUES($id, '$filename')";
$insert_images = $db->query($query);
}
}
}
$query = "UPDATE posts SET ";
$query .= "title = '$title', ";
$query .= "body = '$body', ";
$query .= "status = '$status', ";
$query .= "updated = now() ";
$query .= "WHERE id = $id ";
$update_post = $db->query($query);
//header("Location: posts.php");
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-item">
<label for="title">Post title</label>
<input type="text" value="<?php echo $title; ?>" name="title">
</div>
<div class="form-item">
<label for="body">Post body</label>
<textarea id="editor" name="body" rows="10" cols="30"><?php echo $body; ?></textarea>
</div>
<div class="form-item">
<label for="image">Image</label>
<?php
$query = "SELECT * FROM postimage WHERE post_id = $id";
$select_image = $db->query($query);
while($row = $db->fetch_object($select_image)) {
$filename = $row->filename;
echo '<img width="100" height="70" src="../uploads/' . $filename . '">';
}
?>
<input type="file" name="image[]" multiple>
</div>
<div class="form-item">
<label for="status">Post status</label>
<select name="status">
<option value="<?php echo $status; ?>"><?php echo $status; ?></option>
<?php
if($status == 'published') {
echo '<option value="draft">draft</option>';
} else {
echo '<option value="published">published</option>';
}
?>
</select>
</div>
<div class="form-item">
<input type="submit" class="form-submit" name="submit" value="Update post">
</div>
</form>
When I'm using simple form with uploading a single image and connects with only one table, I usually fix that problem with this:
if(empty($image)) {
$query = "SELECT * FROM posts WHERE id = $id";
$result = $db->query($query);
while($row = $db->fetch_object($result)) {
$image = $row->image;
}
}
How can I solve this problem using multiple upload input?
EDITED: change it to
if(!empty($_FILES['image']['name']))
because $_FILES['image']['tmp_name'] always return path to temp so jou cannot test it for empty
I've solved the problem.
When using multiple file upload, the if statement has to be changed, so in this case it should be: if(!empty($_FILES['image']['tmp_name'][0]))
I've got this upload form and would like to keep the selected option from the dropdown in the session in order to show the last selection after submitting, e.g. i choose the option 'colour' und after submitting colour is still selected in the dropdown.
I echo $_SESSION['testname'] (just before the first radio button) and it gives me back "colour", but in the option-tag where i'd like to echo 'selected' if "colour" was the last selection, it returns nothing! what am i missing?
<?php
session_start();
if(isset($_POST['kategorie'])) {
$_SESSION['testname']=$_POST['kategorie']; }
?>
<?php
$con = mysqli_connect("localhost","Melvin","") or die ("could not connect to server: " . mysqli_connect_error($con));
mysqli_select_db($con, "galerie") or die ("Could not connect to database: " . mysqli_error($con));
if(isset($_POST['submit'])){
$name = $_FILES['file']['name'];
$sub_name = substr($name, 0, -4);
$img_ext = ".jpg";
$tmp_name = $_FILES['file']['tmp_name'];
$location = '_images/_galerie/';
$target = '_images/_galerie/' .$name;
if(move_uploaded_file($tmp_name,$location.$name)){
echo "file uploaded";
$nam = $_POST['nam'];
$kategorie = $_POST['kategorie'];
$size = $_POST['size'];
if ($size == 'thumb') {
// add "thumb" between filename and extension
$extension_pos = strrpos($target, '.'); // find position of the last dot, so where the extension starts
$thumb = substr($target, 0, $extension_pos) . '_thumb' . substr($target, $extension_pos);
$query = mysqli_query($con , "INSERT INTO images(img_name,img_title,img_cat,img_size)VALUES('".$thumb."','$nam','$kategorie','$size')");
} else {
$query = mysqli_query($con , "INSERT INTO images(img_name,img_title,img_cat,img_size)VALUES('".$target."','$nam','$kategorie','$size')");
}
function renameImg() {
$name = $_FILES['file']['name'];
$target = '_images/_galerie/' .$name;
$extension_pos = strrpos($target, '.');
$thumb = substr($target, 0, $extension_pos) . '_thumb' . substr($target, $extension_pos);
rename($target, $thumb);
//echo $name . " replaced with " . $thumb;
};
renameImg();
} else {
echo "file not uploaded";
}
}
?>
<div style="margin:20px 0 40px 0;">
<form action="upload.php" method="POST" enctype="multipart/form-data">
Upload: <input type="file" name="file">
Title: <input type="text" name="nam" value="Tattoo Gallery">
Category: <select name="kategorie" id="selectKat">
<option value="black" <?php if(isset($_SESSION['kategorie']) == "black") { echo ' selected';} ?>>Black and white</option>
<option value="colour" <?php if(isset($_SESSION['kategorie']) == "colour") { echo ' selected';} ?>>Colour</option>
</select>
<br>
<?php
echo $_SESSION['testname'];
?>
<input type="radio" name="size" value="full" id="regularRadio" checked="checked">
<label for="regularRadio">Full size</label>
<br>
<input type="radio" name="size" value="thumb" id="thumbRadio">
<label for="thumbRadio">Thumbnail</label>
<br>
<input type="submit" name="submit">
</form>
</div>
<?php
$result = mysqli_query($con, "SELECT * FROM images WHERE img_size='thumb'");
while($row = mysqli_fetch_array($result)){
echo "<img src=".$row['img_name'] . " class='thumbnails' style='display:inline;float:left;'>";
}
?>
You must not use the isset() function. This function return True or False.
You only have to compare the value of $_POST['kategorie'] or $_SESSION['testname'] (as I see) with your text ("color" or "black"), like this :
if ($_SESSION['kategorie'] == "black") { echo ' selected'; }
I'm sorry if this is a repost. But I have seen many questions without finding the right answer
i'm trying to upload multiple files + some information , but if i submit my form with 2 images it goes ok and the script runs perfect when i upload more then 2 or 3 files i get undefined indexs of all the form elements .
up.php
/////// Random name generator ////////
function random_name($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
//sql//
require("sql.php");
//////////
//!!! some vars !!!//
//
$total = count($_FILES['pimages']['name']);
//
$foldername = random_name(15);
$target_dir = "../images/projects/".$foldername."/";
$target_file = $target_dir . basename($_FILES["icon"]["name"]);
$uploadyes = 1;
$imageType = pathinfo($target_file,PATHINFO_EXTENSION);
$saveicon = $target_dir . "icon." .$imageType;
/////submited form vars /////
$linkedid = $_POST['lid'];
$date = date("y.m.d H:i:s");
$name = $_POST['projectname'];
$loc = $_POST['location'];
$type = $_POST['type'];
$des = $_POST['des'];
$precara = $_POST['cara'];
$client = $_POST['client'];
$col = $_POST['cost'];
$bua = $_POST['builtup'];
////////////////cara slice /////////////
$caraxarray = explode("," , $precara);
$cara = base64_encode(serialize($caraxarray));
echo $imageType ;
///////////////////////// Start of the upload check ////////////////////
if(isset($_POST['submit']) && !empty($name)) {
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
}
// Check if $uploadyes is set to 0 by an error
if (!isset($_POST['submit'])) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
mkdir($target_dir);
if (move_uploaded_file($_FILES["icon"]["tmp_name"], $saveicon)) {
//////////////////////////..........................//////////////////
// Loop through each file
$imgext = array();
for($i=0; $i<=$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['pimages']['tmp_name'][$i];
$x = $i + 1 ;
if ($tmpFilePath != ""){
//Setup our new file path
$pimgex = $_FILES['pimages']['name'][$i];
$pimageType = pathinfo($pimgex,PATHINFO_EXTENSION);
$newFilePath = $target_dir ."img".$x.".".$pimageType;
array_push($imgext , "$newFilePath");
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo "yeaaaaaah";
}
}
}
$str = serialize($imgext);
$sql1 = "INSERT INTO projects (date, name, type, location, icon, imgext, folder, linkedid)
VALUES ('$date', '$name','$type', '$loc', '$saveicon' , '$str', '$foldername', '$linkedid')";
$sql2 = "INSERT INTO projectdetails (proname, prolocation, prodes, procara, client, col, builtarea, linkedid)
VALUES ('$name', '$loc','$des', '$cara', '$client' , '$col', '$bua', '$linkedid')";
mysqli_query($conn ,$sql1);
mysqli_query($conn ,$sql2);
mysqli_close($conn);
/////////////////...........................////////////////////////
header("location:cp.php");
} else {
echo "Sorry, there was an error uploading your file.";
}
}
projectsuploader.php
$lkid = random_name(8);
$tlink = random_name(6);
require("sql.php");
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql1 = "SELECT id, date, name, type, location FROM projects";
$sql2 = "SELECT id, titleen FROM projectsnav";
$result = mysqli_query($conn, $sql1);
$types = mysqli_query($conn, $sql2);
//mysqli_close($conn);
?>
<!DOCTYPE html>
<html>
<h2>Projects Page</h2>
<h5>projects</h5>
<table>
<tr>
<td>#</td>
<td>Date & Time</td>
<td>Project name</td>
<td>Project type</td>
<td>Project location</td>
<!--<td>View</td>
<td>Edit</td>-->
<td>Remove</td>
</tr>
<?php
if (mysqli_num_rows($result) > 0) {
// output data of each row .$row["id"]
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row["id"]."</td>";
echo "<td>".$row["date"]."</td>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["type"]."</td>";
echo "<td>".$row["location"]."</td>";
echo "<td><a href='../del.php?id=".$row['id']."'>Remove</a></td> </tr>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</table>
<h4 id="addproject">Add Project</h3>
<h4 id="addtype">Add Type </h4>
<div id="frontlayer">
<div id="addpro">
<h2 style="text-align:center;"> add project </h2>
<form method="POST" action="up.php" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="50000000">
id:<input type="text" name="lid" value="<?php echo $lkid ; ?>" readonly> <br>
project name:<input type="text" name="projectname"><br>
Type:<select name="type">
<?php
if (mysqli_num_rows($types) > 0){
while($navrow = mysqli_fetch_assoc($types)) {
echo "<option value='".$navrow['titleen']."'>".$navrow['titleen']." </option>";
}
}else{
echo "<option>PLEASE ADD TYPES TO DATABASE FIRST!!!!ERROR 0 TYPES IN DATABASE</option>";
}
mysqli_close($conn);
?>
</select>
<br>
location:<input type="text" name="location"><br>
icon:<input type="file" name="icon" id="icon"><br>
images:<input type="file" name="pimages[]" id="pimages" multiple><br>
<input type="hidden" name="sendfiles" value="Send Files" />
<!--
------//////////////------
------//////////////------
------//////////////------
-->
description:<input type="text" name="des"><br>
caracteristic:<input type="text" name="cara" data-role="tagsinput"><br>
client:<input type="text" name="client"><br>
Collaborator:<input type="text" name="cost"><br>
Gross Area:<input type="text" name="builtup"><br>
<input type="submit" value="Upload" name="submit">
</form>
</div>
Sorry if it is bad writed i\m begginer , Thanks in advance for anyhelp
The problem were that there was a big file (4mb image) and php was not able to post this size of an image so you have to resize your image before upload ..
and big thanks for Felippe Duarte.
Can anyone help me with this, i have checked the SQL table names multiple times but every time i attempt to post it gives me an error. Pretty new to this. Thanks in advance.
require_once('connect.php');
if (isset($_POST['add_product'])):
$product_description=$_POST['product_description'];
$price=$_POST['price'];
$reorder_level=$_POST['reorder_level'];
$current_level=$_POST['current_level'];
$imagename = $_FILES['image']['name'];
$add_this = "products/$imagename";
move_uploaded_file($_FILES['image']['tmp_name'],$add_this);
$my_query="INSERT INTO products VALUES ('','$product_description','$price','$reorder_level','$current_level', '$imagename')";
$result= mysqli_query($connection, $my_query);
if ($result):
echo "<b>Item Successfully Added!</b>";
echo "File ";
echo $_FILES['image']['name'];
echo " was uploaded - ";
echo $_FILES['image']['size'];
echo " bytes in size<br>Temporary name: ";
echo $_FILES['image']['tmp_name'];
echo " - file type: ";
echo $_FILES['image']['type'];
else:
echo "<b>ERROR: unable to post.</b>";
endif;
endif;
require_once 'header1.php';
?>
Here is the form im using
<H1>Add a New Product</H1>
<table>
<form method=post action="addproduct.php" enctype="multipart/form-data">
<tr><td><b>Product Description:</b><td><input type="text" name="product_description" size="30">
<tr><td><b>Price:</b><td><input type="text" name="price">
<tr><td><b>Re Order Level:</b><td><input type="text" name="reorder_level">
<tr><td><b>Stock Level:</b><td><input type="text" name="current_level">
<tr><td><b>Add Image:</b><td><input type="file" name="image">
<tr><td><input type="submit" name="add_product" >
</form>
</table>
</body>
<?php
require_once('connect.php');
$mysql = new MYSQLI("host", "username", "password", "database");
if (isset($_POST['add_product'])):
$product_description = $_POST['product_description'];
$price = $_POST['price'];
$reorder_level = $_POST['reorder_level'];
$current_level = $_POST['current_level'];
$imagename = $_FILES['image']['name'];
$add_this = "products/$imagename";
move_uploaded_file($_FILES['image']['tmp_name'],$add_this);
$mysql->query("INSERT INTO products (`NAME OF CELL IN TABLE WHERE YOU WANT SAVE0 $product_description`, `NAME OF CELL IN TABLE WHERE YOU WANT SAVE $price`, `NAME OF CELL IN TABLE WHERE YOU WANT SAVE $reorder_level`, `NAME OF CELL IN TABLE WHERE YOU WANT SAVE $current_level`, `NAME OF CELL IN TABLE WHERE YOU WANT SAVE $imagename`) VALUES ('{$product_description}', '{$price}', '{reorder_level}', '{$current_level}', '{$imagename}')");
if ($result) {
echo "<b>Item Successfully Added!</b>";
echo "File ";
echo $_FILES['image']['name'];
echo " was uploaded - ";
echo $_FILES['image']['size'];
echo " bytes in size<br>Temporary name: ";
echo $_FILES['image']['tmp_name'];
echo " - file type: ";
echo $_FILES['image']['type'];
}
else {
echo "<b>ERROR: unable to post.</b>";
}
require_once('header1.php');
?>
Try this, but set your information on line 3 ($mysql)
and on line 15 ($mysql->query).