If input image is empty give me error - php

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

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

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)) {

File upload works only if all fields are filled in

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

renaming an image during uploading (PHP)

i have this code for uploading image and storing in database
i want to rename it to a random name first,then upload it and store in database
how should i change my code?
please help me!
here is my PHP code :
$imageFile=$_FILES['image'];
$file_name = $imageFile['name'];
$target_path = "images/news/".$file_name;
if(move_uploaded_file($imageFile['tmp_name'], $target_path)) {
echo "<div id=\"news\">";
echo "Image : "."<br>".$file_name;
echo "<br>";
echo "Successfuly Uploaded!";
echo "<br>";
$newstitle = $_POST['title'];
$newscontent = $_POST['content'];
$newsimage = "images/news/".$file_name;
$sql="insert into news (news_title,news_content,news_image,news_date) values ('$newstitle', '$newscontent','$newsimage',' $newsdate')";
if ($conn->query($sql) === TRUE)
{
echo "Image Stored in DB!</div>";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Try this
Random file name created using $random = md5(uniqid("") . time());
Here is working code that renames your file
$imageFile = $_FILES['image'];
$file_name = $imageFile['name'];
$random = md5(uniqid("") . time());
$target_path = "images/news/" . $random.$file_name;
if (move_uploaded_file($imageFile['tmp_name'], $target_path)) {
echo "<div id=\"news\">";
echo "Image : " . "<br>". $random . $file_name;
echo "<br>";
echo "Successfuly Uploaded!";
echo "<br>";
$newstitle = $_POST['title'];
$newscontent = $_POST['content'];
$newsimage = "images/news/" . $random. $file_name;
$sql = "insert into news (news_title,news_content,news_image,news_date) values ('$newstitle', '$newscontent','$newsimage',' $newsdate')";
if ($conn->query($sql) === TRUE) {
echo "Image Stored in DB!</div>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
feel free to ask ready to help you

PHP file upload restricting images over 20kb

I've created an image upload using PHP, the idea being that the image will save to a directory and the path to the the database which is pretty standard. The problem is it wont save anything over 20kb. I have increased the max upload and post max size in the php.ini file to 10M and have also set size to < 200000kb in the function but it makes no difference. Can somebody please tell me where i have been banging my head off this for days now :(
File upload function (based on example at W3Schools)
function upload_file(){
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["page_main_image"]["name"]);
$extension = end($temp);
if ((($_FILES["page_main_image"]["type"] == "image/gif")
|| ($_FILES["page_main_image"]["type"] == "image/jpeg")
|| ($_FILES["page_main_image"]["type"] == "image/jpg")
|| ($_FILES["page_main_image"]["type"] == "image/pjpeg")
|| ($_FILES["page_main_image"]["type"] == "image/x-png")
|| ($_FILES["page_main_image"]["type"] == "image/png"))
&& ($_FILES["page_main_image"]["size"] < 200000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["page_main_image"]["error"] > 0) {
echo "Return Code: " . $_FILES["page_main_image"]["error"] . "<br />";;
}
else {
echo "Upload: " . $_FILES["page_main_image"]["name"] . "<br />";
echo "Type: " . $_FILES["page_main_image"]["type"] . "<br />";
echo "Size: " . ($_FILES["page_main_image"]["size"] / 1024) . " kb<br />";
if (file_exists("uploads/" . $_FILES["page_main_image"]["name"]))
{
echo $_FILES["page_main_image"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["page_main_image"]["tmp_name"],
"uploads/" . $_FILES["page_main_image"]["name"]);
echo "Stored in: " . "uploads/" . $_FILES["page_main_image"]["name"] . "<br />";
$image="{$_FILES['page_main_image']['name']}";
}
}
}
else {
echo "Invalid file";
}
return $image;
}
The form processing is as follows:
<?php
if (isset($_POST['submit'])) {
//Process the form
$image = upload_file();
$project_id = $_POST['project_id'];
//var_dump ($project_id);
$wireframe_title = mysql_prep($_POST["wireframe_title"]);
$browser_title = $_POST["browser_title"];
$url_key = $_POST["url_key"];
$wireframe_type = $_POST["wireframe_type"];
//$image = $_POST["page_main_image"];
$page_bg_color = $_POST ["page_bg_color"];
$query = "INSERT INTO wireframes (";
$query .= " project_id, wireframe_title, browser_title, url_key, wireframe_type, page_main_image, page_bg_color";
$query .= " ) VALUES (";
$query .= " '{$project_id}','{$wireframe_title}', '{$browser_title}', '{$url_key}', '{$wireframe_type}', '{$image}', '{$page_bg_color}' ";
$query .= ")";
echo $query;
try { $result = mysqli_query($connection, $query);
} catch (Exception $e) {
return 'Caught exception: '+ $e->getMessage()+ "\n";
}
//Test if there was a query error
if ($result) {
//Success
// would normally use a redirect ie redirect_to("somepage.php");
//$message = "Subject created.";
redirect_to("wireframes.php?id=$project_id");
}else {
//failure
//$message = "Subject creation failed.";
//redirect_to("add_project.php");
echo $query;
}
} else {
// This is probably a GET request
redirect_to("add_edit_wireframe.php?id= echo $_GET[$project_id]");
}
?>
The size in $_FILES is expressed in bytes. 200.000 = around 195 kilobyte.
Did you tested it without that condition in the if statement?

Categories