PHP - Creating and uploading to directories - php

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

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

delete image from server folder

Here is code of uploading image in my localhost/file/img folder and also inserting image path and name in my table.
<?php
if (isset($_POST['submit']))
{
$file_id = $_POST['file_id'];
if (count($_FILES['upload']['name']) > 0)
{
for ($i = 0; $i < count($_FILES['upload']['name']); $i++)
{
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != "")
{
$shortname = $_FILES['upload']['name'][$i];
$filePath = "img/" . $_FILES['upload']['name'][$i];
if (move_uploaded_file($tmpFilePath, $filePath))
{
$files[] = $shortname;
$query = "insert into images(id,img_name) values('$file_id',' $filePath')";
mysqli_query($con, $query);
}
}
}
}
echo "<h1>Uploaded:</h1>";
if (is_array($files))
{
echo "<ul>";
foreach($files as $file)
{
echo "<li>$file</li>";
}
echo "</ul>";
}
}
?>
Table Images with attribute img_name type is LONGBLOB
now its totally working fine but when i am deleting image from database its getting error that image name is not found. here is code of sending image id and image name using a href
<ul>
<a href="index.php?img_id=<?php echo urlencode($id); ?>&img=<?php echo urlencode($img); ?>"
style="color:red; margin-left:18px;" onclick="return confirm('Are you sure you want to delete this?')" >Delete
</a>
</ul>
now here is code of want i want to delete from my database and also from my localhost folder named img .
<?php
if (isset($_GET['img_id'], $_GET['img']))
{
$id = $_GET['img_id'];
$img = $_GET['img'];
$query = "delete from images where id='$id' and image='$img'";
if (mysqli_query($con, $query))
{
unlink($img);
echo '<script language="javascript">';
echo 'alert("Image Deleted successfully")';
echo '</script>';
}
else
{
echo '<script language="javascript">';
echo 'alert("image does not exist")';
echo '</script>';
}
}
?>
now showing warning that img/image_name.jpg not found.Help me please .
I think your delete query is wrong
if(isset($_GET['img_id'] , $_GET['img'])){
$id=$_GET['img_id'];
$img=$_GET['img'];
$query="delete from images where id='$id' and image='$id'";
}
$query="delete from images where id='$id' and image='$img'";
In this query you check Id and Image field with same $id variable
try this :
<?php
if (isset($_FILES['image']['name'])) {
$name = $_FILES['image']['name'];
$tmpname1 = $_FILES['image']['tmp_name'];
$exten = explode(".", $_FILES['image']['name']);
$exten = $exten[1];
if ($exten != '') {
$image_name = "img" . time() . "." . $exten;
}
move_uploaded_file($tmpname1, FCPATH . 'assets/admin/uploads/' . $image_name);
$query = "insert into images(id,img_name) values('your_id',' $image_name')";
mysqli_query($con, $query);
//see your code
/*
$id=$_GET['img_id'];
$img=$_GET['img'];
$query="delete from images where id='$id' and image='$id'";
*/
you pass the same id value for image. you should try this-
$query="delete from images where id='$id' and image='$img'";
}

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);
}

How to update an image in sql using php

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);
}
}

Adding images to folder and save their name in database using php

I am trying to upload 2 files in a folder and save their name and image path in database, here is my html code:
<input class="field2" type="file" name="file[]" multiple="multiple" />
and my php code is :
$i=0;
$count=0;
foreach ($_FILES['file']['name'] as $filename)
{
if(file_exists('upload/'.$filename))
{
echo "That File Already Exisit";
break;
}
else
{
$target='upload/';//folder path
$tmp=$_FILES['file']['tmp_name'][$count];
$count=$count + 1;
$i=$i+1;
$target=$target.basename($filename);
move_uploaded_file($tmp,$target);
$sql = "UPDATE `fleet` SET `image$i`='$target',`image_name$i`='$filename' WHERE id='$id' ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
}
the issue is image is not getting stored in a folder, i have create a folder named upload, but nothing works foe me
You can try this code:
<?php
$i=0;
$count=0;
foreach ($_FILES['file']['name'] as $filename)
{
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . "/upload/";
if(file_exists($upload_dir.$filename))
{
echo "That File Already Exist";
break;
}
else
{
$tmp = $_FILES['file']['tmp_name'][$count];
$count++;
$i++;
$target = $upload_dir.basename($filename);
if (is_dir($upload_dir) && is_writable($upload_dir)) {
move_uploaded_file($tmp,$target);
$sql = "UPDATE `fleet` SET `image$i`='$target',`image_name$i`='$filename' WHERE id='$id' ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
} else {
echo 'Upload directory is not writable, or does not exist.';
}
}
If you have:
Upload directory is not writable, or does not exist.
You should to a chmod or/and a chown command to give the permissions to write on the upload_dir.
instead of storing name in data base i am storing it in txt file(as per requirement)
<?php
if (isset($_FILES["uploaded_file"]["name"])) {
$imagename=$_POST['imagename'];
$name = $_FILES["uploaded_file"]["name"];
$tmp_name = $_FILES['uploaded_file']['tmp_name'];
$error = $_FILES['uploaded_file']['error'];
if (!empty($name)) {
$location = './uploads/';
if ( ! is_dir($location)) {
mkdir($location);
}
if (move_uploaded_file($tmp_name, $location.$name)){
echo 'Uploaded';
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","a+");
fwrite($fp,$imagename);
fclose($fp);
}
} else {
echo 'please choose a file';
}
}
?>

Categories