php & Postgresql & moodle: upload file and save in database using moodle db api

Trabla: php & Postgresql: uload file and save in database using moodle db api

Solving:

1. HTML form

<form method="POST" action="upload.php" >
 <fieldset >
<input type="file" name="image"> 
<input type="submit" value="Submit">
</fieldset>
</form>

2. PHP script "upload.php"

<?php
    
   require_once('../../../config.php');  // MOODLE config.php

   // Function declaration

   function upload(){

    global $DB;  // Moodle global DB object

    $temp_file_path = $_FILES['image']['tmp_name'];
    $temp_file_content = file_get_contents($temp_file_path);
    $data = bin2hex($temp_file_content);

    $sql = "INSERT INTO  mdl_my_images( image ) VALUES ( decode('{$data}', 'hex')  ) ";

   if( $DB->execute($sql)) {

      echo 'OK';
    }else{
        echo 'FAILED';
    }

  
}
 
     upload(); // Call function

}
?>

3. PHP script to get image from db "image.php"

<?php

require_once('../../../config.php');  // MOODLE config.php  


  // Function declaration

 function show_image(){

         global $DB;  // Moodle global DB object
   
          $id = intval($_GET['id']);

         $row = $DB->get_record_sql("SELECT id, encode(image, 'base64') as image FROM mdl_my_images where id = ? ", array('id'=>$id));

        header('Content-type: image/png');
        echo base64_decode($row->image);   


}
 

   show_image(); // Call function

?>





No comments:

Post a Comment