I am trying to upload 3 separate images to upload on the server using. the code doesn't throw any error but only 1st image gets uploaded. The other two images are not uploaded on the server but Its name gets inserted into the database.
here is my code to upload the images:
<?php
include("common_code.php");
include("database_connection.php");
$property_id = $_POST['id'];
if (!$_FILES['file1']['size'] == 0) {
$temp = explode(".", $_FILES["file1"]["name"]);
$extension = end($temp);
$fileName1= mt_rand(). "_". time(). "." .$extension;
$image_tmp_name = $_FILES['file1']['tmp_name'];
$folder = "images/property_images/";
$folder = $folder . $fileName1;
move_uploaded_file($image_tmp_name, $folder);
$uploadQuery = "INSERT INTO property_photos (filenames,property_id) VALUES ('$folder','$property_id')";
$run = mysqli_query($connection, $uploadQuery);
}
if (!$_FILES['file2']['size'] == 0) {
$temp2 = explode(".", $_FILES["file2"]["name"]);
$extension2 = end($temp2);
$fileName2= mt_rand(). "_". time(). "." .$extension2;
$image_tmp_name = $_FILES['file2']['tmp_name'];
$folder2 = "images/property_images/";
$folder2 = $folder2 . $fileName2;
move_uploaded_file($image_tmp_name2, $folder2);
$uploadQuery2 = "INSERT INTO property_photos (filenames,property_id) VALUES ('$folder2','$property_id')";
$run2 = mysqli_query($connection, $uploadQuery2);
}
if (!$_FILES['file3']['size'] == 0) {
$temp3 = explode(".", $_FILES["file3"]["name"]);
$extension3 = end($temp3);
$fileName3= mt_rand(). "_". time(). "." .$extension3;
$image_tmp_name = $_FILES['file3']['tmp_name'];
$folder3 = "images/property_images/";
$folder3 = $folder3 . $fileName3;
move_uploaded_file($image_tmp_name3, $folder3);
$uploadQuery3 = "INSERT INTO property_photos (filenames,property_id) VALUES ('$folder3','$property_id')";
$run3 = mysqli_query($connection, $uploadQuery3);
}
header("Location:property_reg_successful.php?id=$property_id");
Only file1 gets uploaded into a server!
file2 and file3 not uploaded.
You've just got a simple variable-naming error:
$image_tmp_name = $_FILES['file2']['tmp_name'];
[...]
move_uploaded_file($image_tmp_name2, $folder2);
Note the different variable names "$image_tmp_name" and "$image_tmp_name2".
Related
I have searched far and wide and cannot find an answer to my question in terms that I can understand. I am trying to make my code upload all text input fields and if not image is in the file input, then upload all except the image and upload all including the image when an image is present. Below is my working code for when an image is present. All help will be greatly appreciated.
<?php
session_start();
error_reporting(E_ALL);
include_once 'dbconnect.php';
$userID = $_SESSION['usr_id'];
if(!empty($_FILES["uploadedimage"]["tmp_name"])) {
$eTitle = mysqli_real_escape_string($con, $_POST['etitle']);
$eDate=mysqli_real_escape_string($con, $_POST['edate']);
$eDesc=mysqli_real_escape_string($con, $_POST['edesc']);
$file_tmp = $_FILES['uploadedimage']['tmp_name'];
$file_ext = strtolower(end(explode('.',$_FILES['uploadedimage']['name'])));
$date = date("d-m-Y");
$imagename = $date."-".time().".".$file_ext;
$target_path = "event_images/".$imagename;
$move = move_uploaded_file($file_tmp, $target_path);
if($move) {
if($_FILES['uploadedimage']===false){
$not = "NULL";
}ELSE{
$not = $imagename;
}
$sql =mysqli_query($con, "INSERT INTO `events` (eventID,eventImage,eventTitle,eventDate,eventDescription) values (NULL,'".$not."','".$eTitle."','".$eDate."','".$eDesc."')");
$db = mysqli_query($sql, $con);
$msg = "Song has been uploaded successfully";
header("Location: websiteeditor.events.php");
}
else {
$msg = "Not uploaded because of error #".$_FILES["file"]["error"];
}
}
else {
$msg = "Failed to Upload<br/>Not uploaded because of error #".$_FILES["file"]["error"];
}
?>
<?=$msg;?>
Following code should work the way you need it.
<?php
session_start();
error_reporting(E_ALL);
include_once 'dbconnect.php';
$userID = $_SESSION['usr_id'];
$eTitle = mysqli_real_escape_string($con, $_POST['etitle']);
$eDate = mysqli_real_escape_string($con, $_POST['edate']);
$eDesc = mysqli_real_escape_string($con, $_POST['edesc']);
$date = date("d-m-Y"); // where is this used?
$not = null;
if (!empty($_FILES["uploadedimage"]["tmp_name"])) {
$file_tmp = $_FILES['uploadedimage']['tmp_name'];
$file_ext = strtolower(end(explode('.', $_FILES['uploadedimage']['name'])));
$imagename = $date . "-" . time() . "." . $file_ext;
$target_path = "event_images/" . $imagename;
$move = move_uploaded_file($file_tmp, $target_path);
if ($move) {
$not = $imagename;
} else {
$msg = "Not uploaded because of error #" . $_FILES["file"]["error"];
}
}
$sql = mysqli_query($con, "INSERT INTO `events` (eventID,eventImage,eventTitle,eventDate,eventDescription) values (NULL,'" . $not . "','" . $eTitle . "','" . $eDate . "','" . $eDesc . "')");
$db = mysqli_query($sql, $con);
$msg = "Song has been uploaded successfully";
header("Location: websiteeditor.events.php");
?>
If I upload a same named image, my code works fine to rename it in my location but when it's fetched from database, the duplicate image is broken. My code for renaming and storing the image is:
insert_image.php
$image = $_FILES['image'];
$name = $_FILES['image']['name'];
$temp_name = $_FILES['image']['tmp_name'];
$newname = $name;
//print_r($_FILES);
$location = realpath(dirname(__FILE__)).'/images/'.basename($name);
$image_path = realpath(dirname(__FILE__)).'/images/';
$extention = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
if(file_exists($location)){
$increment = 0;
list($name, $extention) = explode('.', $location);
while(file_exists($location)) {
$increment++;
$location = $name. $increment . '.' . $extention;
//print_r($location);
$newname = $name. $increment . '.' . $extention;
}
}
mysqli_query($dbc, "INSERT INTO post(username, post, image) VALUES('$uname', '$post', '$newname')");
if(isset($newname)){
if(move_uploaded_file($_FILES['image']['tmp_name'], $location) && is_writable($location)){
//echo 'File uploaded successfully';
}
else{
//echo "Failed to move...";
}
}
any kind of better suggestions will be really helpful.
In location variable (inside while loop) your are storing only file name. You also want full path. change your code as below
$image = $_FILES['image'];
$name = $_FILES['image']['name'];
$temp_name = $_FILES['image']['tmp_name'];
$newname = $name;
//print_r($_FILES);
$location = realpath(dirname(__FILE__)).'/images/'.basename($name);
$image_path = realpath(dirname(__FILE__)).'/images/';
$extention = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
if(file_exists($location)){
$increment = 0;
list($name, $extention) = explode('.', $name);
while(file_exists($location)) {
$increment++;
$location = realpath(dirname(__FILE__)).'/images/'.$name. $increment . '.' . $extention;
$newname = $name. $increment . '.' . $extention;
}
}
mysqli_query($dbc, "INSERT INTO post(username, post, image) VALUES('$uname', '$post', '$newname')");
if(isset($newname)){
if(move_uploaded_file($_FILES['image']['tmp_name'], $location) && is_writable($location)){
//echo 'File uploaded successfully';
}
else{
//echo "Failed to move...";
}
}
I made a code for multiple image uploader, but just first image is stored to mysql table and both into path, some help?
This is my code:
if(!empty($_FILES['file'])){
foreach($_FILES['file']['name'] as $key => $name){
if($_FILES['file']['error'][$key] == 0){
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if(in_array($ext, $allowed) === true && move_uploaded_file($temp, "product_images/{$file}") === true){
$path = 'product_images';
mysql_query("INSERT INTO `products` (img_path, img_name) VALUES ('$path', '$file')");
}else{
$errors[] = 'Format slike mora biti .jpg ili .png';
}
}
}
}
I'm storing vehicle information in a DB and this includes images file names. A user has the option to upload multiple files at once, and those file names are stored in a single row. For e.g, I upload a new vehicle, a Ford, and I have three images for this vehicle. As soon as I hit save, the images are saved in a predefined directory and the file names are stored in the DB. The file names in the DB are split by *.
Here's the code to save the information to the DB:
if (isset($_POST['submit'])) {
//Get form data
$stock_number = $_POST['stock_number'];
$vin_number = $_POST['vin_number'];
$make = $_POST['make'];
$model = $_POST['model'];
$colour = $_POST['colour'];
$milage = $_POST['milage'];
$year = $_POST['year'];
$price = $_POST['price'];
$description = $_POST['description'];
extract($_POST);
if (isset($_FILES['images']['name'])) {
$file_name_all = '';
for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
$tmpFilePath = $_FILES['images']['tmp_name'][$i];
if ($tmpFilePath != '') {
$path = 'uploaded_images/';
$name = $_FILES['images']['name'][$i];
$size = $_FILES['images']['size'][$i];
list($txt, $ext) = explode('.', $name);
$file = time().substr(str_replace(' ', '_', $txt), 0);
$info = pathinfo($file);
$filename = $file . '.' . $ext;
if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $path.$filename)) {
$file_name_all .= $filename . '*';
}
}
$filepath = rtrim($file_name_all, '*');
}
$sql = "
INSERT INTO vehicles
(stock_number, vin_number, make, model, colour, milage, year, price, description, images_path)
VALUES
('$stock_number', '$vin_number', '$make', '$model', '$colour', '$milage', '$year', '$price', '$description', '$filepath')
";
$result = mysqli_query($conn, $sql);
} else {
$filepath = '';
}
if ($result) {
header('Location: manage_vehicles.php');
}
}
That all works great.
Here's the problem: When I select the information from the DB to display, I need to display the images that pertains to only that record, but it doesn't. It displays all the images, despite displaying the correct information for a selected record. For e.g, if I select the Ford I added earlier, it displays the correct information, but all the images of all the records.
Here's the code for selecting information, the images specifically:
$id = $_GET['id'];
$sql = "SELECT * FROM vehicles WHERE id='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$row['make'];
$dir = "uploaded_images/";
$file = $row['images_path'];
if ($opendir = opendir($dir)) {
while (($file = readdir($opendir)) !== false) {
if ($file != '.' && $file != '..') {
echo "<img class='images' src='$dir/$file'>";
}
}
}
}
}
You were overwriting the $file variable.
try the below code
$id = $_GET['id'];
$sql = "SELECT * FROM vehicles WHERE id='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$row['make'];
$dir = "uploaded_images/";
$filePath= $row['images_path'];
$fileArray = explode("*",$filePath); //split the filepath
foreach($fileArray as $file)
{
if(file_exists($dir.$file)) //check if file exist
{
echo "<img class='images' src='$dir/$file'>";
}
}
}
}
P.S The code is not tested!
How do i get a unique image to MySQL and still be able to edit just one image at a time? I only have the ability to update 4 images at once with a unique id or I can edit the images seperatly and have them update without a unique id.
<?php
require_once('storescripts/connect.php');
mysql_select_db($database_phpimage,$phpimage);
$uploadDir = 'upload/';
if(isset($_POST['upload']))
{
foreach ($_FILES as $file)
{
$fileName = $file['name'];
$tmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileType = $file['type'];
if ($fileName != ""){
$filePath = $uploadDir;
$fileName = str_replace(" ", "_", $fileName);
//Split the name into the base name and extension
$pathInfo = pathinfo($fileName);
$fileName_base = $pathInfo['fileName'];
$fileName_ext = $pathInfo['extension'];
//now we re-assemble the file name, sticking the output of uniqid into it
//and keep doing this in a loop until we generate a name that
//does not already exist (most likely we will get that first try)
do {
$fileName = $fileName_base . uniqid() . '.' . $fileName_ext;
} while (file_exists($filePath.$fileName));
$file_names [] = $fileName;
$result = move_uploaded_file($tmpName, $filePath.$fileName);
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$fileinsert[] = $filePath;
}
}
$mid = mysql_real_escape_string(trim($_POST['mid']));
$cat = mysql_real_escape_string(trim($_POST['cat']));
$item = mysql_real_escape_string(trim($_POST['item']));
$price = mysql_real_escape_string(trim($_POST['price']));
$about = mysql_real_escape_string(trim($_POST['about']));
$fields = array();
$values = array();
$updateVals = array();
for($i = 0; $i < 4; $i++)
{
$values[$i] = isset($file_names[$i]) ? mysql_real_escape_string($file_names[$i]) : '';
if($values[$i] != '')
{
$updateVals[] = "{$fields[$i]} = '{$values[$i]}'";
}
}
$updateNames = '';
if(count($updateVals))
{
$updateNames = ", " . implode(', ', $updateVals);
}
$update = "INSERT INTO image
(mid, cid, item, price, about, name1, name2, name3, name4)
VALUES
('$mid', '$cat', '$item', '$price', '$about', '$values[0]', '$values[1]', '$values[2]', '$values[3]')
ON DUPLICATE KEY UPDATE
cid = '$cat', item = '$item', price = '$price', about = '$about' $updateNames";
$result = mysql_query($update) or die (mysql_error());
Within your foreach ($_FILES as $file) { loop you are renaming and saving the uploaded file but you are using the original filenames when inserting into the db. You need to store the renamed files in the db. After your do ... while loop assign the new filename to an array -
do {
$fileName = $fileName_base . uniqid() . '.' . $fileName_ext;
} while (file_exists($filePath.$fileName));
$file_names[] = $fileName;
then modify your for loop to -
for($i = 0; $i < 4; $i++)
{
$values[$i] = isset($filenames[$i]) ? mysql_real_escape_string($filenames[$i]) : '';
if($values[$i] != '') {
$updateVals[] = 'name' . ($i + 1) . " = '{$values[$i]}'";
}
}
and finally, update your update statement to -
$update = "INSERT INTO image
(mid, cid, item, price, about, name1, name2, name3, name4)
VALUES
('$mid', '$cat', '$item', '$price', '$about', '$values[0]', '$values[1]', '$values[2]', '$values[3]')
ON DUPLICATE KEY UPDATE
cid = '$cat', item = '$item', price = '$price', about = '$about' $updateNames";