Tampilkan postingan dengan label Codeigniter. Tampilkan semua postingan
Tampilkan postingan dengan label Codeigniter. Tampilkan semua postingan

Minggu, 30 Agustus 2020

Save PNG image from HTML5 Canvas (the correct way, proved working!!)

This post is kind of a continuation of my previous post 'Take A Picture From Webcam With HTML5'. I had then an issue how to save the image localy. The image taken from the webcam is saved in base64 encoded data with this format data:image/png;base64,AAAFBfj....[base64 encoded data]

After I googled around, the most solution that I found told me just seperate the base64 data from that format and decode it directly to save the image. Unfortunately, its not that easy!!!

shortly, I'll show you how to do it correctly. This solution is shown here. Thanks mas bro Fazlurr!! you are the best.

again, I developed the application using Codeigniter and the code I show here is the function to save the image localy. This function is called by an AJAX function. 



function saveImage(){
     $img = str_replace('data:image/png;base64,', '', $_POST['data']);
     $img = str_replace(' ', '+', $img);
     $data = base64_decode($img);
     $file = FCPATH.'/image/page/'.$_POST['name'].'.png';
     $success = file_put_contents($file, $data);
     echo $success ? '1' : '0';
}



the AJAX send  two POST data; the image data taken from canva and the name used for this image. Take a look at the third line, this line is the key. Other solutions found in google don't have this line, so most of them failed to save the image correctly. 

Well, the funny thing is that I know it works but I don't know what does that third line do, so dont ask me why this code works...ehehehe....

Jumat, 12 Juni 2020

PHP Set session timeout

Quick post. This post will help me to recall how to set a session timeout in PHP someday. Lets cut the explanation what is actually happening behind the scene in PHP for timing out the session. As my other posts, I will put the source where I read this great and helpfull solution. Link. I'd like to thank the dude who wrote that post.

So, I'm still using CodeIgniter and I put this function on my Model for login. So here is my function:


    function session_timeout_check()
    {
        
        $timeout_max = 1800;//timeout after 30 minutes
        $time = $_SERVER['REQUEST_TIME'];

        if(isset($_SESSION['LAST_ACTIVITY']))
        {
            if($time - $_SESSION['LAST_ACTIVITY'] > $timeout_max)
            {
                return 1;
            }
            else
            {
                $_SESSION['LAST_ACTIVITY'] = $_SERVER['REQUEST_TIME'];
                return 0;
            }
        }
        else
        {
            return 1;
        }
    }

I put that function in the constructor of all controller:


    public function __construct()
    {    
        parent::__construct();
        $this->load->model(array("M_login"));
        session_start();
        if($this->M_login->session_timeout_check() == 1)
        {
            //unsetting session variable, destroying session and redirecting to login page
        }
    }

inside the if you can put other conditions to check the session.

so that's all folks.

Senin, 10 September 2018

Code Igniter, retrieving return value from view

You might need someday retrieving a return value from view. Well, I am glad that I finally knew it that it is possible.

So this is how we can do it.

The common usage of function to load a view is like this.

$this->load->view("myPage", $arrayOfData);


But if your view should return a value, then do this

$returnVal = $this->load->view("myPage", $arrayOfData, TRUE);

Yup, this function has a third parameter. If you set it as TRUE, than it will return the value, otherwise it will return CI Object.

Code Igniter ERROR syntax error, unexpected 'use' (T_USE)

Some of you might face this problem, when you try to integrate github library to your Project and you are using CodeIgniter.

The main problem is

You cannot put 'use' inside a function.

But you might have to use it inside your model. To solve it, I put the php file using the 'use' inside the 'views' directory and load it as a views.

In this example I am using the Github's shamir secret sharing library that is developed by Oliver Mueller and Stefan Gehrig.

model.php
<?php 

public function shamirSecretSharing()
{
       $data['message'] = 'this is a secret';
       return $this->load->views('shamir/compute');
}


?>

And here is my compute.php located in "..\application\views\shamir\compute.php".

compute.php
<?php 

require_once APPPATH. 'views/shamir/autoload.php';

use TQ\Shamir\Secret;

$shares = Secret::share($message, 3, 3);

return $shares;

?>

I'm not going to explain the function of the library. What I want to show is how I use the Library inside my model. If you ask me, what APPPATH mean. You can read it here.

required, required_once, include Problem in Codeigniter

I had a problem integrating a library downloaded from github in codeigniter. One of the problem is the "required_once" function.

I'm sure there are many ways to solve this problem. I have two ways to share in this post.

Problem:

In every library downloaded from github, we need to call the autoload.php file at the start using "required_once". In some chases, required_once will be used almost in every php file. It is an old way to integrate github library in your code.

First Way:
Load it as a view.
For example, you need to include the autoload.php file.
Put the whole directory of the library inside the directory of 'views' and do this in the controller

controller.php
<?php

public function myFunc()
{
    $this->load->view('yourLib/autoload');
    $this->load->view('yourPageFile');
}
?>

Or you can do that inside the model as well'

aModel.php
<?php

public function modelFunc()
{
    $var=$this->load->view('yourLib/autoload','',true);
    
    your code ....
}
?>

Take a look at the load views. There are 3 parameters of the view function. The first parameter is the file of the page that you want to show, second parameter is for the variables that will be used in the page and the third parameter is set to TRUE. It will tell the CI that you want to return a value from view. If you don't set it to TRUE, it will return an CI-Object.

Second Way:
Use APPPATH macro. APPPATH is a macro referring your application Path.

If I do this
include_once APPATH."views/myLib/autoload.php";

that will give you  
include_once "c:\xampp\htdocs\myApp\application\views\myLib\autoload.php";

I hope this can help you somehow

Minggu, 02 September 2018

Sending Email with PHP

I got a request to create a web Application with a requirement sending a Warning via E-mail. First thing I did was googling, "sending Email with PHP", "how to send Email with PHP", ect. Thanks to many website and its author that give me a lot of information how to do that. I do really thank you guys for every information that you provide on your website.

I found so many tutorial with the complete library and the example how to use it. Unfortunately, many don't work. BUT...I blame my self, I'm the one who doesn't know how to use it. Then, I stopped for a minute and try to figure it out, how is the logical steps for a web server using PHP to send an E-mail. let me straight to the point, we cannot send an E-mail just using the PHP. Maybe I'm wrong at this point, but if we really could do it, I'm sure that we should make some changes in our web server's configuration.

So, what can we do then? We create a Mail Client using PHP. 
  1. Check the mail client manual setting in your web host. If you are using cpanel, check in Email Accounts --> Connect Devices --> Set up Mail Client
  2. Download PHPMailer here. Thanks to Marcus Bointon that provides us this library.
  3. Create the autoload.php, read it here how to do it. 
Before I continue to the PHP code, lets create the autoload.php for the PHPMailer library. Here is how the autoload.php looks like:

<?php
/**
 * An example of a project-specific implementation.
 *
 * After registering this autoload function with SPL, the following line
 * would cause the function to attempt to load the \Foo\Bar\Baz\Qux class
 * from /path/to/project/src/Baz/Qux.php:
 *
 *      new \Foo\Bar\Baz\Qux;
 *
 * @param string $class The fully-qualified class name.
 * @return void
 */
spl_autoload_register(function ($class) {

    // project-specific namespace prefix
    $prefix = 'PHPMailer\PHPMailer';

    // base directory for the namespace prefix
    $base_dir = __DIR__ . '/src/';

    // does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        return;
    }

    // get the relative class name
    $relative_class = substr($class, $len);

    // replace the namespace prefix with the base directory, replace namespace
    // separators with directory separators in the relative class name, append
    // with .php
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    // if the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});

Put that autoload.php inside PHPMailer directory.

I am using Code Igniter, I put the PHPMailer inside the view. So I load it as a view to use the library.

This is how my function in controller looks like:

public function testMail()
{
    $this->load->view('PHPMailer/autoload');
    $this->load->view('sendMail');
}

and here is the sendMail.php


<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;


$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'mail.yourHost.com';                  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'user@yourHost.com';                 // SMTP username
    $mail->Password = 'password';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 26;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('user@yourHost.com', 'User's Name');
    $mail->addAddress('recepient@test.com', 'Recipient Name');     // Add a recipient
    //$mail->addAddress('recepient@test.com');               // Name is optional
    $mail->addReplyTo('user@yourHost.com', 'User's Name');
    //$mail->addCC('cc@example.com');
   // $mail->addBCC('bcc@example.com');

    //Attachments
   // $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Subject';
    $mail->Body    = 'write something here';
    //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}

?>

You can check your SMTP Configuration on your cpanel. That is already everything.

Selasa, 23 Januari 2018

codeIgniter, removing index.php in url

source : https://situsali.com/belajar-codeigniter-3-dasar-routing/

The default URL used by CI contains "index.php". This bothers some of us.
So here is how I remove the "index.php" inside the URL.


  • Make sure mod_rewrite module in Apache is already activated. This can be checked in httpd.conf. This file can be found in xampp/apache/conf/httpd.conf. Find a line with this LoadModule rewrite_module modules/mod_rewrite.so. If there is a hashtag at the beginning of the line, remove it. 
  • Restart Apache, if it is necessary 
  • Create a .htaccess file inside the CI folder, at the same level with application directory, system directory, user_guide directory and so on. 
  • Insert this code inside .htaccess: 
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

  • Finally, go to application/config/config.php. Set the value of $config['index_page'] to '' (blank) --> $config['index_page'] = '';

That's it

Sabtu, 20 Januari 2018

Storing Javascript value into PHP

Short note!
I'm programming a web app for a health clinic and I just had a problem to give a notification sound for the doctor if new patient registered.

I use SSE to update the list of the queuing patients. The number of the queuing patients will be reduced if one patient is served and added if a new patient registered. The notification sound should be ringed once when a new patient registered.

The question is, where should I put the update function since I save the header, the side menu and the body (content) separately.

If I put the update function in the body, the problem is I have to put the update function in every page. Well it is actually not a problem, it is just funny to put the same function in every page.

So I decide to put the function in the header, since every page uses the same header. The problem is wherever I browse through the web app, the notification sound just may only be ringed once!!!! That means, I have to store the current number of the queuing patients as a session variable. That is the solution, but the problem is how I can do that since the Javascript updating the number..???!!!!

For the record, Javascript is client side and php is server side. So it is imposible to save Javascript value into PHP, if I do it via Javascript. That is the second clue. I have to pass the Javascript value to PHP somehow and let the PHP stores the value to a session variable.

So this is how I do that:

  1. Storing: Use AJAX to pass the Javascript value to PHP
  2. Storing: Since I am using MVC, I make a function in Controller just for storing the value to a session variable.
  3. Fetching: Make a Javascript function to fetch the value of the session variable and call it on loading windows. Storing PHP value into Javascript variable should not be a problem. 
  4. Fetching: Put the AJAX function inside SSE and call it if the number of queuing patient is added.

Minggu, 03 Desember 2017

AJAX with POST in Codeigniter (CI)

Hi there, I just learned how AJAX works. I learned from www.w3school.com, it is really a great web that one can learn everything about programming Web Application.

So this is my summary that I learned so far.
Usually we use AJAX to query something from server without reloading the page. In this example I want to show how I can send two data to be processed in the server using POST.

Oh, I forget to mention that I'm using Codeigniter.

So here is the code in the client looks like if I use POST (in Viewer):
<script>
function test_ajax()
{
    url = 'get_jsondata';

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function(){
    if(this.readyState==4 && this.status == 200)
    {
               alert(this.responseText);
    }

    xhttp.open("POST", url, true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("var1=hallo&var2=halli");
}
</script>

First, take a look at the variable url. It has value of 'get_jsondata'. This value will call URL of (in my case, since I'm still working on local) http://localhost/myweb/index.php/c_home/get_jsondata. That means I have to prepare a function called 'get_jsondata' in Controller 'c_home'.

Second, take a look at the variable 'xhttp'. This variable is an object of XMLHttpRequest(). The real execution of the AJAX request is when calling the function 'send'. What the code does above is:

  1. define the callback function on 'onreadystatechange'. If the readystate change, the function will be called. I read in w3school, the function will be called 4 times.
  2. open specifies the type of request. the third parameter says whether the function should be asynchronous (true) or synchronous (false). If it is asynchronous, the browser will not wait for the response and continue process the web. On the other hand, if it is synchronous, the browser will wait for the response before processing the next step.
  3. If POST is used, the content of the request has to be defined. Just use it like that.
  4. Send the request with defining the variables and their values in string and separated with '&'.


In PHP, the function will look like this (Controller). Like I mentioned before, the function's name should be 'get_jsondata'.

function get_jsondata()
{
    echo $_POST['var1']."    ".$_POST['var2'];
}


Sabtu, 04 November 2017

add/remove HTML input dynamically with Javascript

Again, a posting to remind me again, in case I forget how to do this.
I'm in the middle of coding a web page for member's registration. Some member might have more than one phone number, so I want to have a webpage that the member can add the input form or remove it dynamically.

I use Codeigniter and Bootstrap to code.

So, here is a part of the HTML code:


<div class="form-group">
<div class="row">

<label class="col-sm-2 control-label text1">phone</label>

<div class="col-sm-1">

<a onclick="addTelp()">

<i class="icon_plus_alt2" style="float: right"></i>

</a>

</div>

<div class="col-sm-9">

<input type="text" class="form-control" name="telp[0]">

</div>

</div>
</div>
<div id="morephone">

</div>



the new input field will be put inside div with id "morephone".

Here is the javascript code to add new input field :


<script>
var i=1;
function addTelp()
{

var div=document.createElement('div');

div.className='form-group';

var attr="telp_"+i;

div.setAttribute('id', attr);

div.innerHTML='<div class="row" >\

<label class="col-sm-2 control-label text1"> </label>\

<div class="col-sm-1" >\

<a onclick="remove(this)" style="color:red" >

<i class="icon_minus_alt2" style="float: right"> </i>

</a>\

</div>\
<div class="col-sm-9" id="inti">\
<input type="text" class="form-control" name="telp['+i+']" id="idtelp'+i+'">\
</div>\
</div>';
document.getElementById('morephone').appendChild(div);
i++;
}
</script>

The sequence number for the id and the name of the input form is optional. I use it for my own purpose that I don't describe here.

Here is the generated HTML code from that function:

<div class="form-group" id="telp_1">
<div class="row">

<label class="col-sm-2 control-label text1"> </label>

<div class="col-sm-1">

<a onclick="remove(this)" style="color:red">

<i class="icon_minus_alt2" style="float: right"> </i>
</a>
</div>
<div class="col-sm-9">
<input type="text" class="form-control" name="telp[1]" id="idtelp1">
</div>
</div>
</div>


This is how I remove the input field:


<script>
function remove(input) {

var parent=document.getElementById('morephone');

node=input.parentNode.parentNode.parentNode

parent.removeChild(node);
}
</script>


Lets take a look at the third line of the function above.

node=input.parentNode.parentNode.parentNode

It was new for me and it took quite time to understand what was it. So here is the explanation:

Take a look at the generated HTML code. Onclick event is in HTML tag <a> and call a javascript function remove with a parameter "this". "this" refers to the tag <a>.

What I want to remove with the function "remove(this)" is one input field. That means I have to remove the whole generated HTML. To do that I have to get the tag <div> with id "telp_1", which is located 3 level above the <a>.

Now lets take a look again at this line:

node=input.parentNode.parentNode.parentNode

input refers to tag <a> where the function remove() called on mouse click.
input.parentNode refers to tag <div class="col-sm-1">
input.parentNode.parentNode refers to the tag  <div class="row">
input.parentNode.parentNode.parentNode referst to the tag  <div> with id telp_1 and this is what I want to have. Right now I will call it as an element Node.

The one who can remove a node is its parent. The parent is a node in one level above, that means the parent is <div> tag with id "morephone".

Selasa, 31 Oktober 2017

Session Data Lost after redirection in Codeigniter

I am using Codeigniter 3.0.6 and PHP 7.1.2. Problem that I faced is the session data lost after redirecting to another controller. After googled, this issues is kind of a bug in Codeigniter. I have tried many solution found in google and this link gives the solution that works for my case.

I did exactly the steps that are shown in that link :
  1. Go to system/libraries/Session/Session.php
  2. Comment session_start() by adding //. We want to relocate the sessionn_start().
  3. Find (using ctrl + f ) a comment that says "Security is king". Comment out all the line under that comment until the end of the function. In my case I commented out the line number 313 - 318.
  4. Go to the main index.php, it is the first index.php and located in the same directory with the sub-directories 'application', 'system', 'user_guide', etc. 
  5. Put 'session_start()' right after < ?php
Hope this can help you....

Senin, 30 Oktober 2017

Cross-Origin Resource Sharing (CORS) Problem in Codeigniter

Facing a problem with CORS while developing a web with Codeigniter, the console keeps giving this error message "...has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource"

I browsed and tried many solutions posted in web, many failed to solve my problem. Finaly, I found a solution that works, at least for me. This is the link, where I found the solution. Link

So this is the solution:

Open "config.php" which is located in ../application/config/config.php .
Under Base Site URL, change existing configuration with this:

$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);


This works like a charm....
Hope this can help you somehow...

Selasa, 27 September 2016

HTML5 Server Sent Event in Codeigniter

There are many sources describing about SSE in HTML5 and also with the code that can be downloaded. One source that I can recommend to read is this. W3school also describes SSE in a short, simple and clear explanation.

But, there are not many websites that gives tutorial using SSE in Codeigniter. I'm working on a project using Codeigniter that requires SSE to display a dynamic data. It was quite difficult for me at the beginning to implement SSE in MVC-way, since all the codes that I got from some tutorials are not programmed in MVC-way. 

Maybe it is not the best way to implement SSE in Codeigniter, but at least it works. 

At the client side I have a javascript code shown below that allows client to "subscribe" a stream of data from the server. I send JSON data from server.

var source = new EventSource("❬?php echo site_url('c_sse/loaddata');?❭");
    
  source.addEventListener("message", function(e) {
   document.getElementById("status").innerHTML = "MESSAGE";showdata(e);
   }, false);
   
  source.addEventListener("open", function(e) {
   document.getElementById("status").innerHTML = "OPENED";
   }, false);

  source.addEventListener("error", function(e) {
   document.getElementById("status").innerHTML = e.readyState;
   if (e.readyState == EventSource.CLOSED) {
    document.getElementById("status").innerHTML = "CLOSED";
     }
   }, false);
 } else {
  document.getElementById("notSupported").innerHTML = "SSE not Supported";
 }
}
  
function showdata(Jdat)
{
 var data = JSON.parse(Jdat);
   
 document.getElementById("result").innerHTML = data.name;
}
 

The MVC style code is already seen in there. Check the EventSource above, that is the way I call the function "loaddata" inside controller c_sse.php.

At the server side, I started to code from the controller. The function that is responsible for sending the data (for example) called "loaddata". The most important thing of SSE in server side are the first three line with "header" in the code. Those should be placed in this function and they will cause Error if I put those in the Viewer. So, here is how the function "loaddata" looks like.


function loaddata()
{
 header("Content-Type: text/event-stream");
 header("Cache-Control: no-cache");
 header("Connection: keep-alive");
  
 $this-❭load-❭model('m_sse');
 while(true)
 {
  $data['mydata']=$this-❭m_sse-❭compute_dashboard_data();
  $this-❭load-❭view('sse_view_fast',$data);
  sleep(1);
 }
}


m_sse is the model for computing the data. In my case the return's value of the function 'compute_dashboard_data( )' is JSON data.

The one who is responsible to flush the data to Client is the viewer. Wrongly coded in the viewer can make the performance of SSE much slower. Firstly, I'll show the code resulting slow SSE. Oh ya, I forgot to mention the syntax. The real data should be put behind the "data:".

the source code for sse_view_slow.php:

print "data:".$mydata;
ob_flush();
flush();

If you implement that code, you'll have to wait couple seconds or maybe even couple minutes until the data shown.

Better use this code:

sse_view_fast.php

print "data:".$mydata.PHP_EOL;
print PHP_EOL;

ob_end_flush();
flush();

Actually, that is it for the programming. That is how I implement SSE in Codeigniter.