Verification of image accepting invalid files upload - php

I have a problem with my upload code it accepts invalid files and saves the filename in the database. I don't know what part of the code is wrong.
<?php
session_start();
if (!isset($_SESSION['LOGIN_STATUS'])) {
header('location:login.php');
}
?>
<?php
$allowedExts = array(
"gif",
"jpeg",
"jpg",
"png"
);
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 2000000) && in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
$image = $_FILES["file"]["name"];
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
$image = $_FILES["file"]["name"];
}
}
} else if ($_FILES["file"]["name"] == null) {
$image = $_SESSION['IMAGE'];
} else {
echo "Invalid file";
}
?>
<?php
include("includes/dbConnect.php");
$Department = $_SESSION['DEPARTMENT'];
$lname = $_POST['lname'];
$fname = $_POST['fname'];
$mname = $_POST['mname'];
$alias = $_POST['alias'];
$place = $_POST['place'];
$address = $_POST['address'];
$gender = $_POST['gender'];
$nationality = $_POST['nationality'];
$age = $_POST['age'];
$complexion = $_POST['complexion'];
$height = $_POST['height'];
$weight = $_POST['weight'];
$build = $_POST['build'];
$haircolor = $_POST['haircolor'];
$pecularities = $_POST['pecularities'];
$other = $_POST['other'];
$clname = $_POST['clname'];
$cfname = $_POST['cfname'];
$cmname = $_POST['cmname'];
$cnumber = $_POST['cnumber'];
$caddress = $_POST['caddress'];
$relationship = $_POST['relationship'];
$description = $_POST['description'];
$lastseen = $_POST['lastseen'];
mysql_query("INSERT INTO `persons`(LastName,FirstName,MiddleName,Image,Alias,Place,Address,Gender,Nationality,Age,Complexion,Height,Weight,Build,HairColor, Pecularities, Other, CLastName, CFirstName, CMiddleName, ContactNumber, Relationship, Status, CAddress,Description,Department,lastseen) VALUES ('$lname','$fname','$mname','$image','$alias', '$place','$address','$gender','$nationality','$age','$complexion','$height','$weight','$build','$haircolor','$pecularities', '$other','$clname','$cfname','$cmname','$cnumber','$relationship','Missing','$caddress','$description','$Department','$lastseen')");
header('location:admin_search.php');
mysql_close($con);
?>
The code above verifies the user input but it also saves invalid file the file name only not the file itself. I don't know what part has the error it execute the query part but the verification for upload image accepts different file type but I have extension allowExts.

you need to put exit as the code below.
else {
echo "Invalid file";
exit;
}

Related

PHP Overwrite Uploaded Image

I am trying some file upload code which I Googled.
Now Issue is when I try to upload image and if its already in folder then its over write and issues come. I Try Code From here and here as well but I face some error.
Here is my code. Can I do in this code that its upload file with some extra name which stop over write of existing file??
if(isset($_REQUEST['main']))
{
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
/*if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts)) {*/
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
if( move_uploaded_file($_FILES["file"]["tmp_name"], "../img/catalog/" . $_FILES["file"]["name"]) ){
$filepath = "img/catalog/" . $_FILES["file"]["name"];
}else{
echo $_FILES["file"]["name"]." unable to store";
}
}
/*}
} else {
echo "Invalid file";
}*/
}
$main = $_REQUEST['main'];
$sql="INSERT INTO image VALUES ('', '$filepath', '$main')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
You can check if the file exists using file_exists.
If it exist, add some extra characters to the file name. Then you can save it.
Here is a function that generates random characters :
function randomString($length) {
$str="";
$chars = "subinsblogabcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0;$i < $length;$i++) {
$str .= $chars[rand(0,$size-1)];
}
return $str;
}
Replace the code :
if( move_uploaded_file($_FILES["file"]["tmp_name"], "../img/catalog/" . $_FILES["file"]["name"]) ){
$filepath = "img/catalog/" . $_FILES["file"]["name"];
}else{
echo $_FILES["file"]["name"]." unable to store";
}
with :
$newLocation = "../img/catalog/" . $_FILES["file"]["name"];
if(file_exists($newLocation)){
$newLocation .= randomString(10); // We append 10 new characters
}
if( move_uploaded_file($_FILES["file"]["tmp_name"], $newLocation) ){
$filepath = str_replace("../img", "img", $newLocation); // make File Path starting with img/
}else{
echo $_FILES["file"]["name"]." unable to store";
}
The above code will check if the file exists. If yes, then a string of 10 random characters is appended to the file name and stored in the destination folder.
You didnt mention your problem but I think you have missed a point in your
if else
part. write it like this :
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
$_FILES["file"]["name"] = $_FILES["file"]["name"].$your_new_number;
}
if( move_uploaded_file($_FILES["file"]["tmp_name"], "../img/catalog/" . $_FILES["file"]["name"]) ){
$filepath = "img/catalog/" . $_FILES["file"]["name"];
}else{
echo $_FILES["file"]["name"]." unable to store";
}
}

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?

Syntax Error When Writing Data Into a Table - unexpected T_VARIABLE

Parse error: syntax error, unexpected T_VARIABLE in upload_file.php on line 44
The code worked until I added these lines :
Lines 42-44 :
$path = "uploads/" . $_FILES["file"]["name"];
$Link = mysql_connect($Host, $User, $Password);
$Query = "INSERT INTO $Table_7 VALUES ('0','"$path"')";
Thanks it sorta worked. The script is for uploading images into a folder. That part of works but I cannot write the image path into the table. I have a table with two fields :
picid - auto incrementing primary key
path - varchar(60)
Any idea what I'm doing wrong? I've added the full script.
UPDATE. FULL CODE
<?php
include "connect.php";
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 10000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("uploads/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $_FILES["file"]["name"]);
echo "Stored in: " . "uploads/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
$path = "uploads/" . $_FILES["file"]["name"];
$Link = mysql_connect($Host, $User, $Password);
$Query = "INSERT INTO $Table_7 VALUES ('0','{$path}')";
?>
You are missing you concatenation operator on line 44:
$Query = "INSERT INTO $Table_7 VALUES ('0','"$path"')";
should be
$Query = "INSERT INTO $Table_7 VALUES ('0','".$path."')";
or
$Query = "INSERT INTO $Table_7 VALUES ('0','$path')";
or
$Query = "INSERT INTO $Table_7 VALUES ('0','{$path}')";

if no file upload, file id in database should be: placeholder.gif

i have a form where you can put an image uploade, which is optional. with this script at the moment it writes upload/timestamp into my database. but i need to replace that with a placeholder if no file is uploaded. here is the code:
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 1024000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$path_parts = pathinfo($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $path_parts['filename'].'_'.time().'.'.$path_parts['extension']);
}
}
else
{
echo "Invalid file";
}
and:
$name1 = $_REQUEST['name1'];
$email1 = $_REQUEST['email1'];
$beschreibung1 = $_REQUEST['beschreibung1'] ;
$latitude = $_REQUEST['latitude'] ;
$longitude = $_REQUEST['longitude'] ;
$file = $_REQUEST['file'] ;
$pic = ("upload/" . $path_parts['filename'].'_'.time().'.'.$path_parts['extension']);
include 'bikemap_db_open.php';
$sql = "INSERT INTO input2 (f_name, f_e_mail, f_text, f_adr, f_dat, f_geom, f_foto)";
$sql = $sql . " VALUES ('" . $name1 . "','" . $email1 . "','" . $beschreibung1 .
"','" . $longitude . " " . $latitude . "', '" . date("d-m-Y") . "', ST_GeomFromText('POINT(" . $longitude . " " . $latitude . ")', 4326),'" . $pic . "')";
$result = pg_query($sql) or die('Query failed: ' . pg_last_error());
include 'bikemap_db_close.php';
header( "Location: /danke.html" );exit;
In the first code block
else
{
echo "Invalid file";
$fileupload = false;
}
In second codeblock
if ($fileupload == true){
$pic = ("upload/" . $path_parts['filename'].'_'.time().'.'.$path_parts['extension']);
}
else
{
$pic = 'placeholder.gif'; // you will need to specify the full path
}

PHP - file upload will not move file to directory

the file upload script is below...the storing of the file name in the DB is working fine, but the file is not being moved to the proper directory. the "Avatars" file is located in the "/httpdocs/" directory. I have set the permissions to "777".
<?php
require('dbconfig.php');
//generate a random string
function generateRandomString($length = 40) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$customname = generateRandomString();
$newimagename = "$customname." . pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
//echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
header ('Location: /dashboard.php?filetype=invalid');
exit();
}
else
{
//echo "Upload: " . $_FILES["file"]["name"] . "<br>";
//echo "Type: " . $_FILES["file"]["type"] . "<br>";
//echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
//echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
//echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"avatars/" . $newimagename);
//echo "Stored in: " . "profile_videos/" . $newimagename;
$storedtoken = $_COOKIE['login_token'];
$mysqlicon = mysqli_connect($db_host, $db_username, $db_password, $db_name);
//identify the user by comparing tokens
$find_user_id = mysqli_query($mysqlicon, "SELECT * FROM logins WHERE token='$storedtoken'");
//grab the user's UUID
while ($row = mysqli_fetch_array($find_user_id)) {
$uuid = $row['userID'];
mysqli_query($mysqlicon, "UPDATE families SET avatarURL='avatars/$newimagename' where husbandID='$uuid' OR wifeID='$uuid'");
mysqli_close($mysqlicon);
}
header ('Location: /dashboard.php');
}
}
}
else
{
header ('Location: /dashboard.php?profile-video-upload=invalid');
mysqli_close($mysqlicon);
exit();
}
?>

Categories