0

On my website, i allow users to submit a profile picture and i check if the picture is "png or jpeg" and also i check if the file is less than "2 mb" and if it is, i display an error message. But when the file is less than the php ini upload max, it display the message but when it is greater i get a lot of php errors that is not what i wanted to display. How do i remove the errors and display my generated message to the user. I found a post but the post was how to read the errors. I only get those errors when the submitted file is greater than 200mb or the php ini upload max. When its lower, it goes fine. Here is my code and error messages

Error Messages enter image description here

PHP

<?php

session_start();

if(isset($_COOKIE['username'])){

    if($_SESSION['came_from_upload'] != true){

        setcookie("username", "", time() - 60*60);
        $_COOKIE['username'] = "";
        header("Location: developerLogin.php");
        exit;


    }

    if($_SERVER['REQUEST_METHOD'] =="POST"){
        $userid = $_SESSION['id'];
        $fullname = addslashes(trim($_POST['fullname']));
        $username = addslashes(trim($_POST['username']));
        $email = addslashes(trim($_POST['email']));
        $password = addslashes(trim($_POST['password']));
        $storePassword = password_hash($password, PASSWORD_BCRYPT, array('cost' => 10));
        $file_name = addslashes(trim($_FILES['file']['name']));
        $file_tmp = addslashes(trim($_FILES['file']['tmp_name']));

        try{

        // new php data object 
        $handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
        //ATTR_ERRMODE set to exception
        $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        }catch(PDOException $e){
             die("There was an error connecting to the database");   

        }


        $stmtChecker = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id = ?");
        $stmtChecker->execute(array($userid));
        if(!$stmtChecker->fetch()){

            setcookie("username", "", time() - 60*60);
            $_COOKIE['username'] = "";
            header("Location: developerLogin.php");
            exit;
        }


        if(!empty($fullname)){

            $stmtFullname = $handler->prepare("UPDATE generalusersdata SET fullname = ? WHERE user_id = ?");
            $stmtFullname->execute(array($fullname, $userid));
        }

        if(!empty($username)){

            $stmtCheckerUsername = $handler->prepare("SELECT * FROM generalusersdata WHERE username = ?");
            $stmtCheckerUsername->execute($username);
            if($resultCheckerUsername = $stmtCheckerUsername->fetch()){

                die("Username Already in use! Please try again");
            }

            $stmtUsername = $handler->prepare("UPDATE generalusersdata SET username = ? WHERE user_id = ?");
            $stmtUsername->execute(array($username, $userid));

        }

        if(!empty($email)){

            if(filter_var($email, FILTER_VALIDATE_EMAIL) == false){

            die ("Email is Not Valid!");
        }

            $stmtCheckerEmail = $handler->prepare("SELECT * FROM generalusersdata WHERE email = ?");
            $stmtCheckerEmail->execute($email);
            if($resultCheckerEmail = $stmtCheckerEmail->fetch()){

                die("Email Already in use! Please try again");
            }

            $stmtEmail = $handler->prepare("UPDATE generalusersdata SET email = ? WHERE user_id = ?");
            $stmtEmail->execute(array($email, $userid));

        }

        if(!empty($password)){

            if(strlen($password) < 6){

            die ("Password has to be GREATER than 6 characters!");

        }

            //Check if password has atleast ONE Uppercase, One Lowercase and a number
            if(!preg_match("(^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$)",$password)){

                    echo 'Password needs to be at least ONE uppercase, ONE lowercase, and a number!';
                    exit;
                }

            $stmtPassword = $handler->prepare("UPDATE generalusersdata SET password = ? WHERE user_id = ?");
            $stmtPassword->execute(array($storePassword, $userid));


        }

        if($_FILES['file']['error'] == UPLOAD_ERR_OK){


            $allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG);
            $detectedType = exif_imagetype($_FILES['file']['tmp_name']);
            if($extensionCheck = !in_array($detectedType, $allowedTypes) || $_FILES['file']['size'] < 2000){

                die("Failed to upload image; the format is not supported");
            }

             $dir = "userprofilepicture";

             if(is_dir($dir)==false){

                 mkdir($dir, 0700);
             }


            move_uploaded_file($file_tmp,$dir.'/'.$file_name);

            $stmtPassword = $handler->prepare("UPDATE generalusersdata SET profile_image = ? WHERE user_id = ?");
            $stmtPassword->execute(array($file_name, $userid));

        }

        echo "ok";

    }



}else{

    header("Location: developerLogin.php");
    exit;
}





?>
Jagr
  • 484
  • 2
  • 11
  • 31
  • 2
    Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – Rajdeep Paul Jul 20 '17 at 20:05
  • 2
    **WARNING**: When using PDO you should be using [prepared statements](http://php.net/manual/en/pdo.prepared-statements.php) with placeholder values and supply any user data as separate arguments. In this code you have potentially severe [SQL injection bugs](http://bobby-tables.com/). Never use string interpolation or concatenation and instead use [prepared statements](http://php.net/manual/en/pdo.prepared-statements.php) and never put `$_POST` or `$_GET` data directly in your query. Refer to [PHP The Right Way](http://www.phptherightway.com/) for guidance with this and other problems. – tadman Jul 20 '17 at 20:05
  • 2
    **WARNING**: `addslashes` is **not** an adequate SQL escaping method and if your reference material is telling you it is, your reference material is wickedly out of date. – tadman Jul 20 '17 at 20:05
  • You are accessing keys inside of $_POST that do not exist. – victor Jul 20 '17 at 20:07
  • What do you mean? – Jagr Jul 20 '17 at 20:08
  • @tadman can you possibly "dumb down" your comments because its really hard for me to understand D: – Jagr Jul 20 '17 at 20:08
  • $fullname = addslashes(trim($_POST['fullname'])); $_POST['fullname'] does not exist. That is what is throwing the error, I dont think those errors are related to php.ini configurations – victor Jul 20 '17 at 20:09
  • utilize if(isset($_POST['fullname'])) { // now we know the array has the index – victor Jul 20 '17 at 20:09
  • The thing is, i only get those errors when the submitted file is greater than 200mb or the php ini upload max. When its lower, it goes fine. – Jagr Jul 20 '17 at 20:11
  • try to do a print_r($_POST) with a request that is above the file size limit. This will show you what the contents of your $_POST array are. – victor Jul 20 '17 at 20:15
  • @Jagr The links explain the issues here in more details. There's a limit to how much I can explain in a single comment. Writing SQL code doesn't have to be difficult, but it can be **dangerous** if you arbitrarily inject user data in your queries like you've done here. Using prepared statements with placeholder values means you have things like `?` or `:username` in your query, no actual data, and the PDO database driver takes care of adding it in correctly and safely. This is all covered in the [official documentation](http://php.net/manual/en/pdo.prepared-statements.php). – tadman Jul 20 '17 at 20:29
  • The reason I raise these issues is it's important to internalize these habits early on or you'll create a mess of code that's a lingering liability to you, your career, and any companies that deploy it. Do it properly the first time and you'll never expose yourself to that risk. – tadman Jul 20 '17 at 20:30
  • Oh so i should use like bindParam and bindValue instead? – Jagr Jul 20 '17 at 20:32

2 Answers2

1

I think this will help you find your answer.

How to gracefully handle files that exceed PHP's `post_max_size`?

"If the size of post data is greater than post_max_size, the $_POST and $_FILES superglobals are empty. This can be tracked in various ways, e.g. by passing the $_GET variable to the script processing the data, i.e. , and then checking if $_GET['processed'] is set."

put this at beginning of your script after you start the session.

    if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){ //catch file overload error...
        $postMax = ini_get('post_max_size'); //grab the size limits...
        echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!<br>Please be advised this is not a limitation in the CMS, This is a limitation of the hosting server.<br>For various reasons they limit the max size of uploaded files, if you have access to the php ini file you can fix this by changing the post_max_size setting.<br> If you can't then please ask your host to increase the size limits, or use the FTP uploaded form</p>"; // echo out error and solutions...
        return $postMax
    }
victor
  • 802
  • 7
  • 12
  • 1
    Thank you so much @victor. I see now because when is over the max, it seems to be empty. I noticed that because when i use the "error_reporting" from the other answer and it told me that it is empty when it wasn't. Thank you so much. – Jagr Jul 21 '17 at 17:08
1

Try dumping out your whole Post after submitting the form with a oversized file. It could be empty. Since those are notice messages you can use

error_reporting(E_ALL & ~E_NOTICE);

in your file to get of them. But this will not solve the issues causing this errors.

MuratBa
  • 304
  • 1
  • 5
  • I pu his right under the code where i check if they submit? – Jagr Jul 20 '17 at 20:28
  • I would put it before : if($_SERVER['REQUEST_METHOD'] =="POST"){ – MuratBa Jul 20 '17 at 20:36
  • I did that and still getting the errors. This is the one i think is the problem. " Warning: exif_imagetype(): Filename cannot be empty in C:\wamp64\www\MT\developer_infoupdater.php on line 120" – Jagr Jul 20 '17 at 20:38
  • Thank you for the help, the error_reporting did help me notice the error message that was key to the fix :D – Jagr Jul 21 '17 at 17:10
  • Glad to be helpful :) – MuratBa Jul 22 '17 at 07:08