0

I am creating a signup page for my website and I wanted to set the users profile picture as a default one for now until the user is ready to change. I know how to get the filename of the picture using an array and new DirectoryIterator but the problem is i want to upload the blob type into the database as well so when they want to change it, i can change both and not just the file name. I tried using

file_get_contents();

but it wasn't working and i got an error like

 Warning: file_get_contents(default-user-profilepic.png): failed to open stream: No such file or directory in C:\wamp64\www\MT\infoupdate.php on line 128

So what i want to do is, take a file from my file directory and upload it with the filename and file_tmp into the database. Here is my code

PHP

<?php

session_start();

if($_SERVER['REQUEST_METHOD'] =="POST"){

    //Set variables
    $fullname = trim($_POST['fullname']);
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $storePassword = password_hash($password, PASSWORD_BCRYPT, array('cost' => 10));
    $cpassword = trim($_POST['cpassword']);
    $boolean = true;

    //Check if values are empty
    if(!empty($fullname) && !empty($fullname) && !empty($email) && !empty($password) && !empty($cpassword) && !empty($_POST['gender'])){

        //Check if email is valid
        if(filter_var($email, FILTER_VALIDATE_EMAIL) == false){

            die ("Email is Not Valid!");
        }
        //Check if passwrod is greater 6
        if(strlen($password) < 6 && strlen($cpassword) < 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;
            }

        //Check if passwords match
        if(!password_verify($cpassword, $storePassword)){

            die ("Passwords DO NOT Match!");
        }

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

    }

        //Check if username is in DB
        $stmtUsername = $handler->prepare("SELECT * FROM generalusersdata WHERE username = :username LIMIT 1");

        $stmtUsername->execute(array(':username'=>$username));

        if($resultUsername = $stmtUsername->fetch()){

            die("Username is already in user! Please try a different one!");
        }

        $userid = $resultUsername['user_id'];
        //Check if EMAIL is in DB
        $stmtEmail = $handler->prepare("SELECT * FROM generalusersdata WHERE email = :email LIMIT 1");

        $stmtEmail->execute(array(':email'=>$email));

        if($resultEmail = $stmtEmail->fetch()){

                die("Email already in use! Please try a different one!");
            }

        $extensions = array('jpg', 'jpeg', 'png', 'gif', 'bmp');

        // init result

        // directory to scan
        $directory = new DirectoryIterator('images');

        // iterate
        foreach ($directory as $fileinfo) {
            // must be a file
            if ($fileinfo->isFile()) {
                // file extension
                $extension = strtolower(pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION));
                // check if extension match
                if (in_array($extension, $extensions)) {
                    // add to result
                    $file_name = $fileinfo->getFilename();
                }
            }
        }

        $isDev = 1;
        $gender = $_POST['gender'];
        //set up sql
        $query = "INSERT INTO generalusersdata(fullname, username, email, password, profile_image, isDev, gender)VALUES(:fullname, :username, :email, :storePassword, :file_name, :isDev, :gender)";

        $stmt = $handler->prepare($query);

        $stmt->bindParam(':fullname', $fullname, PDO::PARAM_STR);
        $stmt->bindParam(':username', $username, PDO::PARAM_STR);
        $stmt->bindParam(':email', $email, PDO::PARAM_STR);
        $stmt->bindParam(':storePassword', $storePassword, PDO::PARAM_STR);
        $stmt->bindParam(':file_name', $file_name, PDO::PARAM_STR);
        $stmt->bindParam(':isDev', $isDev, PDO::PARAM_STR);
        $stmt->bindParam(':gender', $gender, PDO::PARAM_STR);
        if(!$stmt->execute()){

             $_SESSION['error'] = true;
             header("Location: errorsignup.php");
             exit;

        }

        $_SESSION['username'] = $username;
        setcookie("username", $username, time() + 60*60*24*365);
        header("Location: developerUpload.php");

    //Empty else    
    }else{

        echo "Missing Values!";
        exit;
    }
}


?>
10
  • 1
    "but it wasn't working and i got a lot of errors." Can you please, share the errors with us? Commented Jul 22, 2017 at 5:35
  • Uuhm sorry but why are you looping through the images directory? I don't understand. You always endup with the last file because there is no break after setting $file_name. Commented Jul 22, 2017 at 5:39
  • And why storing it as blob while you have it on disk? Another part that is weird to me. Commented Jul 22, 2017 at 5:40
  • Thats how i learned it honestly. I want to put it in the "longblob" type on the SQL database @DigitalHuman Commented Jul 22, 2017 at 5:45
  • Hi @Jagr, meh. Don't do it. Unless there is no other way. Restoring a backup with images as blobs in DB's is a nightmare. Same for performance. Big tables (blob fields) don't fit in memory easily. Just keep file as files and leave them on the disk ;) Commented Jul 22, 2017 at 5:49

1 Answer 1

1

If I understand it correctly you have a set of images in a folder named images. Every user will receive a default profile picture. If they want to change their picture they choose another from that folder. If that is correct, you won't need to upload them as a blob. Here is a way you can do it:

  1. You will store just the filename in your user table
  2. For new users you'll store the default picture's filename In your view, i.e.: profile summary, you will use the img-tag and put the picture file name as a source.
  3. When he changes his profile picture you will update just the filename in the database.

Maybe that process above is an option for you.

Your code is producing your warning

Warning: file_get_contents(default-user-profilepic.png): failed to open stream: No such file or directory in C:\wamp64\www\MT\infoupdate.php on line 128

because the file path is not correct. You are working with a relative path, that means your current path is your infoupdate.php. It tries to find the requested file in the MIT folder. Since I don't know your directory structure, I can not provide a better description. If your Image folder is inside the MIT folder, you can try to change your Directory Iterator line to:

$directory = new DirectoryIterator('/images');

or use absolute path instead:

$directory = new DirectoryIterator('C:\wamp64\www\MT\images');
Sign up to request clarification or add additional context in comments.

2 Comments

Well all the user will update from a file they have, i just needed the picture to upload as their default profile picture for now. Thanks for the help because i used the "absolute path" and it worked :D
Hello MuratBa, my computer shut down on me earlier and all my unsaved code for this question was deleted. But the only thing i lost was the "directoryIterator" part but the problem is i can't remember how to submit the file, or image, from the "$directory" into the database as a "longblob". Can you help?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.