How can a user upload a profile picture on my codeigniter registration form

Asked
Active3 hr before
Viewed126 times

7 Answers

upload
90%

Step 3: Create Controller,Step 1: Download Fresh Codeigniter 3,application/controllers/ImageUpload.php,application/views/imageUploadForm.php

< ? phpdefined('BASEPATH') OR exit('No direct script access allowed');
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['image-upload'] = 'ImageUpload';
$route['image-upload/post']['post'] = "ImageUpload/uploadImage";
load more v
88%

I made a user registration form on the CodeIgniter framework so users can registrate to my website. Now the only thing that doesn't work is that I cant upload a profile picture. When I click on the register button I'm getting 2 errors. I want the profile picture to be uploaded in the product_foto column., How does the Bladesinging wizard's Extra Attack feature interact with the additional Attack action from the Haste spell? , By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy. , Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers

I modified your code. Try this

public
function register() {
   $data = array();

   $config = array(
      'upload_path' => 'upload',
      'allowed_types' => 'gif|jpg|png|jpeg',
   );
   $this - > load - > library('upload', $config);

   if (!$this - > upload - > do_upload('profiel_foto')) {
      $error = array('error' => $this - > upload - > display_errors());
      // var_dump( $error); die; check errors 
   } else {
      $fileName = $this - > upload - > data();
      $data['profiel_foto'] = $fileName['file_name'];
   }
   // voeg gebruiker toe aan database
   $data = array(
      'voornaam' => $_POST['voornaam'],
      'achternaam' => $_POST['achternaam'],
      'email' => $_POST['email'],
      'wachtwoord' => ($_POST['wachtwoord']),
      'startdatum' => date('Y-m-d'),
      'postcode' => $_POST['postcode'],
      'huisnummer' => $_POST['huisnummer'],
      'woonplaats' => $_POST['woonplaats'],
      'beschrijving' => $_POST['beschrijving'],
      'geboortedatum' => $_POST['geboortedatum'],
      'geslacht' => $_POST['geslacht'],
   );
   $this - > db - > insert('users', $data);

   $this - > session - > set_flashdata("success", "Uw account is nu geregistreerd, u kunt nu inloggen");
   redirect("auth/register", "refresh");
}
load more v
72%

//Use the rename() function.
rename('first_location/image1.jpg', 'new_location/image1.jpg');
load more v
65%

upload_form.php – this view contains the HTML form that has the input type of file and submits the selected file to the server for processing,CodeIgniter Routes | URL Routing with Example ,Add the following code to ImageUploadController.php,How to Download & Install CodeIgniter with Composer

<!DOCTYPE html>
<html>
<head>
    <title>CodeIgniter Image Upload</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div>
        <h3>Select an image from your computer and upload it to the cloud</h3>
        <?php
                if (isset($error)){
                    echo $error;
                }
            ?>
            <form method="post" action="<?=base_url('store-image')?>" enctype="multipart/form-data">
                <input type="file" id="profile_image" name="profile_image" size="33" />
                <input type="submit" value="Upload Image" />
            </form>
    </div>
</body>
</html>
load more v
75%

$profile_image = $file->getName(); This will return the Image file name what we will upload.,$file->move(“images”, $profile_image) move() method is used to upload the image from form to images folder.,$this->request->getFile(“profile_image”) – Reading file from requested parameters,$file->move(“images”) We can also use it as here. The second value when we want to change the name to something different name.

Here is the command to install via composer –

$ composer create - project codeigniter4 / appstarter codeigniter - 4
$ cp env.env

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create table with some columns.

CREATE TABLE `tbl_users`(
   `id`
   int(11) NOT NULL AUTO_INCREMENT,
   `name`
   varchar(120) DEFAULT NULL,
   `email`
   varchar(120) DEFAULT NULL,
   `phone_no`
   varchar(120) DEFAULT NULL,
   `profile_image`
   varchar(180) DEFAULT NULL,
   `created_at`
   timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
   PRIMARY KEY(`id`)
) ENGINE = InnoDB DEFAULT CHARSET = latin1;
 #-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 # DATABASE
 #-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
//...

$routes - > match(["get", "post"], "my-form", "User::myForm");

Back to terminal and run this spark command to create a model file.

$ php spark make: model User--suffix
< ? php

namespace App\ Models;

use CodeIgniter\ Model;

class UserModel extends Model {
   protected $DBGroup = 'default';
   protected $table = 'tbl_users';
   protected $primaryKey = 'id';
   protected $useAutoIncrement = true;
   protected $insertID = 0;
   protected $returnType = 'array';
   protected $useSoftDelete = false;
   protected $protectFields = true;
   protected $allowedFields = [
      'name',
      'email',
      'phone_no',
      'profile_image'
   ];

   // Dates
   protected $useTimestamps = false;
   protected $dateFormat = 'datetime';
   protected $createdField = 'created_at';
   protected $updatedField = 'updated_at';
   protected $deletedField = 'deleted_at';

   // Validation
   protected $validationRules = [];
   protected $validationMessages = [];
   protected $skipValidation = false;
   protected $cleanValidationRules = true;

   // Callbacks
   protected $allowCallbacks = true;
   protected $beforeInsert = [];
   protected $afterInsert = [];
   protected $beforeUpdate = [];
   protected $afterUpdate = [];
   protected $beforeFind = [];
   protected $afterFind = [];
   protected $beforeDelete = [];
   protected $afterDelete = [];
}
<!DOCTYPE html>
<html lang="en">
<head>
  
  <title>Image Upload with Form data in CodeIgniter 4 Tutorial</title>
  
</head>
<body>

   <?php
  if(session()->get("success")){
    ?>
      <h3><?= session()->get("success") ?></h3>
    <?php
  }
  if(session()->get("error")){
    ?>
    <h3><?= session()->get("error") ?></h3>
    <?php
  }
?>

<form action="<?= site_url('my-form') ?>" method="post" enctype="multipart/form-data">
   <p>
       Name: <input type="text" name="name" placeholder="Enter name"/>
   </p>

   <p>
       Email: <input type="email" name="email" placeholder="Enter email"/>
   </p>

   <p>
       Phone No: <input type="text" name="phone_no" placeholder="Enter phone"/>
   </p>

   <p>
     File Upload: <input type="file" name="profile_image"/>
   </p>
   <p>
     <button type="submit">Submit</button>
   </p>
</form>

</body>
</html>

Inside this folder we will save uploaded image. Please make sure this images folder should have the sufficient permission to store file.

$ php spark make: controller User
< ? php

namespace App\ Controllers;

use App\ Models\ UserModel;

class User extends BaseController {
   public
   function myForm() {
      if ($this - > request - > getMethod() == "post") {

         $file = $this - > request - > getFile("profile_image");

         $file_type = $file - > getClientMimeType();

         $valid_file_types = array("image/png", "image/jpeg", "image/jpg");

         $session = session();

         if (in_array($file_type, $valid_file_types)) {

            $profile_image = $file - > getName();

            // We can also use it like this. Automatically move function place the default image name into specified location.
            // Second value will be more beneficiary when we want to give a different name to the uploaded file.
            // $file->move("images"); 

            if ($file - > move("images", $profile_image)) {

               $userModel = new UserModel();

               $data = [
                  "name" => $this - > request - > getVar("name"),
                  "email" => $this - > request - > getVar("email"),
                  "phone_no" => $this - > request - > getVar("phone_no"),
                  "profile_image" => "/images/".$profile_image,
               ];

               if ($userModel - > insert($data)) {

                  $session - > setFlashdata("success", "Data saved successfully");
               } else {

                  $session - > setFlashdata("error", "Failed to save data");
               }
            } else {
               $session - > setFlashdata("error", "Failed to move file");
            }
         } else {
            // invalid file type
            $session - > setFlashdata("error", "Invalid file type selected");
         }

         return redirect() - > to(base_url());

      }

      return view("my-form");
   }
}
# Method to submit form

public
function myForm() {
   if ($this - > request - > getMethod() == "post") {

      $rules = [
         "name" => "required|min_length[3]|max_length[40]",
         "email" => "required|valid_email",
         "phone_no" => "required|min_length[9]|max_length[15]",
         "profile_image" => [
            "rules" => "uploaded[profile_image]|max_size[profile_image,1024]|is_image[profile_image]|mime_in[profile_image,image/jpg,image/jpeg,image/gif,image/png]",
            "label" => "Profile Image",
         ],
      ];

      if (!$this - > validate($rules)) {

         return view("my-form", [
            "validation" => $this - > validator,
         ]);
      } else {

         $file = $this - > request - > getFile("profile_image");

         $session = session();
         $profile_image = $file - > getName();

         if ($file - > move("images", $profile_image)) {

            $userModel = new UserModel();

            $data = [
               "name" => $this - > request - > getVar("name"),
               "email" => $this - > request - > getVar("email"),
               "phone_no" => $this - > request - > getVar("phone_no"),
               "profile_image" => "/images/".$profile_image,
            ];

            if ($userModel - > insert($data)) {

               $session - > setFlashdata("success", "Data saved successfully");
            } else {

               $session - > setFlashdata("error", "Failed to save data");
            }
         }
      }
      return redirect() - > to(base_url());
   }
   return view("my-form");
}
< ? php
// To print error messages
if (isset($validation)) {

   print_r($validation - > listErrors());
} ?
>

Start development server:

$ php spark serve
load more v
40%

CodeIgniter 2.* is in legacy mode and reached end-of-life on October 31, 2015. It means they are not going to support it anymore. It's there for projects already developed under this code, but you should not use it to start new ones, as if a security issue is found, …,CodeIgniter 2.* is in legacy mode and reached end-of-life on October 31, 2015. It means they are not going to support it anymore. It's there for projects already developed under this code, but you should not use it to start new ones, as if a security issue is found, you would have to patch it on your own.,Hi, I am new to framwork, Now I started to learn Codeigniter. I have installed version of CodeIgniter 2.2.6, from the following link https://codeigniter.com/download I want to do a simple registration form with image upload , storing that image in a seperate folder, image name in to database, and with validation too.,view.php its save on views folder in application >views

hi, AntonyRayan its good to go CI 3.x its secure , and firstly you can check out lots of tutorial avaliable for codignitor framework ,you can visit phpeverday.com , and basic code for insert data is this ...
on Controller create file tops.php

< ? php // controller class hit url index.php/tops/box/1 
class tops extends CI_Controller {

   function box($num1) //this is call from url
   {
      echo $num1.
      "Welcome in codeignitor";
      ////redirect(tops/blog); // for header() use this redirect()
      $this - > load - > view('test-view');
   }
   public
   function send() {
      $u = $this - > input - > post('username');
      $p = $this - > input - > post('subject');
      //echo $u . $p ;
      // you can use for image uploade files option 
      $this - > load - > model('model'); // its shows model  folder model.php                

      $data = array("username" => $u, "subject" => $p);
      $this - > model - > insertdata('reg', $data);

   }
   // you can create file in view folder name blog.php call here through url index.php/file name tops and function name blog
   // open this file index.php/tops/blog/
   public
   function blog() {

      $this - > load - > view('blog'); // view folder file name blog.php
   }

} ?
>

model.php

< ? php

class Model extends CI_Model {

   function insertdata($table, $data) {

      $this - > db - > insert($table, $data);

   }

}

?
> // save on models folder under application>models
load more v
22%

Next, go to the root of the CI installation and create a folder named “uploads”.,Go to the view folder (located at the root of the CI installation)  and create two new “view” files. Name these files file_view.php (displays the form containing file upload fields) and upload_success.php (displays the upload successful message).,Next, go to the controller folder and create a new file with the name upload_controller.php,For the structure of the image upload, I will start by creating a file in the views folder  with the name custom_view.php. Open this file and add the following code to it:

The next step is the creation of a file in the controller folder.  Name the file upload_controller.php. In this file, I will load a library for initializing the Upload class through the following code:

$this - > load - > library('upload');
load more v

Other "upload-undefined" queries related to "How can a user upload a profile picture on my codeigniter registration form"