File upload works only if all fields are filled in - php

I have a form where users have the option to upload up to 4 files. They do not have to upload all 4.
If they upload 4 files my script works fine. If they upload less than this I get an error "Notice: Undefined index: extension" on the lines in the filenamefetch section that start
$fileName2 = uniqid() . '.' . $fileData2["extension"]; for each of the empty files.
How can I hide this error message? The rest of the script operates as I would expect.
<?php
require_once("connect_db.php");
$ajax_result = "error";
$employeeid=$_POST['employeeid'];
$file1type=$_POST['file1type'];
$file1date=$_POST['file1date'];
$file2type=$_POST['file2type'];
$file2date=$_POST['file2date'];
$file3type=$_POST['file3type'];
$file3date=$_POST['file3date'];
$file4type=$_POST['file4type'];
$file4date=$_POST['file4date'];
//file data fetch
$fileData1 = pathinfo(basename($_FILES["file1"]["name"]));
$fileName1 = uniqid() . '.' . $fileData1["extension"];
$target_path1 = ("uploads/" . $fileName1);
$fileData2 = pathinfo(basename($_FILES["file2"]["name"]));
$fileName2 = uniqid() . '.' . $fileData2["extension"];
$target_path2 = ("uploads/" . $fileName2);
$fileData3 = pathinfo(basename($_FILES["file3"]["name"]));
$fileName3 = uniqid() . '.' . $fileData3['extension'];
$target_path3 = ("uploads/" . $fileName3);
$fileData4 = pathinfo(basename($_FILES["file4"]["name"]));
$fileName4 = uniqid() . '.' . $fileData4['extension'];
$target_path4 = ("uploads/" . $fileName4);
//image 1
while(file_exists($target_path1))
{
$fileName1 = uniqid() . '.' . $fileData1['extension'];
$target_path1 = ("uploads/" . $fileName1);
}
if (move_uploaded_file($_FILES['file1']['tmp_name'], $target_path1))
{ // The file is in the images/gallery folder. Insert record into database by
$q5="INSERT INTO uploadedfiles (filetype, employeeid, filename, filedate) VALUES('$file1type', '$employeeid','$fileName1', '$file1date')";
$r5 = mysqli_query($dbc, $q5) or die(mysqli_error($dbc));
echo "file 1 uploaded";} else {echo "";}
//image 2
while(file_exists($target_path2))
{
$fileName2 = uniqid() . '.' . $fileData2['extension'];
$target_path2 = ("uploads/" . $fileName2);
}
if (move_uploaded_file($_FILES['file2']['tmp_name'], $target_path3))
{ // The file is in the images/gallery folder. Insert record into database by
$q6="INSERT INTO uploadedfiles (filetype, employeeid, filename, filedate) VALUES('$file2type', '$employeeid','$fileName2', '$file2date')";
$r6 = mysqli_query($dbc, $q6);
echo "";} else {echo "";}
//image 3
while(file_exists($target_path3))
{
$fileName3 = uniqid() . '.' . $fileData3['extension'];
$target_path3 = ("uploads/" . $fileName3);
}
if (move_uploaded_file($_FILES['file3']['tmp_name'], $target_path3))
{ // The file is in the images/gallery folder. Insert record into database by
$q7="INSERT INTO uploadedfiles (filetype, employeeid, filename, filedate) VALUES('$file3type', '$employeeid','$fileName3', '$file3date')";
$r7 = mysqli_query($dbc, $q7);
echo "";} else {echo "";}
//image 4
while(file_exists($target_path4))
{
$fileName4 = uniqid() . '.' . $fileData4['extension'];
$target_path4 = ("uploads/" . $fileName4);
}
if (move_uploaded_file($_FILES['file4']['tmp_name'], $target_path4))
{ // The file is in the images/gallery folder. Insert record into database by
$q8="INSERT INTO uploadedfiles (filetype, employeeid, filename, filedate) VALUES('$file4type', '$employeeid','$fileName4', '$file4date')";
$r8 = mysqli_query($dbc, $q8);
echo "";} else {echo "";}

Related

Upload file not working if checking for uploaded files is on the code

The images are uploading normally, but I want an "else if" to check if there is any file selected. This is working:
<?php
session_start();
include('includes/conexao.php');
$fileinfo=PATHINFO($_FILES["image"]["name"]);
$newFilename=$fileinfo['filename'] ."_". time() . "." . $fileinfo['extension'];
move_uploaded_file($_FILES["image"]["tmp_name"],"images/perfis/" . $newFilename);
$location="images/perfis/" . $newFilename;
$todas_fotos = mysqli_query($conexao, "select * FROM esc_usuarios_fotos WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'");
if( mysqli_num_rows($todas_fotos) > 0) {
//$path=$location;
//if(unlink($path)) echo "Deleted file ";
mysqli_query($conexao,"UPDATE esc_usuarios_fotos SET img_local = '$location' WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'");
}
else if( mysqli_num_rows($todas_fotos) == 0)
{
mysqli_query($conexao,"insert into esc_usuarios_fotos (img_local, img_usu_codigo) values ('$location', '" . $_SESSION['codigo'] . "')");
}
else {
};
header('location:perfil.php');
?>
It inserts if there isn't an image, but if there is, it updates. But when I add:
else if (empty($_FILES['image']['name']))
{
header('location:perfil.php');
}
It returns me undefined index: extension on line 5. How to go?
Rewrite the code as follows. Here we are checking whether the file is not available at the beginning of the code and redirect if no file is found.
<?php
session_start();
if (empty($_FILES['image']['name']))
{
header('location:perfil.php?error=1');
return;
}
include('includes/conexao.php');
$fileinfo=PATHINFO($_FILES["image"]["name"]);
$newFilename=$fileinfo['filename'] ."_". time() . "." . $fileinfo['extension'];
move_uploaded_file($_FILES["image"]["tmp_name"],"images/perfis/" . $newFilename);
$location="images/perfis/" . $newFilename;
$todas_fotos = mysqli_query($conexao, "select * FROM esc_usuarios_fotos WHERE
img_usu_codigo = '" . $_SESSION['codigo'] . "'");
if( mysqli_num_rows($todas_fotos) > 0) {
//$path=$location;
//if(unlink($path)) echo "Deleted file ";
mysqli_query($conexao,"UPDATE esc_usuarios_fotos SET img_local = '$location' WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'");
}else {
mysqli_query($conexao,"insert into esc_usuarios_fotos (img_local, img_usu_codigo) values ('$location', '" . $_SESSION['codigo'] . "')");
}
and in the perfil.php you should put
window.onload = function(){
var url = new URL(window.location.href);
var error = url.searchParams.get("error");
if(error==1)
alert("No file uploaded");
}

Notify user when file is uploaded

I want to show a message when the file has been uploaded, right below the UPDATE statement, but I'm struggling with the syntax. The full code:
if (empty($_FILES['image']['name']))
{
header('location:perfil.php?error=1');
return;
}
else if (!in_array($_FILES['image']['type'], $formatos))
{
header('location:perfil.php?error=2');
return;
}
else if (in_array($_FILES['image']['type'], $formatos))
{
if( mysqli_num_rows($todas_fotos) > 0) {
mysqli_query($conexao,"UPDATE esc_usuarios_fotos SET img_local = '$location' WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'");
if (move_uploaded_file($_FILES["image"]["tmp_name"],"images/perfis/" . $newFilename)){
header('location:perfil.php');
}
}
else {
mysqli_query($conexao,"insert into esc_usuarios_fotos (img_local, img_usu_codigo) values ('$location', '" . $_SESSION['codigo'] . "')");
}
header('location:perfil.php');
}
Any thoughts?
EDIT:
These are the upload parameters:
$fileinfo=PATHINFO($_FILES["image"]["name"]);
$newFilename=$fileinfo['filename'] ."_". time() . "." . $fileinfo['extension'];
move_uploaded_file($_FILES["image"]["tmp_name"],"images/perfis/" . $newFilename);
$location="images/perfis/" . $newFilename;
$todas_fotos = mysqli_query($conexao, "SELECT * FROM esc_usuarios_fotos WHERE
img_usu_codigo = '" . $_SESSION['codigo'] . "'");
$formatos = array('image/jpeg', 'image/png');/*

If input image is empty give me error

I have a form with some inputs with that form I want to make some edit in database. I want if exist a picture in databse to keep it not to replace with blank space. If input is empty I get the error from if condition branch else echo "Sorry, there was an error uploading your file.";. If I upload an image everything works fine. Here is my code
<?php
include "../../../config/config.php";
session_start();
if (isset($_GET['car'])) {
$car = $_GET['car'];
} else {
die("Not found");
}
if (isset($_POST['submit-edit'])) {
$title = mysqli_real_escape_string($con, $_POST['title-edit']);
$description = mysqli_real_escape_string($con, $_POST['description-edit']);
$category = mysqli_real_escape_string($con, $_POST['category-edit']);
/* ----------------------- MAIN IMAGE -------------------------- */
$target_dir = "../../../img/found/thumbs-category/";
$target_file2 = "" . basename($_FILES["img-edit"]["name"]);
$target_file = $target_dir . basename($_FILES["img-edit"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check file size
if ($_FILES["img-edit"]["size"] > 100000) {
$_SESSION['image-size'] = 1;
header("Location: /dashboard/views/edit.php?car=$car");
exit();
}
//
//Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != NULL) {
$_SESSION['image-format'] = 1;
header("Location: /dashboard/views/edit.php?car=$car");
exit();
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
} else {
if (move_uploaded_file($_FILES["img-edit"]["tmp_name"], $target_file)) {
} else {
echo "Sorry, there was an error uploading your file.";
exit();
}
$query = "UPDATE cars
SET title='" . $title . "', text='" . $description . "', image='" . $target_file2 . "', fk_cars_first='" . $category . "' WHERE car=" . $car;
$result = mysqli_query($con, $query);
// var_dump($query);
// exit();
if ($result) {
header("Location: /dashboard/views/edit.php?car=$car");
} else {
//
echo "error";
exit();
header("Location: /dashboard/views/edit.php?car=$car");
}
}
}
?>
More exactly in my database I have
title | description | image | fk_category
test more text car.jpg tuning
When I want to edit the the database I use the form and if the input with type="file" is empty I want to keep the actual path not to erase.. Right the code do something like this..I set the submit button and the database look like
title | description | image | fk_category
testedited | ed!t | | tuning_tex_edited
If is empty get the error Sorry, there was an error uploading your file. and in database the path is blank.
Simply use this code:
if ($_FILES['img-edit']){
foreach($_FILES['img-edit']['name'] as $a=>$v){
//Check if empty
if(!empty($_FILES['img-edit']['name'][$a])){
//Check size of image
if($_FILES['img-edit']['size'][$a]>0){
//Now code here
}
}
}
}
Try this code
if (move_uploaded_file($_FILES["img-edit"]["tmp_name"], $target_file)) { //if you have a valid file it will replace the image name
$query = "UPDATE cars
SET title='" . $title . "', text='" . $description . "', image='" . $target_file2 . "', fk_cars_first='" . $category . "' WHERE car=" . $car;
} else { //if you dont have any image it will leave with the older one
$query = "UPDATE cars
SET title='" . $title . "', text='" . $description . "', fk_cars_first='" . $category . "' WHERE car=" . $car;
echo "Sorry, there was an error uploading your file.";
exit();
}

Update input type="file" and keep path for image

This is my code
<?php
include "../../../config/config.php";
session_start();
if (isset($_GET['id'])) {
$id = $_GET['id'];
} else {
die("Not found");
}
if (isset($_POST['submit-edit'])) {
$title = mysqli_real_escape_string($con, $_POST['title']);
$description = mysqli_real_escape_string($con, $_POST['description']);
$category = mysqli_real_escape_string($con, $_POST['category']);
/* ----------------------- MAIN IMAGE -------------------------- */
$target_dir = "../../../img/find/thumbs-categorii/";
$target_file2 = "" . basename($_FILES["img-edit"]["name"]);
$target_file = $target_dir . basename($_FILES["img-edit"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check file size
if ($_FILES["img-edit"]["size"] > 100000) {
$_SESSION['image-size'] = 1;
exit();
}
//
//Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" && $imageFileType != NULL) {
$_SESSION['image-format'] = 1;
exit();
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["img-edit"]["tmp_name"], $target_file)) {
} else {
echo "Sorry, there was an error uploading your file.";
// exit();
}
$query = "UPDATE descopera_second" .
"SET title='" . $title . "', text='" . $description . "', image='" .
$target_file2 . "', fk_descopera_first='" . $category .
"' WHERE id=" . $id;
var_dump($query);
exit();
$result = mysqli_query($con, $query);
// var_dump($query);
// exit();
if ($result) {
$_SESSION['edit_slider'] = 1;
header("Location: /dashboard/");
} else {
//
header("Location: /dashboard/");
}
}
}
?>
I want to keep the current path in database if the input with the image is empty. I don't know why, but my code currently stops at echo "Sorry, there was an error uploading your file."; and changes the path for the image, in my database. If the input is empty I want to keep the current path, because I just want to edit.
You define $uploadOk = 1, but that value never changes. So the following code, will always execute the else part of your condition.
if ($uploadOk == 0) {
} else {
/* Everything in here will be executed */
}
Now look at all of the code that inside of that one conditional block.
The first thing is another condition.
if (move_uploaded_file($_FILES["img-edit"]["tmp_name"], $target_file)) {
} else {
echo "Sorry, there was an error uploading your file.";
// exit();
}
Where you say your code is stopping means that move_uploaded_file failed. This would be expected if the user did not supply a file upload in the request. Because $target_file will be empty, and an empty string is probably not going to be a valid path on your filesystem, plus there's the fact that there was no file upload in the first place even if it were.
Everything else that happens inside that first conditional block then continues to happen anyway, unconditionally (i.e. updating your database even though there was no file uploaded).
$query = "UPDATE descopera_second" .
"SET title='" . $title . "', text='" . $description . "', image='" .
$target_file2 . "', fk_descopera_first='" . $category .
"' WHERE id=" . $id;
Try using var_dump to inspect the value of $target_file2 when this happens. It won't be what you expected. We know this because you initialize it as $target_file2 = "" . basename($_FILES["img-edit"]["name"]); above, and there was no file upload. So $_FILES is empty.
var_dump($target_file2);
So the better way to do this is to check if a valid file upload occurs first before attempting to update this value in your database. You probably meant to do this with your $uploadOk variable at the top.
if (isset($_FILES["img-edit"]["tmp_name"])) {
$query = "UPDATE descopera_second" .
"SET title='" . $title . "', text='" . $description . "', image='" .
$target_file2 . "', fk_descopera_first='" . $category .
"' WHERE id=" . $id;
} else {
$query = "UPDATE descopera_second" .
"SET title='" . $title . "', text='" . $description . "'," .
", fk_descopera_first='" . $category .
"' WHERE id=" . $id;
}
if (move_uploaded_file($_FILES["img-edit"]["tmp_name"], $target_dir)) {

php file path/file extension not saving to database in sql

I'm successfully scrambling and uploading images to my database however the file path isn't saving to the 'profile' tab in my sql database. What's wrong here? How do i fix it.
include 'core/init.php';
function change_profile_image($user_id, $file_temp, $file_extn) {
$file_path = 'profile/' . substr (md5(time()), 0, 10) . '.' . $file_extn;
move_uploaded_file($file_temp, $file_path);
mysql_query("UPDATE `users` SET `profile` = " . $file_path . "' WHERE `user_id` = " . (int)$user_id);
}
if (isset($_FILES['profile']) === true) {
if (empty($_FILES['profile']['name']) === true) {
echo 'y u no choose file!';
} else {
$allowed = array ('jpg', 'jpeg', 'gif', 'png');
$file_name = $_FILES['profile']['name'];
$file_extn = strtolower(end(explode ('.', $file_name)));
$file_temp = $_FILES['profile']['tmp_name'];
if (in_array($file_extn, $allowed) === true) {
change_profile_image($session_user_id, $file_temp, $file_extn);
header('Location: dontdelete.php');
exit();
}else {
echo 'y u no jpg or png or gif';
}
}
}
if (empty($user_data['profile']) === false) {
echo '<img src"', $user_data['profile'], '" alt="">';
}
?>
Your line of code:
mysql_query("UPDATE `users` SET `profile` = " . $file_path . "' WHERE `user_id` = " . (int)$user_id);
Look at
`profile` = " . $file_path . "'
You forgot a ' at the beginning of $file_path ;)

Categories