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");
?>
Related
<?php
session_start();
require "database.php";
$db = new database();
$operation = $_REQUEST['action'];
$file = uniqid() . " - " . $_FILES['document']['name'];
$result = move_uploaded_file(
$_FILES['document']['tmp_name'],
"uploads/" . $file );
switch ($operation)
{
case 'Add':
$name = $_REQUEST['name'];
$image = "uploads/" . $file;
$result = $db->insert($name,$image);
break;
case 'update':
$id = $_SESSION['user_id'];
$name = $_REQUEST['name'];
$image = "uploads/" . $file;
$result = $db->update($id,$name,$image);
break;
case 'delete':
$result = $db->delete($_REQUEST['id']);
break;
default:
echo "invalid request";
break;
}
header("Location:display.php");
?>
Use is_uploaded_file() function to check whether a file is uploaded with the form or not. So accordingly, change your code in the following way,
...
$operation = $_REQUEST['action'];
$file = null;
if(is_uploaded_file($_FILES['document']['tmp_name'])){
$file = uniqid() . " - " . $_FILES['document']['name'];
$result = move_uploaded_file($_FILES['document']['tmp_name'], "uploads/" . $file );
}
switch($operation){
case 'Add':
$name = $_REQUEST['name'];
$image = ($file == null) ? null : "uploads/" . $file;
$result = $db->insert($name,$image);
break;
case 'update':
$id = $_SESSION['user_id'];
$name = $_REQUEST['name'];
$image = ($file == null) ? null : "uploads/" . $file;
$result = $db->update($id,$name,$image);
break;
case 'delete':
...
}
...
And your update method would be like this,
public function update($id, $name, $image) {
$query = "UPDATE customers SET name='$name'";
if($image != null){
$query .= ", image ='$image'";
}
$query .= " WHERE id=$id";
return mysqli_query($this->connect,$query);
}
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attack. Also see how you can prevent SQL injection in 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...";
}
}
Evertime I upload a picture, the FILENAME is NOT CHANGING the static value(filename) that is inserting in database is always "0.png" I don't know how is that happening, Please Help me how to fix this problem.
Here is my code:
<?php
session_start();
include("../db_connection.php");
$seller_id = $_SESSION['seller_id'];
$trade_name = $_POST ['trade_name'];
$s_address = $_POST ['s_address'];
$opening_time = $_POST ['opening_time'];
$opening_days = $_POST ['opening_days'];
$order_cutoff = $_POST ['order_cutoff'];
$seller_delivery_time = $_POST ['seller_delivery_time'];
$area_covered_delivery = $_POST ['area_covered_delivery'];
$delivery_fee = $_POST ['delivery_fee'];
$extension = pathinfo($_FILES['s_image']['name'], PATHINFO_EXTENSION);
$sql = mysqli_query($db, "UPDATE selling_details
SET
opening_time = '$opening_time',
opening_days = '$opening_days',
order_cutoff = '$order_cutoff',
seller_delivery_time = '$seller_delivery_time',
area_covered_delivery = '$area_covered_delivery',
delivery_fee = '$delivery_fee'
WHERE seller_id= '" . $_SESSION['seller_id'] . "' ");
if ($sql)
{
$id = mysqli_insert_id($db);
$filename = $id.'.'.$extension;
if(move_uploaded_file($_FILES['s_image']['tmp_name'], 'upload/'.$filename))
{
$sql2 = mysqli_query($db, "UPDATE seller
SET
trade_name = '".$trade_name."',
s_address = '".$s_address."',
s_image = '".$filename."'
WHERE seller_id= '" . $_SESSION['seller_id'] . "' ");
if ($sql2)
{
header('location: seller_menu.php');
}
else
{
echo "error occured : " . mysqli_error($db);
}
}
else
{
echo "error occured : " . mysqli_error($db);
}
}
?>
The function mysqli_insert_id returns the id of the row you just inserted into your database, and since you don't insert anything (you just update) the value the function returns is 0, so the name of your image is $id.'.'.$extension ==> 0.png.
Since you update the seller_id, and you have it inside $_SESSION['seller_id'], you can use it in your code:
$filename = $_SESSION['seller_id'].'.'.$extension;
I want to update or set a photo on specific user, when I tried to upload an image, the image is not uploaded on my folder "upload" and the name of the photo (which is a number but 0 e.g: 1.jpg) is inserted in database and the file extension is missing inside the database can someone help me with this
HERE IS MY CODE:
<?php
session_start();
include("../db_connection.php");
$seller_id = $_SESSION['seller_id'];
$trade_name = $_POST ['trade_name'];
$s_address = $_POST ['s_address'];
$opening_time = $_POST ['opening_time'];
$opening_days = $_POST ['opening_days'];
$order_cutoff = $_POST ['order_cutoff'];
$seller_delivery_time = $_POST ['seller_delivery_time'];
$area_covered_delivery = $_POST ['area_covered_delivery'];
$delivery_fee = $_POST ['delivery_fee'];
$extension = pathinfo($_FILES['s_image']['name'], PATHINFO_EXTENSION);
$sql = mysqli_query($db, "UPDATE selling_details
SET
opening_time = '$opening_time',
opening_days = '$opening_days',
order_cutoff = '$order_cutoff',
seller_delivery_time = '$seller_delivery_time',
area_covered_delivery = '$area_covered_delivery',
delivery_fee = '$delivery_fee'
WHERE seller_id= '" . $_SESSION['seller_id'] . "' ");
if ($sql)
{
$id = mysqli_insert_id($db);
$filename = $id.'.'.$extension;
if(move_uploaded_file($_FILES['s_image']['tmp_name'], 'upload/'.$filename))
{
}
else
{
echo "error occured : " . mysqli_error($db);
}
$sql2 = mysqli_query($db, "UPDATE seller
SET
trade_name = '$trade_name',
s_address = '$s_address',
s_image = '$filename'
WHERE seller_id= '" . $_SESSION['seller_id'] . "' ");
if ($sql2)
{
header('location: seller_menu.php');
}
else
{
echo "error occured : " . mysqli_error($db);
}
}
?>
Try like this... If your field is varchar means it will work. and you need to declare the variable using .[concodinate] operator. Not tested check and let me know.
$sql2 = mysqli_query($db, "UPDATE seller
SET
trade_name = '".$trade_name."',
s_address = '".$s_address."',
s_image = '".$filename."'
WHERE seller_id= '" . $_SESSION['seller_id'] . "' ");
Edited:
Try to change like this because if your file upload complete then save into your DB is correct way...In your code is run the second sql2 query if not file upload into the folder.
if ($sql) {
$id = mysqli_insert_id($db);
$filename = $id.'.'.$extension;
if(move_uploaded_file($_FILES['s_image']['tmp_name'], 'upload/'.$filename)) {
$sql2 = mysqli_query($db, "UPDATE seller
SET
trade_name = '".$trade_name."',
s_address = '".$s_address."',
s_image = '".$filename."'
WHERE seller_id= '" . $_SESSION['seller_id'] . "' ");
if ($sql2) {
header('location: seller_menu.php');
}else{
echo "error occured : " . mysqli_error($db);
}
}
} else {
echo "error occured : " . mysqli_error($db);
}
$upload_dir = "upload"; // The directory for the images to be saved in
$upload_path = $upload_dir."/";
$userfile_tmp = $_FILES['s_image'.$i]['tmp_name'];
$filename = basename($_FILES['s_image'.$i]['name']);
$file_Size = $_FILES['s_image']['size'];
$extension = strtolower(substr($filename, strrpos($filename, '.') + 1));
if (empty($extension)) {$error='No extension exist!';}
if(isset($_FILES['s_image']['name']) && $_FILES['s_image']['name']==true && $file_Size >0 && $error=='')
{
$filename = $id.'.'.$extension;
$new_image_location=$upload_path.$filename;
//chmod($new_image_location, 0777);
if(move_uploaded_file($userfile_tmp, $new_image_location))
{
$sql2 = mysqli_query($db, "UPDATE seller
SET
trade_name = '$trade_name',
s_address = '$s_address',
s_image = '$filename'
WHERE seller_id= '" . $_SESSION['seller_id'] . "' ");
}else{
echo 'upload folder permission required!!';
//chmod($new_image_location, 0777);
}
}
I am trying to upload files to a directory created with PHP. The application should create a sub-directory inside the root directory according to a User's UserID. (for e.g. files/14/).
The directory is being created, however the files are not being uploaded to the sub-directory.
This is the code:
<?php
include("dbConfig.php");
$Username = $_SESSION["username"];
global $userid;
$Password = $_SESSION["password"];
$Password = md5($Password);
$sql = "SELECT UserID FROM users WHERE Username = '".$Username."'";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$userid = $row['UserID'];
}
echo $userid;
$dirname = (string)$userid;
$filename = ("/folder/" . "$dirname" . "/");
if (!file_exists($filename))
{
mkdir("files/$dirname", 0777);
if (isset($_FILES['files'])) {
echo "<div id='files_table'><table class='center'.><tr><td>";
$dest = ("files/" . $dirname . "{$_FILES['files']['name'][$key]}");
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
move_uploaded_file($tmp_name, $dest );
echo $_FILES['files']['name'][$key], " uploaded.", "<br>";
}
}else {
if (isset($_FILES['files'])) {
echo "<div id='files_table'><table class='center'.><tr><td>";
$dest = ("files/" . $dirname . "{$_FILES['files']['name'][$key]}");
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
move_uploaded_file($tmp_name, $dest );
echo $_FILES['files']['name'][$key], " uploaded.", "<br>";
}
echo "</td></tr></table></div><br><br>";
}
}
}
Brain,
PHP support one file upload at one time, if you have many file fields in your form, you should keep "$dest = ("files/" . $dirname . "{$_FILES['files']['name'][$key]}");" in the loop.
$Key will be empty outside the loop.
Loop can't be on temp_name, temp_name is a temp copy of the file which php is going to upload.
Here is the modified code:
Note: I corrected some errors in your code too. please compare.
<?php
include("dbConfig.php");
$Username = $_SESSION["username"];
global $userid;
$Password = $_SESSION["password"];
$Password = md5($Password);
$sql = "SELECT UserID FROM users WHERE Username = '".$Username."'";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$userid = $row['UserID'];
}
$dirname = (string)$userid;
$filename = ("$dirname" . "/");
if (!file_exists($filename)) {
mkdir("files/$dirname", 0775);
}
if (isset($_FILES['files'])) {
echo "<div id='files_table'><table class='center'.><tr><td>";
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
$dest = ("files/" . $dirname . "{$_FILES['files']['name'][$key]}");
move_uploaded_file($tmp_name, $dest );
echo $_FILES['files']['name'][$key], " uploaded.", "<br>";
}
}
?>