Can't set image upload variable to NULL - php

So weird well annoying problem, I'm trying to upload images from a form (all works fine) However when there is no image it should set itself to NULL, but because i'm using $target_dir . basename it keeps taking the last part of the $target_dir instead of setting to NULL and inserting the word products into the database instead of nothing. But obv need the $target_dir for when the upload takes place to put in correct place. Please see code below, all help much appreciated.
$target_dir = "../images/products/";
if (!isset ($_FILES["img1"]["name"])) {
$target_file1 = NULL;
} else {
$target_file1 = $target_dir . basename($_FILES["img1"]["name"]);
}
if (!isset ($_FILES["img2"]["name"])) {
$target_file2 = NULL;
} else {
$target_file2 = $target_dir . basename($_FILES["img2"]["name"]);
}
if (!isset ($_FILES["img3"]["name"])) {
$target_file3 = NULL;
} else {
$target_file3 = $target_dir . basename($_FILES["img3"]["name"]);
}
if (!isset ($_FILES["img4"]["name"])) {
$target_file4 = NULL;
} else {
$target_file4 = $target_dir . basename($_FILES["img4"]["name"]);
}
SQL query and relevant info
<pre>
$image1 = basename($target_file1);
$image2 = basename($target_file2);
$image3 = basename($target_file3);
$image4 = basename($target_file4);
echo $image1;
echo $image2;
echo $image3;
echo $image4;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO products (product_code, product_name, category,
filter, description, specification, img1, img2, img3, img4, price)
VALUES('$product_code', '$product_name', '$category', '$filter',
'$description', '$specification', '$image1', '$image2', '$image3',
'$image4', '$price')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
</pre>
K, changed it to set the values first and only assign value if isset
same thing, see screenshot of output below.

u can try
$target_dir = "../images/products/";
if (!isset ($_FILES["img1"]["name"])) {
$target_file1 = NULL;
} else {
if (!empty($_FILES["img1"]["name"])) {
$target_file1 = $target_dir . basename($_FILES["img1"]["name"]);
} else {
$target_file1 = NULL;
}
}
if (!isset ($_FILES["img2"]["name"])) {
$target_file2 = NULL;
} else {
if (!empty($_FILES["img2"]["name"])) {
$target_file2 = $target_dir . basename($_FILES["img2"]["name"]);
} else {
$target_file2 = NULL;
}
}
if (!isset ($_FILES["img3"]["name"])) {
$target_file3 = NULL;
} else {
if (!empty($_FILES["img3"]["name"])) {
$target_file3 = $target_dir . basename($_FILES["img3"]["name"]);
} else {
$target_file3 = NULL;
}
}
if (!isset ($_FILES["img4"]["name"])) {
$target_file4 = NULL;
} else {
if (!empty($_FILES["img4"]["name"])) {
$target_file4 = $target_dir . basename($_FILES["img4"]["name"]);
} else {
$target_file4 = NULL;
}
}

Related

upload all fields with the image file upload optional PHP MySQLI

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");
?>

How to move images to new dynamic folder

Dear friends I have a simple code to move some images to dynamically created folders
Here is my code
ini_set('max_execution_time', -1);
include("connection.php");
$sql = "SELECT manufacturers.id, user_profiles.logo
FROM `manufacturers`
INNER JOIN user_profiles
WHERE manufacturers.user_id = user_profiles.user_id AND manufacturers.id > 2235";
$query=mysqli_query($live_db, $sql) or die("Connection failed: " . mysqli_connect_error($live_db));
while($row = mysqli_fetch_array($query) ){
$temp = '/home/aigae4z5r/mydomain.com/frontend/web/uploads/manufacturers/images/'. $row['logo'];
$idDir = '/home/aigae4z5r/mydomain.com/frontend/web/uploads/manufacturers/'.$id;
$destinationPath = $idDir . DIRECTORY_SEPARATOR . $row['logo'];
if (!is_dir($idDir)) {
mkdir($idDir, 0777, TRUE);
}
if (rename($temp, $destinationPath)) {
echo 'moved! <br />';
} else {
echo 'failed <br />';
}
}
The problem is to create new folders
if (!is_dir($idDir)) {
mkdir($idDir, 0777, TRUE);
}

PHP Explode and updata data to each colomn in mysql database

I have a form where I want a user to upload one or more images. I've used only one file field for this. The issue is when I submit the form only the "itemImageOne" field will be update. But the echo part( echo $pieces[0], echo $pieces[1] ) is shows the correct result. Bellow is part of my code.
<?php
error_reporting(E_ALL & ~E_NOTICE);
#ini_set('post_max_size', '64M');
#ini_set('upload_max_filesize', '64M');
/* * *********************************************** */
// database constants
define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'root');
define('DB_SERVER_PASSWORD', '');
define('DB_DATABASE', 'ibs');
$dboptions = array(
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$DB = new PDO(DB_DRIVER . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $dboptions);
} catch (Exception $ex) {
echo $ex->getMessage();
die;
}
if (isset($_POST["add"])) {
// include resized library
//require_once('./php-image-magician/php_image_magician.php');
$msg = "";
$pieces = "";
$valid_image_check = array("image/gif", "image/jpeg", "image/jpg", "image/png", "image/bmp");
if (count($_FILES["user_files"]) > 0) {
$folderName = "uploads/";
//$sql = "UPDATE module_course SET itemImage='$filename' WHERE id=1";
//$sql = "UPDATE SET module_course(itemImage) VALUES (:img)";
//$stmt = $DB->prepare($sql);
for ($i = 0; $i < count($_FILES["user_files"]["name"]); $i++) {
if ($_FILES["user_files"]["name"][$i] <> "") {
$image_mime = strtolower(image_type_to_mime_type(exif_imagetype($_FILES["user_files"]["tmp_name"][$i])));
// if valid image type then upload
if (in_array($image_mime, $valid_image_check)) {
$ext = explode("/", strtolower($image_mime));
$ext = strtolower(end($ext));
$filename = rand(10000, 990000) . '_' . time() . '.' . $ext;
$filepath = $folderName . $filename;
$pieces = explode(" ", $filename);
$imageOne = $pieces[0];
$imageTwo = $pieces[1];
echo $pieces[0]."<br/>"; // piece1
echo $pieces[1]."<br/>"; // piece2
$sql = "UPDATE module_course SET itemImageOne = $imageOne, itemImageTwo = $date WHERE id='1'";
$stmt = $DB->prepare($sql);
if (!move_uploaded_file($_FILES["user_files"]["tmp_name"][$i], $filepath)) {
$emsg .= "Failed to upload <strong>" . $_FILES["user_files"]["name"][$i] . "</strong>. <br>";
$counter++;
} else {
$smsg .= "<strong>" . $_FILES["user_files"]["name"][$i] . "</strong> uploaded successfully. <br>";
/* * ****** insert into database starts ******** */
try {
$stmt->bindValue(":img", $filename);
$stmt->execute();
$result = $stmt->rowCount();
if ($result > 0) {
// file uplaoded successfully.
} else {
// failed to insert into database.
}
} catch (Exception $ex) {
$emsg .= "<strong>" . $ex->getMessage() . "</strong>. <br>";
}
/* * ****** insert into database ends ******** */
}
} else {
$emsg .= "<strong>" . $_FILES["user_files"]["name"][$i] . "</strong> not a valid image. <br>";
}
}
}
$msg .= (strlen($smsg) > 0) ? successMessage($smsg) : "";
$msg .= (strlen($emsg) > 0) ? errorMessage($emsg) : "";
} else {
$msg = errorMessage("You must upload atleast one file");
}
}
?>
Try
UPDATE module_course
SET itemImageOne = $imageOne, itemImageTwo = $imageTwo
WHERE id = '1'; # Changed
Changed - Edit 01
$stmt = $DB->prepare("UPDATE module_course
SET itemImageOne = ?, itemImageTwo = ?
WHERE id = 1");
$stmt->bindValue(1, $imageOne, PDO::PARAM_STR);
$stmt->bindValue(2, $imageTwo, PDO::PARAM_STR);
$stmt->execute();
Error Bcz of you are binding one parameter $stmt->bindValue(":img", $filename);

How to upload ONLY images in database

I want to upload ONLY pictures , in the database using php.
What I tried is,
<?php
if (isset($_POST['Upload'])) {
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("iis", $con);
$image = $_FILES["product_image"]["name"];
$imageType = mysql_real_escape_string($_FILES["product_image"]["type"]);
if (substr($imageType, 0, 5) == "image") {
if (!file_exists("product_images")) {
mkdir("product_images");
}
if ($_FILES["product_image"]["error"] > 0) {
$error = "ERROR Return Code :" . $_FILES["product_image"]["error"] . "<br />";
} else {
move_uploaded_file($_FILES["product_image"]["tmp_name"], "product_images/" . $_FILES["product_image"]["name"]);
}
}
$UserName = $_SESSION['id'];
$product_image = ("product_images/" . $_FILES["product_image"]["name"]);
mysql_query("INSERT INTO `feedbackzxc` VALUES ('', '$UserName', '$product_image')");
echo "Image Uploaded!";
} else {
echo "Only images are allowed";
}
?>
But when I upload a file other than images it doesn't show the error message. How can I make it show error message if a file other than an image is uploaded?
Your else block where the message Only images are allowed is shown must be located after the if block that check this: substr($imageType,0,5) == "image"
if(substr($imageType,0,5) == "image"){
if(!file_exists("product_images"))
{
mkdir("product_images");
}
if($_FILES["product_image"]["error"] > 0)
{
$error = "ERROR Return Code :" . $_FILES["product_image"]["error"] . "<br />";
}
else
{
move_uploaded_file($_FILES["product_image"]["tmp_name"], "product_images/".
$_FILES["product_image"]["name"]);
}
}
else
{
echo "Only images are allowed";
}

Running MySQL queries in specific order

I wonder if someone could advise me here. I have a page where I am updating information in a database, from the previous page I post any new images (with a caption too) and I have a checkbox for deleting images. On the processing page I have the following code:
<?php
session_start();
$dbhost = 'removed';
$dbuser = 'removed';
$dbpass = 'removed';
$dbname = 'removed';
function reArrayFiles($file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpass);
}catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$query="SELECT * FROM `soldier_info` WHERE `soldier_id` = " . $_POST['soldier_id'] ;
foreach ($dbo->query($query) as $row) {
$soldier_pre_images = explode(",", $row['soldier_images']);
}
if($_POST['deletephoto']){
$imagestodelete=$row['soldier_images'];
$captionstodelete=$row['soldier_images_captions'];
foreach($_POST['deletephoto'] as $todelete){
$deleteexplode = explode("--",$todelete);
echo $deleteexplode;
$deleteexplodepath = $deleteexplode[0];
$deletecaption=$deleteexplode[1];
$imagesafterdelete= str_replace($deleteexplodepath.",","",$imagestodelete);
echo $imagesafterdelete;
$captionsafterdelete = str_replace($deletecaption."--","",$captionstodelete);
echo $captionsafterdelete;
$unlinkpath = str_replace('site url','..',$deleteexplodepath);
unlink($unlinkpath);
}
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpass);
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $dbo->prepare("UPDATE `soldier_info` SET `soldier_images`= :image, `soldier_images_captions`= :captions WHERE `soldier_id`= :id");
$q->execute(array(":image" => $imagesafterdelete, ":captions" => $captionsafterdelete, ":id" => $_POST['soldier_id']));
}catch (PDOException $e) {
$db_error = "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
if ($_FILES['photo']) {
$file_ary = reArrayFiles($_FILES['photo']);
$capcount = 0;
foreach ($file_ary as $file) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $file["name"]);
$extension = end($temp);
if ((($file["type"] == "image/gif")||($file["type"] == "image/jpeg")||($file["type"] == "image/jpg")||($file["type"] == "image/pjpeg")||($file["type"] == "image/x-png")||($file["type"] == "image/png"))&&($file["size"] < 9000000) && in_array(strtolower($extension), $allowedExts)) {
if ($file["error"] > 0) {
$file_error = "Return Code: " . $file["error"] . "<br>";
} else {
$newfilename = "../assets/uploads/images/" . $_POST['soldier_id'] . "/" . $file["name"];
$file_fullname = "site urlv/assets/uploads/images/" . $_POST['soldier_id'] . "/" . $file["name"];
$new_caption = $_POST['image_captions'][$capcount];
if (file_exists($newfilename)) {
$file_exists = $file["name"] . " already exists. ";
} else {
if(is_dir("../assets/uploads/images/" . $_POST['soldier_id'])){
move_uploaded_file($file["tmp_name"],$newfilename);
if (strlen($uploaded_images)>1){
$uploaded_images = $uploaded_images . ",". $file_fullname;
}else{
$uploaded_images = $file_fullname;
}
if (strlen($uploaded_captions)>1){
$uploaded_captions = $uploaded_captions . "--". $new_caption;
}else{
$uploaded_captions = $new_caption;
}
}else{
mkdir("../assets/uploads/images/" . $_POST['soldier_id'], 0777, true);
move_uploaded_file($file["tmp_name"],$newfilename);
if (strlen($uploaded_images)>1){
$uploaded_images = $uploaded_images . ",". $file_fullname;
}else{
$uploaded_images = $file_fullname;
}
if (strlen($uploaded_captions)>1){
$uploaded_captions = $uploaded_captions . "--". $new_caption;
}else{
$uploaded_captions = $new_caption;
}
}
}
if (strlen($row['soldier_images'])>1){
$uploaded_images = $row['soldier_images'] . ",". $uploaded_images;
}else{
$uploaded_images = $uploaded_images;
}
}
} else {
$file_invalid = "The file is not a jpg/gif/png file, or is larger than 20mb. Please try again.";
}
$capcount = $capcount+1;
}
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpass);
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $dbo->prepare("UPDATE `soldier_info` SET `soldier_images`= :image, `soldier_images_captions`= :captions WHERE `soldier_id`= :id");
$q->execute(array(":image" => $uploaded_images, ":captions" => $uploaded_captions, ":id" => $_POST['soldier_id']));
}catch (PDOException $e) {
$db_error = "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
$query="SELECT * FROM `soldier_info` WHERE `soldier_id` = " . $_POST['soldier_id'] ;
foreach ($dbo->query($query) as $row) {
$firstname = $row['firstname'];
$surname = $row['surname'];
$yearofbirth = $row['yearofbirth'];
$dateofdeath = date("d/m/Y", strtotime($row['dateofdeath']));
$ageatdeath = $row['ageatdeath'];
$regiment = $row['regiment'];
$battallion_brigade = $row['battallion_brigade'];
$Coybty = $row['Coy/bty'];
$rank = $row['rank'];
$solider_number = $row['soldier_number'];
$Next_of_Kin = $row['Next_of_Kin'];
$CWGC = $row['CWGC'];
$Place_Died = $row['Place_Died'];
$Connection_to_Wymeswold = $row['Connection_to_Wymeswold'];
$Cemetery = $row['Cemetery'];
$LRoH = $row['LRoH'];
$Grave = $row['Grave'];
$Memorial = $row['Memorial'];
$Pier_Face = $row['Pier_Face'];
$Other_Mem = $row['Other_Mem'];
$Other_Details = $row['Other_Details'];
$soldier_images = explode(",", $row['soldier_images']);
$soldier_images_captions = explode("--", $row['soldier_images_captions']);
}
$dbo = null;
?>
This isn't a live site right now and is in testing/dev. However the issue I am seeing is that, all the queries are running, but the page loads up as though the select has run first (by this I mean that the records returned are those from before the updates as processed. Can I force this select to run last so that it gets the latest records?
I think you get the 'original' data on the last select because you are running the queries on different connections. Hence they will live in isolated transactions, that might not be properly committed when the last select runs.
If you run them all in the same PDO object I think it will work.
(If you take POST parameters and concatenate them into SQL your server will be hacked. It's just a matter of time and you have the URL here for everyone to see.)

Categories