File uploading in codeigniter4

edited September 2023 in PHP

Write the below code in Commonhelper so we can access the function whenever it is required


function file_upload($img, $path)

{

    // This Function is to Upload Image to A path and return The path and name of file

    if ($img->isValid() && !$img->hasMoved()) {

        $time = time();

        $file_name = $img->getClientName();

        $ext = $img->getExtension();

       

        // Specify the target directory where you want to save the uploaded file

        $targetDirectory = WRITEPATH . 'public/common_assets/admin/' . $path . '/';

       

        // Generate a unique file name

        $newFileName = $path . '_' . $time . '.' . $ext;


        $file_path_stored = '/writable/public/common_assets/admin/' . $path . '/'.$newFileName;


       

        // Move the uploaded file to the target directory with the new file name

        if ($img->move($targetDirectory, $newFileName)) {

            $response['error'] = 0;

            $response['file_path'] = $file_path_stored ;

            $response['file_name'] = $newFileName;

        } else {

            $response['error'] = 1;

            $response['file_path'] = null;

        }

        return $response;

    }

}


This function will return the file_path and file_name save it in the database wherever it is required......


Call this function from the Controller (or wherever required) as shown

$file=file_upload($this->request->getFile('images'), "file_upload");

where $this->request->getFile('images') will get the file from html form with name images and file_upload is the target directory

Sign In or Register to comment.