ini_set('date.timezone', 'Asia/Jakarta');
$ts = date('Y-m-d H:i:s');
Tampilkan postingan dengan label PHP. Tampilkan semua postingan
Tampilkan postingan dengan label PHP. Tampilkan semua postingan
Sabtu, 17 Juni 2023
PHP Timestamp Jakarta
Just for my personal purpose to remind me something easy but easily forgettable as well.
Here is how we get timestamp for jakarta.
Kamis, 31 Desember 2020
Get Date of 1 month Ago with PHP
Hi again, at the first day of the year 2021 I wrote this post since my web app showed error while retrieving data between the date of one month ago until today.
So here is the way to get date of 1 month Ago.
$dateHelp = date("Y-m-d");
$monthAgo = Date("Y-m-d", strtotime($dateHelp."-1 Month"));
To get the date of N months later / ago, just change the text "-1 Month" to "+N Month" to get N months later or "-N Month" to get N months ago.
Here is the source where I read the solution. Source
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:
I put that function in the constructor of all controller:
inside the if you can put other conditions to check the session.
so that's all folks.
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.
Labels:
Codeigniter,
PHP,
session,
session timeout,
timeout
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.
and here is the sendMail.php
You can check your SMTP Configuration on your cpanel. That is already everything.
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.
- 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
- Download PHPMailer here. Thanks to Marcus Bointon that provides us this library.
- 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:
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:
<?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.
Labels:
Codeigniter,
github,
PHP,
PHPMailer,
Send Email
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:
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:
- Storing: Use AJAX to pass the Javascript value to PHP
- Storing: Since I am using MVC, I make a function in Controller just for storing the value to a session variable.
- 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.
- Fetching: Put the AJAX function inside SSE and call it if the number of queuing patient is added.
Labels:
AJAX,
Codeigniter,
Javascript value into PHP,
PHP,
Server Sent Event
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.
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.
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:
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
Actually, that is it for the programming. That is how I implement SSE in Codeigniter.
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.
Labels:
Codeigniter,
HTML5,
PHP,
Server Sent Event,
SSE,
Web
PHP: echo with " vs '
A simple thing about php echo that maybe I'm not the only one who hasn't realized the difference between echo using ".." and using '..'. Again, its a note for me in case I forget about this later.
echo "hali";
echo "halo";
The output of those commands will be:
hali
halo
If your php code like this:
echo 'hali';
echo 'halo';
your output would be:
halihalo
see the difference?
echo "hali";
echo "halo";
The output of those commands will be:
hali
halo
If your php code like this:
echo 'hali';
echo 'halo';
your output would be:
halihalo
see the difference?
Sabtu, 01 November 2014
foreach-loop in php
Menjawab pertanyaan "foreach-loop".
Perhatikan berikut:
------------------------------------------------------------
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
); foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}
-------------------------------------------------------------
------------------------------------------------------------
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
); foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}
-------------------------------------------------------------
foreach bekerja dengan membaca satu-persatu index array. Pada kasus diatas,
loop 1 dia membaca $a[one]
loop 2 dia membaca $a[two]
dst.
loop 2 dia membaca $a[two]
dst.
untuk interpretasi "foreach ($a as $k => $v)". $a adalah nama arraynya, $k adalah variabel nama index array disimpan dan $v adalah variabel dimana nilai dari array $a index ke- $k disimpan.
Jadi output dari code diatas adalah
$a[one] => 1.
$a[two] => 2.
$a[three] => 3.
$a[seventeen] => 17.
Semoga bisa membantu.
$a[one] => 1.
$a[two] => 2.
$a[three] => 3.
$a[seventeen] => 17.
Semoga bisa membantu.
Langganan:
Postingan (Atom)