Tiadakan dirimu, maka Jatidirimu akan terungkap tanpa kata-kata.

Archive for the ‘PHP’ Category

Backlink Edu dan Profile Terbaik

Setelah sebelumnya saya sering menulis tentang Tutorial, sekarang saatnya sayamemberikan informasi tentang backlink dimana peran backlink tidak kalah pentingnya untuk menunjang kebutuhan blogger yang ada di dunia.

Maka dari itu berikut ini adalah list backlink yang sangat bermanfaat untuk menaikan DA PA blog sobat semua, silahkan digunakan dengan baik dan bijak, Terimakasih.

Backlink Profile
https://anigid.ucoz.ru/forum/
https://www.csfd.cz/registrace/
https://musescore.com/
https://idee.paris.fr/
https://www.etsy.com/
https://www.jssor.com/action/sign_up.aspx
https://www.dpreview.com/
https://github.com/
https://imgur.com/
https://www.flickr.com/
https://soundcloud.com/
https://knowyourmeme.com/
https://myspace.com/
https://www.mixcloud.com/
https://loop.frontiersin.org/
https://www.viki.com/
https://www.etsy.com/in-en/
https://www.fanfiction.net/
https://getsatisfaction.com/
https://profiles.wordpress.org/
https://www.buzzfeed.com/
https://gumroad.com/
https://social.microsoft.com/profile/u/edit/?
https://myanimelist.net/
https://marketplace.visualstudio.com/
https://coub.com/
https://pastebin.com/
http://flgclassifieds.cce.cornell.edu/

Backlink RSS
http://pages.cs.wisc.edu/~roundy/mrss/scripts/magpie_debug.php?url=https://bit.ly/2YI4CQa DA 91
https://www.neildouglas.co.uk/magpierss/scripts/magpie_debug.php?url=https://bit.ly/2YI4CQa DA 25
https://www.dur.ac.uk/scripts/rss/magpie/scripts/magpie_debug.php?url=https://bit.ly/2YI4CQa DA 73
http://pages.cs.wisc.edu/~roundy/mrss/scripts/magpie_debug.php?url=https://bit.ly/2YI4CQa DA 87
http://mmaster.dicea.unifi.it/lib/magpie/scripts/magpie_debug.php?url=https://bit.ly/2YI4CQa DA 87
http://www.zeelandnet.nl/libs/magpierss-0.72/scripts/magpie_slashbox.php?rss_url=https://bit.ly/2YI4CQa DA 55
https://dict.longdo.com/3rdparties/magpierss-0.72/scripts/magpie_debug.php?url=https://bit.ly/2YI4CQa DA 50
http://local.eteamsys.com/lib/magpie/scripts/magpie_debug.php?url=https://bit.ly/2YI4CQa DA 26
http://rep.morriscode.ca/rss/scripts/magpie_debug.php?url=https://bit.ly/2YI4CQa DA 20
http://letopisi.org/extensions/magpierss/scripts/magpie_simple.php?url=https://bit.ly/2YI4CQa DA 38
http://letopisi.org/extensions/magpierss/scripts/magpie_simple.php?url=https://bit.ly/2YI4CQa DA 38
https://www.abris-box-chevaux.fr/include/rss/scripts/magpie_debug.php?url=https://bit.ly/2YI4CQa DA 17
http://www.thetakozpontpecs.hu/ui/images/includes/magpierss/scripts/magpie_simple.php?url=https://bit.ly/2YI4CQa DA 13
http://www.sahten.com/magpierss/scripts/magpie_slashbox.php?rss_url=https://bit.ly/2YI4CQa DA 37
http://cotes-de-la-moliere.com/magpierss/scripts/magpie_simple.php?url=https://bit.ly/2YI4CQa DA 32
http://cktrappes.org/magpierss/scripts/magpie_simple.php?url=https://bit.ly/2YI4CQa DA 23
http://www.clubeinvest.com/bolsa/magpierss/scripts/magpie_simple.php?url=https://bit.ly/2YI4CQa DA 23
https://www.regolespinalemanez.it/inc/magpierss/scripts/magpie_simple.php?url=https://bit.ly/2YI4CQa DA 21
http://www.taex.de/texorama/feed2js/magpie_simple.php?url=https://bit.ly/2YI4CQa

BACKLINK EDU
BACKLINK KOMEN DOFOLLOW / NOFOLLOW

http://history.lib.ntnu.edu.tw/wiki/index.php
https://ilde2.upf.edu/levinsky/
https://nowewyrazy.uw.edu.pl/
https://trove.nla.gov.au/userProfile/user/user:public:indrak/about
https://connect.nl.edu/NLU-Strategic-Plan-2011-2016/blog/Lists/Comments/AllComments.aspx#InplviewHashb40b76c9-b9c3-4de8-916a-81744e8e9701=
https://graphql-ra-dev.roboticsacademy.fiu.edu/
https://open.mit.edu/
https://searchtech.fogbugz.com/default.asp?Suggestions
https://telegra.ph/
http://danse.chem.utk.edu/trac/timeline?from=2022-08-22T04%3A47%3A25-04%3A00&precision=second
http://www.juntadeandalucia.es/averroes/centros-tic/21700290/helvia/bitacora/index.cgi?wIdPub=178
https://gumroad.com/
http://groupspaces.com/
https://blogs.miamioh.edu/aaa201c/2016/12/asian-american-dance/
https://sites.williams.edu/cop21/blog-posts/who-gets-the-last-word-activism-in-climate-change-negotiations/
http://blogs.cae.tntech.edu/jwlangston21/2010/12/24/pdanet-and-internet-connection-sharing-without-dhcp-step-by-step/comment-page-94/
https://science.utm.my/seminarseries/2017/10/25/faculty-of-science-seminar-series-7-dr-sheela-chandren/
https://sio2.mimuw.edu.pl/c/pa-2018-1/forum/84/941/
http://mizwardomlank.blog.upi.edu/2013/09/17/intel-processor-generation/
http://sas.scrippscollege.edu/sas-blog/voice-article-october-2nd
https://centrenet.centre.edu/ICS/New_Campus_Life/Student_Organizations/Campus_Groups/Centre_College_Democrats/Discussion.jnz?portlet=Forums&screen=PostView&screenType=change&id=7720baf9-f99c-4e99-87e3-344a8ca276d0
http://www.de.kuas.edu.tw/community/forum.php?CID=17
https://my.wartburg.edu/ICS/Campus_Life/Campus_Groups/Chemistry_TA_Safety_Training/Discussion.jnz?portlet=Forums&screen=PostView&screenType=change&id=74ad25fc-8673-4528-87e0-0dacb95c8021
http://international.lander.edu/news1/fals-approved-culture-exchange-tajikistan
http://mde.nkust.edu.tw/community/viewtopic.php?CID=17&Topic_ID=21&no=45
https://compass.centralmethodist.edu/ICS/Campus_Life/Campus_Groups/Allied_Health_Bldg__Conference_Room_Schedule/Discussion.jnz?portlet=Forums&screen=PostView&screenType=change&id=11bff528-9fc6-49b5-b1ba-d1c49c6c21ee&p=4
https://www.tistr.or.th/tistr/newsboard/shownews.php?Category=newsboard&No=502
https://myjcc.sunyjefferson.edu/web/public/message-board/-/message_boards/message/3157935
http://dli.nkut.edu.tw/stu1/viewtopic.php?CID=17&Topic_ID=38&Order=&no=30&print=friendly
http://academic.kru.ac.th/academic/webboard/ViewWebboard.php?QuestionID=04866
https://cen.edu.au/index.php/component/k2/item/1-latest-news-analysis?start=1230
https://uniclaretiana.edu.co/node/485?page=1627
http://www.prachuabwit.ac.th/kmpw/index.php?name=webboard&file=read&id=288&mentid=63&actionpost=quote&commentpost=quote2
http://www.hy.ac.th/web/index.php?name=webboard&file=read&id=1094
http://banbueng.ac.th/index.php?name=webboard&file=read&id=3670
http://nuevocontinente.edu.ec/nuestro-staff/
http://wiki.cs.hse.ru/index.php?title=%D0%A1%D0%BB%D1%83%D0%B6%D0%B5%D0%B1%D0%BD%D0%B0%D1%8F:%D0%92%D1%85%D0%BE%D0%B4&returnto=%D0%9E%D0%B1%D1%81%D1%83%D0%B6%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5+%D1%83%D1%87%D0%B0%D1%81%D1%82%D0%BD%D0%B8%D0%BA%D0%B0%3ABuymoneyprinters&type=signup
https://portal.yokak.gov.tr/forum/?foro=signup
http://rasto.staf.upi.edu/2016/03/14/pengertian-motivasi-menurut-para-ahli/pengertian-motivasi/
http://globalblogs.cse.umn.edu/2018/01/day-11-makazi-homestead-residence-home.html
http://lumenstudet.cempaka.edu.my/2013/07/notebook-design.html?showComment=1612659400817#c7538272808616855491
http://www.akhbaroka.co.vu/2014/10/blog-post_436.html?showComment=1612659539516#c6445311845955651981

Cara Menambah Keamanan PHP dengan SuPHP

Salah satu cara untuk menambah keamanan PHP adalah dengan menginstall suPHP. Kalau anda baru mendengar suPHP, maka disini saya akan sedikit menjelaskan serta memberikan cara instalasinya.

SuPHP adalah tool yang digunakan untuk memperkuat keamanan server kita, bagi yang menggunakan PHP tentunya. Dengan adanya suPHP ini maka setiap skrip PHP tidak dapat dijalankan tanpa perizinan dari pemiliknya. SuPHP ini terdiri dari modul Apache (mod_suphp) dan setuid root binary (suphp) yang digunakan oleh modul Apache untuk mengubah uid dari proses eksekusi PHP.

Menambah Keamanan PHP dengan SuPHP

Berikut adalah cara instalasi suPHP dengan menggunakan apt-get:

Instalasi

apt-get install libapache2-mod-suphp

Disable modul PHP

a2dismod php5

Me-restart Apache

/etc/init.d/apache2 restart

Testing SuPHP

1
2
3
<?php
system('id');
?>

Jika anda menggunakan direktori selain /var/www sebagai lokasi penyimpanan web anda, maka anda juga harus mengubah  /etc/suphp/suphp.conf sebagai berikut:

;Path all scripts have to be in
docroot=/var/www/ -> ubah ke tempat lokasi penyimpanan web anda. Semoga bermanfaat.

 

Sumber = https://azuharu.net/php/tutorial-install-suphp/

Cara Setting ModSecurity untuk keamanan web server di ubuntu 14.04

Introduction

ModSecurity is a free web application firewall (WAF) that works with Apache, Nginx and IIS. It supports a flexible rule engine to perform simple and complex operations and comes with a Core Rule Set (CRS) which has rules for SQL injection, cross site scripting, Trojans, bad user agents, session hijacking and a lot of other exploits. For Apache, it is loaded as an additional module which makes it easy to install and configure.

Prerequisites

To follow this tutorial, you will need:

  • A Ubuntu 14.04 or Debian 8 Droplet.
  • A standard user account with sudo privileges, which you can set up by following the initial server setup tutorial for Ubuntu 14.04 or Debian 8.
  • A LAMP stack, which you can install by following the tutorial for Ubuntu 14.04 or Debian 8.

Step 1 — Installing ModSecurity

In this step, we will install ModSecurity.

First, update the package index files.

  • sudo apt-get update

Then, install ModSecurity.

  • sudo apt-get install libapache2-mod-security2 -y

You can verify that the ModSecurity module was loaded using the following command.

  • sudo apachectl -M | grep –color security2

If the output reads security2_module (shared), this indicates that the module was loaded.

ModSecurity’s installation includes a recommended configuration file which has to be renamed.

  • sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf

Finally, reload Apache.

  • sudo service apache2 reload

A new log file for ModSecurity will be created in the Apache logs directory at /var/log/apache2/modsec_audit.log.

Step 2 — Configuring ModSecurity

Out of the box, ModSecurity doesn’t do anything because it needs rules to work. In this step, we will first enable some configuration directives.

To find and replace the configuration directives in this step, we will be using sed, a stream editor. You can read the sed tutorial series to learn more about the tool.

Basic Directives to Enable

The default ModSecurity configuration file is set to DetectionOnly, which logs requests according to rule matches and does not block anything. This can be changed by editing the modsecurity.conf file and modifying the SecRuleEngine directive. If you are trying this out on a production server, change this directive only after testing all your rules.

  • sudo sed -i “s/SecRuleEngine DetectionOnly/SecRuleEngine On/” /etc/modsecurity/modsecurity.conf

The SecResponseBodyAccess directive configures whether response bodies are buffered (i.e. read by ModSecurity). This is only necessary if data leakage detection and protection are required. Therefore, leaving it on will use up Droplet resources and also increase the logfile size, so we will turn it off.

  • sudo sed -i “s/SecResponseBodyAccess On/SecResponseBodyAccess Off/” /etc/modsecurity/modsecurity.conf

Optional Directives to Modify

There are other directives you may want to customize by editing /etc/modsecurity/modsecurity.conf. The SecRequestBodyLimit and SecRequestBodyNoFilesLimit directives limit the maximum data that can be posted to your web application.

In particular, the SecRequestBodyLimit directive specifies the maximum POST data size. If anything larger is sent by a client the server will respond with a 413 Request Entity Too Large error. If your web application does not have any file uploads, this value can be left as it is. The pre-configured value specified in the configuration file is 13107200 bytes (12.5MB). If you want to change this value, look for the following line modsecurity.conf:

Optional `modsecurity.conf` directive change
SecRequestBodyLimit 13107200

Similarly, the SecRequestBodyNoFilesLimit limits the size of POST data minus file uploads. This value should be set as low as possible to reduce susceptibility to denial of service (DoS) attacks when someone is sending request bodies of very large sizes. The pre-configured value in the configuration file is 131072 bytes (128KB). If you want to change this value, look for the following line modsecurity.conf:

Optional `modsecurity.conf` directive change
SecRequestBodyNoFilesLimit 131072

A directive that affects server performance is SecRequestBodyInMemoryLimit. This directive is pretty much self-explanatory; it specifies how much of “request body” data (POSTed data) should be kept in the memory (RAM), anything more will be placed in the hard disk (just like swapping). Because Droplets use SSDs, this is not much of an issue. However, this can be changed if you have RAM to spare. The pre-configured value for this directive is 128KB. If you want to change this value, look for the following line modsecurity.conf:

Optional `modsecurity.conf` directive change
SecRequestBodyInMemoryLimit 131072

Step 3 — Testing an SQL Injection

Before configuring some rules, we will create a PHP script which is vulnerable to SQL injection to test ModSecurity’s protection.

Note: this is a basic PHP login script with no session handling or form sanitation. It is just used as an example to test the SQL injection and ModSecurity’s rules. It will be removed before the end of the tutorial.

First, access the MySQL prompt.

  • mysql -u root -p

Here, create a MySQL database called sample and connect to it.

  • create database sample;
  • connect sample;

Then create a table containing some credentials — the username sammy and the password password.

  • create table users(username VARCHAR(100),password VARCHAR(100));
  • insert into users values(‘sammy’,’password’);

Finally, exit the MySQL prompt.

  • quit;

Next, create the login script in Apache’s document root.

  • sudo nano /var/www/html/login.php

Paste the following PHP script into the file. Be sure to change the MySQL password in the script below to the one you set earlier so the script can connect to the database:

/var/www/html/login.php

<html>
<body>
<?php
    if(isset($_POST['login']))
    {
        $username = $_POST['username'];
        $password = $_POST['password'];
        $con = mysqli_connect('localhost','root','your_mysql_password','sample');
        $result = mysqli_query($con, "SELECT * FROM `users` WHERE username='$username' AND password='$password'");
        if(mysqli_num_rows($result) == 0)
            echo 'Invalid username or password';
        else
            echo '<h1>Logged in</h1><p>This is text that should only be displayed when logged in with valid credentials.</p>';
    }
    else
    {
?>
        <form action="" method="post">
            Username: <input type="text" name="username"/><br />
            Password: <input type="password" name="password"/><br />
            <input type="submit" name="login" value="Login"/>
        </form>
<?php
    }
?>
</body>
</html>

This script will display a login form. Open your browser and navigate to http://your_server_ip/login.php to see it. If you enter the correct pair of credentials, e.g. sammy in the Username field and password in the Password field, you will see the message This is text that only gets displayed when logged in with valid credentials. If you navigate back to the login screen and use incorrect credentials, you will see the message Invalid username or password.

The next job is to try an SQL injection to bypass the login page. Enter the following for the username field.

SQL injection username
' or true -- 

Note that there should be a space after -- for this injection to work. Leave the password field empty and hit the login button. The script shows the message meant for authenticated users! In the next step, we will prevent this.

Step 4 — Setting Up Rules

In this step, we will set up some ModSecurity rules.

Enabling the CRS

To make things easier, there are a lot of rules which are already installed along with ModSecurity. These are called the CRS (Core Rule Set) and are located in the /usr/share/modsecurity-crs directory. To load these rules, we need to configure Apache to read .conf files in these directories, so open the security2.conf file for editing.

sudo nano /etc/apache2/mods-enabled/security2.conf

Add the two following directives, highlighted in red, inside before the last line in the file (</IfModule>).

Updated security2.conf
        IncludeOptional /etc/modsecurity/*.conf
        IncludeOptional "/usr/share/modsecurity-crs/*.conf"
        IncludeOptional "/usr/share/modsecurity-crs/activated_rules/*.conf"
</IfModule>

Save and close the file.

Excluding Directories/Domains (Optional)

Sometimes it makes sense to exclude a particular directory or a domain name if it is running an application, like phpMyAdmin, as ModSecurity will block SQL queries. It is also better to exclude admin backends of CMS applications like WordPress. If you’re following this tutorial on a fresh server, you can skip this step.

To disable ModSecurity for a complete VirtualHost, place the following directives inside the <VirtualHost>[...]</VirtualHost> block in its virtual host file.

<IfModule security2_module>
    SecRuleEngine Off
</IfModule>

For omitting a particular directory (for example, /var/www/wp-admin):

<Directory "/var/www/wp-admin">
    <IfModule security2_module>
        SecRuleEngine Off
    </IfModule>
</Directory>

If you don’t want to completely disable ModSecurity in a directory, use the SecRuleRemoveById directive to remove a particular rule or rule chain by specifying its ID.

<LocationMatch "/wp-admin/update.php">
    <IfModule security2_module>
        SecRuleRemoveById 981173
    </IfModule>
</LocationMatch>

Activating the SQL Injection Rule

Next, we will activate the SQL injection rule file. The required rule files should be symlinked to activated_rules directory, which is similar to Apache’s mods-enabled directory. Change to the activated_rules directory.

  • cd /usr/share/modsecurity-crs/activated_rules/

Then create a symbolic link from the modsecurity_crs_41_sql_injection_attacks.conf file.

  • sudo ln -s ../base_rules/modsecurity_crs_41_sql_injection_attacks.conf .

Finally, reload Apache for the rules to take effect.

  • sudo service apache2 reload

Now open the login page we created earlier and try using the same SQL injection query on the username field. Because we changed the SecRuleEngine directive to On in step 2, a 403 Forbidden error is displayed. (If SecRuleEngine was left to the DetectionOnly option, the injection will be successful but the attempt would be logged in the modsec_audit.log file.)

Because this PHP login script is only meant to test ModSecurity, you should remove it now that the test is done.

  • sudo rm /var/www/html/login.php

Step 5 — Writing Your Own Rules

In this section, we’ll create a rule chain which blocks the request if certain words commonly associated with spam are entered in a HTML form.

First, we’ll create an example PHP script which gets the input from a text box and displays it back to the user. Open a file called form.php for editing.

  • sudo nano /var/www/html/form.php

Paste the following code:

/var/www/html/form.php
<html>
    <body>
        <?php
            if(isset($_POST['data']))
                echo $_POST['data'];
            else
            {
        ?>
                <form method="post" action="">
                        Enter something here:<textarea name="data"></textarea>
                        <input type="submit"/>
                </form>
        <?php
            }
        ?>
    </body>
</html>

Custom rules can be added to any of the configuration files or placed in ModSecurity directories. We’ll place our rules in a separate new file called modsecurity_custom_rules.conf.

sudo nano /etc/modsecurity/modsecurity_custom_rules.conf

Paste the following in this file. The two words we’re blocking are blockedword1 and blockedword2.

modsecurity_custom_rules.conf
SecRule REQUEST_FILENAME "form.php" "id:'400001',chain,deny,log,msg:'Spam detected'"
SecRule REQUEST_METHOD "POST" chain
SecRule REQUEST_BODY "@rx (?i:(blockedword1|blockedword2))"

The syntax for SecRule is SecRule VARIABLES OPERATOR [ACTIONS]. Here we used the chain action to match variables REQUEST_FILENAME with form.phpREQUEST_METHOD with POST, and REQUEST_BODY with the regular expression (@rx) string (blockedword1|blockedword2). The ?i: does a case insensitive match. On a successful match of all these three rules, the ACTION is to deny and log with the msg "Spam detected." The chain action simulates the logical AND to match all the three rules.

Save the file and reload Apache.

sudo service apache2 reload

Open http://your_server_ip/form.php in the browser. If enter text containing blockedword1 or blockedword2, you will see a 403 page.

Because this PHP form script is only meant to test ModSecurity, you should remove it now that the test is done.

  • sudo rm /var/www/html/form.php

Conclusion

In this tutorial, you have learned how to install and configure ModSecurity, and add custom rules. To learn more, you can check out the official ModSecurity documentation.

 

Sumber = https://www.digitalocean.com/community/tutorials/how-to-set-up-modsecurity-with-apache-on-ubuntu-14-04-and-debian-8

alidasi Codeigniter dengan Ajax Server Side

Validasi form pada web ada dua jenis di client side (sisi klien) dan server side (sisi klien). Tentu berdasarkan performa untuk validasi form server side lebih unggul di banding client side, silahkan googling sendiri perbedaan validasi Client Side dan Server Side  ^_^.

Validasi CodeIgniter Server Side With Ajax
Validasi CodeIgniter Server Side With Ajax
Disini akan dibahas Tutorial cara melakukan validasi form CodeIgniter menggunakan Server Side (Sisi Server) dengan Ajax. Untuk kategori validasinya sendiri terdiri beberapa kategori yaitu :
  • field tidak boleh kosong
  • field tidak boleh sama dengan sudah di input (!=duplikat input)
  • input hanya boleh number saja, dengan maksimal dan minimal karakter.
  • validasi email yang valid.
Owh yah.. pada Tutorial Form Validation CodeIgniter dengan Ajax Server Side, saya menggunakan CodeIgniter versi 3 dan juga framework Bootstrap 3.
Untuk alur Validasi CodeIgniter dengan Ajax Server Side :
  1. Input data field
  2. Data akan di proses menggunakan Ajax (Ajax mengirim ke Server Side)
  3. Server Side akan cek data, apakah kosong ? duplikat data ? Angaka atau huruf ? Minimal dan Maksimal karakter ?
  4. Jika cek Validasi Server Side berhasil, Server Side akan konfirmasi ke Ajax dan Ajax menampilakan pesan berhasil
  5. Jika cek Validasi Server Side gagal, Server Side akan konfirmasi ke Ajax berupa input field tidak memenuhi syarat, dan Ajax menampilkan pesan syarat yang harus dipenuhi.
Berikut Coding untuk view saya di bagi menjadi 5 yaitu head.php, nav.php, form.php content.php dan footer.php
Coding untuk head.php => berupa data css dan js
<!doctype html>
<html lang="en">
  <head>
    <title><?php echo $title;?></title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>asset/bootstrap.min.css">             
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />  
   <!-- Javascripts-->
    ?php%20echo%20base_url();?asset/jquery.min.js
    https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js  
    https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js  
    ?php%20echo%20base_url();?asset/bootstrap.min.js
    https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js
     
  </head>
Coding untuk nav.php => data coding untuk navbar menu
<nav class="navbar navbar-default">
  
<ul class="nav navbar-nav"> <li><a href="<?php echo base_url();?>">Home</a></li> <li><a href="<?php echo base_url();?>home/content">Data</a></li> </ul> </div> </nav>
Coding untuk form.php => data coding form input field
 <body>
   

Crud Insert Data


<?php echo form_open('home/data', 'id="mydata" '); ?>
Masukan nama lengkap anda.
<button type="submit" class="btn btn-primary">Save</button> </form> </div>
</div> </div> $('#mydata').submit(function(e){ e.preventDefault(); var fa = $(this); $.ajax({ url: fa.attr('action'), type: 'post' , data: fa.serialize(), dataType: 'json', success: function(response) { if(response.success == true) { $('#info').append('
' + 'Data Tersimpan' + '
'); $('.form-group').removeClass('has-error') .removeClass('has-success'); $('.text-danger').remove(); fa[0].reset(); $('.alert-success').delay(500).show(10, function() { $(this).delay(3000).hide(10, function() { $(this).remove(); }); }) } else { $.each(response.messages,function(key, value){ var element = $('#' + key); element.closest('div.form-group') .removeClass('has-error') .addClass(value.length > 0 ? 'has-error' : 'has-success') .find('.text-danger') .remove(); element.after(value); }); } } }); });
Untuk tampil data saya menggunakan DataTable Server Side, jadi Tutorial ini bisa juga di gunakan untuk Tampil data CodeIgniter 3 menggunakan DataTable Server Side.
Coding untuk content.php => data coding untuk tampil data
  <body>
  

Crud Edit & Delete


NIM Nama Email Edit Delete
</div>
Coding untuk footer.php => data coding penutup tag
  </body>
</html>
Untuk model coding saya berinama file mdata.php
Coding untuk mdata.php
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Mdata extends CI_Model
{
   var $table = "tbmhs";  
      var $select_column = array("id", "nim", "nama", "email");  
      var $order_column = array(null, "nim", "nama", null, null);  

  //query insert data
  function insert_all($table,$data) {
    $this->db->insert($table,$data);
  }

    function update_all($where,$data,$table) {
    $this->db->where($where);
    $this->db->update($table,$data);
  }

  // chech or ambil all data
 function check_all($table,$where,$limit) {
  $query = $this->db->get_where($table,$where,$limit);
  if($query->num_rows()==1)
  {
   return $query->result();
  }
  else {
   return false;
  }
 }

      function make_query()  
      {  
           $this->db->select($this->select_column);  
           $this->db->from($this->table);  
           if(isset($_POST["search"]["value"]))  
           {  
                $this->db->like("nim", $_POST["search"]["value"]);  
                $this->db->or_like("nama", $_POST["search"]["value"]);  
           }  
           if(isset($_POST["order"]))  
           {  
                $this->db->order_by($this->order_column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);  
           }  
           else  
           {  
                $this->db->order_by('nim', 'DESC');  
           }  
      }  
      function make_datatables(){  
           $this->make_query();  
           if($_POST["length"] != -1)  
           {  
                $this->db->limit($_POST['length'], $_POST['start']);  
           }  
           $query = $this->db->get();  
           return $query->result();  
      }  
      function get_filtered_data(){  
           $this->make_query();  
           $query = $this->db->get();  
           return $query->num_rows();  
      }       
      function get_all_data()  
      {  
           $this->db->select("*");  
           $this->db->from($this->table);  
           return $this->db->count_all_results();  
      }

          function delete_data($nim)  
      {  
           $this->db->where("nim", $nim);  
           $this->db->delete("tbmhs");  
           //DELETE FROM users WHERE id = '$user_id'  
      }   
 }

?>
Untuk Controller coding saya berinama file home.php
Coding untuk home.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller {

 function __construct()
 {
 parent::__construct();
 $this->load->model('mdata', '', TRUE);
 $this->load->helper(array('form', 'url'));
 }

 public function index()
 {
  $data['title'] = "Form Crud";
  $data['active'] = "active";
  $this->load->view('head',$data);
  $this->load->view('nav');
  $this->load->view('form');
  $this->load->view('footer');  
 }

 public function content()
 {
  $data['title'] = "Data Crud";
  $data['active'] = "active";
  $this->load->view('head',$data);
  $this->load->view('nav');
  $this->load->view('content');
  $this->load->view('footer');  
 }


 public function data() {

  $data = array ('success' => false, 'messages' => array());

  $this->load->library('form_validation');
  $this->form_validation->set_rules('nim', 'Nim', 'trim|required|numeric|min_length[10]|max_length[11]|callback_nimdata_check'); 
  $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]|callback_namadata_check');    
  $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[tbmhs.email]');  
  $this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>');


  if($this->form_validation->run()) {   


    $data = array (
       'nim' => $this->input->post('nim'),
       'nama' => $this->input->post('username'),
       'email' => $this->input->post('email')        
     );
    $this->mdata->insert_all('tbmhs',$data);
    
   $data['success'] = true;

  } else {
   foreach ($_POST as $key => $value) {
     $data['messages'][$key] = form_error($key);
   }   

  }
  echo json_encode($data);

 }


        public function nimdata_check($nim)
        {

         $where = array ('nim'=>$nim);
   $check = $this->mdata->check_all('tbmhs',$where,1);

                if ($check)
                {
                        $this->form_validation->set_message('nimdata_check', 'The {field} already exists');
                        return FALSE;
                }
                else
                {
                        return TRUE;
                }
        }

        public function namadata_check($str)
        {

         $where = array ('nama'=>$str);
   $check = $this->mdata->check_all('tbmhs',$where,1);

                if ($check)
                {
                        $this->form_validation->set_message('namadata_check', 'The {field} already exists');
                        return FALSE;
                }
                else
                {
                        return TRUE;
                }
        }


        function datauser() {             
           $fetch_data = $this->mdata->make_datatables();  
           $data = array();  
           foreach($fetch_data as $row)  
           {  
                $sub_array = array();                  
                $sub_array[] = $row->nim;  
                $sub_array[] = $row->nama;
                $sub_array[] = $row->email;  
                $sub_array[] = '<button type="button" name="update" id="'.$row->nim.'" class="btn btn-info btn-xs update">Update</button>';  
                $sub_array[] = '<button type="button" name="delete" id="'.$row->nim.'" class="btn btn-danger btn-xs delete">Delete</button>';  
                $data[] = $sub_array;  
           }  
           $output = array(  
                "draw"                    =>     intval($_POST["draw"]),  
                "recordsTotal"          =>      $this->mdata->get_all_data(),  
                "recordsFiltered"     =>     $this->mdata->get_filtered_data(),  
                "data"                    =>     $data  
           );  
           echo json_encode($output);  
      }  


        function delete_nim()  
      {             
           $this->mdata->delete_data($_POST["nim"]);             
      } 


         function danim()  
      {  

           $output = array();             
           $data = $this->mdata->check_all('tbmhs', array('nim'=>$_POST["nim"]),1);           
           foreach($data as $row)  
           {  
                $output['nim'] = $row->nim;  
                $output['nama'] = $row->nama;
                $output['email'] = $row->email;  
           }  
           echo json_encode($output);  
      }  
  
}
Silahkan jalankan di localhost atau mau upload hosting free untuk demo mangga ^_^….
Demikian tutorial cara validasi form CodeIgniter 3 dengan Ajax Server Side atau Tutorial cara menampilkan data CodeIgniter 3 dengan DataTable Server Side.
Sumber = https://fahmiffa.blogspot.co.id/2017/12/tutorial-validasi-codeigniter-3-Ajax-Server-side.html?m=1

Membuat Library Sendiri di Codeigniter

Halo guys! Ga kerasa udah lebaran lagi ya! saya mau ngucapin Minal Aidzin Wal Faidzin, mohon maaf lahir dan batin kalau saya sering salah di blog ini baik itu yang disengaja maupun yang ga disengaja. OK, sekarang saya udah balik lagi nich ke kosan jadi ya udah mulai beraktifitas normal lagi.

Pada kesempatan kali ini saya mau ngebahas tutorial bagaimana membuat library sendiri di Codeigniter. Jadi gini loh, misalkan kamu pernah bikin sebuah function atau class di PHP Native / No Framework, nah ketika kamu beralih ke Codeigniter tentu kamu ingin function itu bisa digunakan kembali tanpa harus menulis ulang codenya di controller.

Ok, saya asumsikan kamu udah menginstall dan juga membangun sebuah aplikasi di Codeigniter. Sekarang kita bikin library dulu, saya bikin contohnya gini aja ya

taruh file tersebut di folder /application/libraries dan beri nama sesuai dengan nama classnya. Karena pada contoh disini nama classnya adalah Contoh maka nama filenya adalah Contoh.php

Nah sekarang kita tinggal load library tersebut

Gampang kan? nah supaya Codeigniter dapat memuat library-nya secara automatis saat aplikasi berjalan, kamu bisa memasukan nama classnya di file application/config/autoload.php. Cari baris yang membuat code seperti ini

Kamu tinggal masukkan nama class library yang udah kamu buat tadi menjadi seperti ini

Keuntungannya ? kamu ga usah repot-repot memanggil library-nya lagi, kamu tinggal memanggil fungsinya saja

Bahkan kamu bisa memanggilnya di view seperti ini

Gampang banget kan? Silahkan dicoba dan semoga bermanfaat 😀

 

Sumber = https://elcicko.com/membuat-library-sendiri-di-codeigniter

Mengatasi Error: The URI You Submitted Has Disallowed Characters Pada Codeigniter

Baru belajar Codeigniter, pas nyoba kodingan dari tutorial ada error “The URI you submitted has disallowed characters”. Lantas saya jadi kaget, kok malah error padahal di video tutorialnya biasa aja tuh.
Setelah itu saya coba tanya om google, akhirnya ketemu juga cara terjitu untuk mengatasi masalah tersebut.

Caranya simple, cukup mengikuti 2 langkah tutorial dibawah :

1. Edit file URI.php (system/libraries/URI.php)

Cari baris:

if ( ! preg_match(“|^[“.preg_quote($this->config->item(‘permitted_uri_chars’)).”]+$|i”, rawurlencode($str)))

Ganti dengan :

if ( ! preg_match(“|^[“.($this->config->item(‘permitted_uri_chars’)).”]+$|i”, rawurlencode($str)))

2. Edit file config.php (system/application/config/config.php)

Cari baris:

$config[‘permitted_uri_chars’] = ‘a-z 0-9~%.:_-‘;

Ganti dengan :

$config[‘permitted_uri_chars’] = ‘a-z 0-9~%\.\:_\-‘;

Allhammdulillah setelah dicoba akhirnya error_nya musnah :p

Sumber = http://www.priawadi.com/2012/05/mengatasi-error-uri-you-submitted-has.html;

Menampilkan Pesan Error Di Webserver ( Apache ) Ubuntu

Untuk belajar PHP kita memerlukan yang namanya webserver, dan ketika kita belajar PHP terkadang saat kita mengetik sebuah program ada kesalahan dalam penulisan script atau kode program, yang mengakibatkan program yang kita buat itu tidak berjalan. Secara default setelah menginstall Webserver di linux, pesan error tidak di tampilkan di browser.

Akibatnya jika ada kesalahan dalam penulisan kode program maka yang terjadi adalah browser akan menampilkan pesan “500 INTERNAL SERVER ERROR”. Tentunya ini akan menyulitkan kita dalam menganalisa permasalahan yang terjadi pada program PHP yang kita kerjakan.

Untuk memudahkan kita dalam proses development, kita bisa menampilkan pesan Error tersebut pada browser dengan mengedit file PHP.ini yang terletak di folder /etc/php/7.0/apache2/php.ini dengan cara mengganti parameter OFF pada display_error dan display_starup_error mengjadi ON. setelah itu kita restart service apache nya.

Berikut adalah langkah – langkah memunculkan pesan Error PHP di browser :

1.Buka file php.ini menggunakan aplikasi nano pada folder /etc/php/7.0/apache2/php.ini, caranya :

2.Cari kata display_error dengan menekan CTRL + W ( jika menggunakan nano editor ) lalu ketikkan display_error.

3.Ubah parameter Off menjadi On

4.Dengan cara yang sama lakukan  pada display_startup_errors

5.Restart server dengan menjalankan perintah berikut ini pada terminal

Sekian dari saya, Terima Kasih

Sumber = https://phpbatch3.wordpress.com/2016/12/07/menampilkan-pesan-error-di-webserver-apache-ubuntu/

Membuat Laporan menggunakan lib mPDF pada CI

Bagian ini membahas proses pembuatan salah satu laporan untuk aplikasi Simple Kasir yang telah dibahas tahun lalu. Baru sempat merangkumnya sekarang. 🙂

Contoh laporan yang akan dibuat adalah laporan penjualan untuk bulan tertentu. Pembuatan laporan ini menggunakan lib dari mPDF yang bisa diunduh disini. Pada contoh ini digunakan mPDF versi 5.7, jika ingin menggunakan versi yang terbaru silahkan. Pada situs ini juga disediakan dokumentasi yang cukup lengkap yang bisa dijadikan sebagai bahan acuan pembangunan laporan.

Langkah-langkah awal yang harus dilakukan agar bisa menggunakan mPDF pada CI adalah :

1. Ekstrak file MPDF57.zip yang sudah diunduh sebelumnya. Hasil ekstraksi berupa folder MPDF57 letakkan di folder application/libraries/MPDF57, kita bisa menghapus beberapa file atau folder yang tidak diperlukan, misalnya : folder example, iccprofiles, graph_cache.

Lib mPDF memerlukan fungsi mb_string bawaan dari php, jadi pastikan pada file php.ini extension php_mbstring.dll ter-enable.

2. Agar bisa digunakan dengan mudah dalam CI, kita buat class pdf yang akan membungkus lib mPDF ini. Pada folder application/libraries buat file pdf.php dan isi dengan code berikut :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php if ( ! defined('BASEPATH')) exit('Tidak ada akses langsung script diperbolehkan');
class pdf{
    function pdf(){
        $CI =& get_instance();
        log_message('Debug', 'mPDF class is loaded.');
    }
    function load($param=NULL){
        include_once APPPATH.'libraries/MPDF57/mpdf.php';
        if($params == NULL){
            $param = '"en-GB-x","A4","","",10,10,10,10,6,3';
        }
        return new mPDF($param);
    }
}
 /* End of file pdf.php
    Location ./application/libraries/pdf.php */

Pada class pdf terdapat fungsi load yang digunakan untuk memuat lib mPDF. Jika saat memanggil fungsi load tidak ada parameter yang dilewatkan maka secara default fungsi ini akan menginstansiasi object mPDF dengan parameter = “en-GB-x”,”A4″, “”, “”, 10, 10, 10, 10, 6, 3; dimana urutan parameternya adalah : mode, format kertas, font size, font, margin left, margin right, margin top, margin bottom, margin header, margin footer, orientasi kertas (bisa diisi dengan p / portrait atau l / landscape).

Sampai tahap ini library pdf sudah bisa digunakan. Cara memuat lib ini sama seperti memuat lib lainnya, cukup dengan syntax : $this->load->library(‘pdf’);. Dan untuk mendapatkan object dari class mPDF dengan memanggil fungsi load dengan syntax : $pdf=$this->pdf->load();.

3. Buat helper pada application/helpers dengan nama file “common_helper.php”. Tambahkan fungsi “getMonthName” untuk mendapatkan nama-nama bulan, fungsi “get5LastYears” untuk mendapatkan daftar tahun lima tahun kebelakang dan fungsi “getNameOfMonth” untuk mendapatkan nama bulan dari nomor urut bulan. Code-nya :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php if ( ! defined('BASEPATH')) exit('Tidak ada akses langsung script diperbolehkan');
if ( ! function_exists('getMonthNames')){
    function getMonthNames(){
        $namaBulan = array(
            1 => 'Januari',
            2 => 'Februari',
            3 => 'Maret',
            4 => 'April',
            5 => 'Mei',
            6 => 'Juni',
            7 => 'Juli',
            8 => 'Agustus',
            9 => 'September',
            10 => 'Oktober',
            11 => 'November',
            12 => 'Desember');
        return $namaBulan;
    }
}
if( ! function_exists('getNameOfMonth')){
    function getNameOfMonth($bln){
        $namaBulan = getMonthNames();
        return $namaBulan[(int)$bln];
    }
}
if( ! function_exists('getg5LastYears')){   
    function get5LastYears(){
        $listTahun = array();
        $thnNow = intval(date('Y'));
        for($i=$thnNow-4; $i<=$thnNow; $i++){
            $listTahun[(string)$i] = (string)$i;
        }
        return $listTahun;
    }
}   
/*     End of file common_helper.php
    Location ./application/helpers/common_helper.php */

4. Buat controller untuk menampilkan halaman cetak laporan dengan nama lapPenjualanPerBulan.php. Pada bagian constructor muat lib template, table dan validation serta model item dan user. Buat fungsi _set_fields yang akan menampung nilai inputan bulan dan tahun.

Fungsi index akan menampilkan halaman generate laporan dengan memilih bulan dan tahun terlebih dahulu. Untuk mengisi dropdownlist bulan dan tahun, digunakan fungsi dari helper yang sebelumnya sudah kita buat, muat helper dengan syntax : $this->load->helper(‘common_helper’); dan untuk memanggil fungsinya cukup dengan syntax : getMonthNames() dan get5LastYears(). Code-nya :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function __construct(){
    parent::__construct();
    //load lib:
    $this->load->library('template','table');       
    //load model:
    $this->load->model('item_model', '', TRUE);
    $this->load->model('user_model', '', TRUE);
}
function index(){
    if($this->session->userdata('logged_in')) {           
        $session_data = $this->session->userdata('logged_in');
        $data['jabId'] = $session_data['jab'];
        $data['judul'] = 'Penjualan';
        
        $this->load->helper('common_helper');
        $data['cbBulan'] = getMonthNames();
        $data['cbTahun'] = get5LastYears();
        $data['lap'] = 'lapPenjualanPerBulan';
        
        $this->validation->namaBulan = date('m');
        $this->validation->tahun = date('Y');
        
        $this->template->display('laporan/lapBlnan', $data);
    }else{ //jika tidak ada session, redirect ke halaman login
        redirect('login', 'refresh');
    }
}

Tambahkan fungsi loadReport yang akan menghasilkan file pdf yang akan di tampilkan di tab baru, dalam membuat pdf digunakan lib mPDF yang sudah dibungkus dalam class pdf sebelumnya.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
function loadReport(){
    if($this->session->userdata('logged_in')) {           
        $session_data = $this->session->userdata('logged_in');           
        $data['bulan'] = $this->input->post('bln');
        $data['tahun'] = $this->input->post('thn');
        $this->load->helper('common_helper');
        $data['tglCetak'] = date('d') .' '. getNameOfMonth(date('m')) . ' ' . date('Y');
        //As PDF creation takes a bit of memory, we're saving the created file in /downloads/reports/
        $pdfFilePath = FCPATH."/downloads/reports/lapJualBln".date('F').".pdf";
        
        if(file_exists($pdfFilePath)==FALSE){
            ini_set('memory_limit', '64M');
            //generate table :
            $items = $this->item_model->GetLapJualPerBln($data['bulan'] . '-' . $data['tahun']);               
            $this->load->library('table');
            $this->table->set_empty("&nbsp;");
            $this->table->set_heading('No', 'Kode Barang', 'Nama Barang', 'Foto', 'Jumlah Terjual');
            if($items != false){
                $i=0;
                foreach($items as $brg){
                    $this->table->add_row(
                        ++$i,
                        $brg->IdBrg,
                        $brg->NamaBarang,
                        ($brg->GambarBarang!=null) ?
                        '<img width="100" src="data:image/jpeg;base64,'.base64_encode($brg->GambarBarang).'">' : '-',
                        $brg->jumTerjual
                    );
                }
            }else{
                $this->table->add_row("","","Tidak ada barang yang terjual","","");
            }
            $data['table'] = $this->table->generate();   
            
            $data['bulan'] = getNameOfMonth($data['bulan']);
            
            $peg = $this->user_model->GetUserByUserName($session_data['username']);
            $data['namaPeg'] = $peg->NamaPengguna;
            
            $html = $this->load->view('laporan/labjualPerBln', $data, true); //render the view into HTML
            $this->load->library('pdf');
            $pdf=$this->pdf->load();
            $pdf->SetFooter(''.'|{PAGENO}|'.''); //Add a footer for good measure
            $pdf->WriteHTML($html); //write the HTML into PDF
            $pdf->Output();
        }
        redirect("downloads/reports/namafile.pdf");
    }else{ //jika tidak ada session, redirect ke halaman login
        redirect('login', 'refresh');
    }
}

Guna menghasilkan laporan dalan bentuk pdf diperlukan tampilan html yang merupakan isi content dari laporan, dalam contoh ini namanya “labjualPerBln.php” yang akan tersimpan pada application/views/laporan. Code pada file tersebut adalah:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<head>
    <title>Lap. Penjualan</title>
    <link rel="stylesheet"type="text/css"href="<?php echo base_url().$this->config->item('css'); ?>"/>
</head>
<body>

"content">
    

class="row">
        

class="caption" align="center">Laporan Penjualan Barang bulan echo $bulan." ".$tahun;?>

        

class="end">

    </div>
    <hr>
    

class="row">
        

class="value">Tanggal Cetak : echo $tglCetak;?>

        

class="end">

    </div>
    <br/>
    

class="row">
        

class="value">Berikut adalah daftar barang yang berhasil terjual bulan ini.

        

class="end">

    </div>
    

class="row">       
        

class="data">echo $table; ?>

        

class="end">

    </div>
    

class="spacer">

    

class="row">
        

class="value" align="right">
            Pembuat Laporan
            

            echo $namaPeg; ?>
        

        

class="end">

    </div>
</div>                       
</body>

5. Buat tampilah halaman yang akan membuat file pdf simpan dengan nama lapBlnan.php, code-nya :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<head>
    <title><?php echo "Laporan ".$judul."/Bulan";?></title>   
    "text/javascript" src="assets/js/jquery-1.3.2.min.js">
</head>
<body>
    

class="row">
        

class="caption">echo "Laporan ".$judul." Barang/Bulan"; ?>

        

class="end">

    </div>
    <hr />
    

"content">
        echo form_open(site_url($lap.'/loadReport'), array('target' => '_blank'));?>
        

class="row">
            

class="caption_border">Pilih Periode Laporan

            

class="end">

        </div>
        

class="row">
            

                

                    

                    

                    

                    

                    

                

            
"padding-left:5px;">Bulan : "padding-left:5px;">echo form_dropdown('bln',$cbBulan,$this->validation->namaBulan,'id="bln";onChange="updateGraph()"');?> "padding-left:15px;">Tahun : "padding-left:5px;">echo form_dropdown('thn',$cbTahun,$this->validation->tahun,'id="thn";onChange="updateGraph()"');?> "padding-left:15px;">
                        $f_btn = array('name'=>'submit', 'id'=>'submit', 'value'=>'Generate Report');
                              echo form_submit($f_btn); ?>
                    

            

class="end">

        </div>
        

class="spacer">

    </div>
</body>

6. Selesai. Slanjutnya tinggal mendaftarkan halaman laporan tersebut pada menu dan contoh hasil tampilannya adalah :

Dan ketika menekan tombol “Generate Report” akan terbuka tab baru yang menampilkan laporan dalam format pdf. Contoh tampilannya:

Sekian catatan kali ini. Semoga bermanfaat… (^u^)

Sumber = https://tvianty.wordpress.com/2015/08/26/membuat-laporan-menggunakan-mpdf/

Membuat select (combo box) dinamis dengan Ajax dan Codeigniter

Apa kabar semuanya, semoga dalam keadaan sehat dan baik baik saja.

Pada artikel kali ini saya akan membagikan tutorial cara membuat menu select (combo box) dinamis menggunakan ajax dan php.

 
1. Intro

 
Kita tau bersama bahwa menu select atau combo box sangat diperlukan didalam membuat aplikasi. Bukan hanya sebagai pelengkap saja, melainkan menu select sudah merupakan sebuah kebutuhan didalam setiap form inputan.

 

Selain ‘input’, select juga pasti akan anda jumpai pada setiap form yang berhubungan dengan registrasi, survei, kuis, maupun form administratif lainnya. Maka dari itu setiap programmer diharuskan dan wajib tau penggunaan menu ini, dan yang paling penting adalah ‘bisa dinamis’.

 

Misalnya bayangkan jika dalam aplikasi terdapat 3 buah menu select, dan memiliki kondisi dimana pilihan/option yang ada pada menu ke-3 hasilnya bergantung pada apa yang dipilih pada menu ke-2, dan pilihan/option yang ada pada menu ke-2 bergantung pada apa yang dipilih pada menu pertama.

 

Prakteknya (dahulu), agar bisa memenuhi kondisi ini, masing masing menu akan disiapkan kedalam 3 buah halaman yang berbeda.
Ketika user memilih data pada menu select pertama, browser akan mengalihkan (mereload) halaman ke halaman menu select kedua.
Dan data yang dipilih oleh user pada menu select pertama akan dijadikan sebagai parameter pada select yang kedua, agar supaya halaman menu select yang kedua dapat menghasilkan pilihan data sesuai pilihan menu pertama. Begitupun setelah user memilih data pada menu kedua, browser akan mengalihkan ke halaman menu select ke tiga.

 

Cara diatas memang merupakan metode atau praktik untuk menghasilkan menu dinamis, tapi masih bukanlah cara paling efisien.
Karena jika hanya menggunakan parameter ‘dinamis’ nya saja, jelas cara diatas sah-sah saja. Tapi bagaimana jika perameter lainnya mulai diterapkan? misalnya: user firendly, resource, performa, dan waktu. Parameter parameter inilah sangat diperlukan oleh aplikasi aplikasi modern era ini, bukan hanya sekedar ‘dinamis’ saja.

 

Terima kasih banyak dengan hadirnya Ajax (Asynchronous JavaScript and
XML)! Karena dengan kehadirannya, menu yang harus kita pisahkan didalam 3 halaman tadi, sekarang sudah bisa kita tampilkan secara bersama-sama didalam 1 halaman saja. Ketika memilih data pada menu pertama,pilihan pada menu select kedua akan langsung muncul tanpa perlu lagi direload atau mengalihkan halaman. Karena request perpindahan halaman seperti cara diatas sudah digantikan dengan cara Asynchronous request.
Sebagai latihan kita kali ini kita akan menggunakan kasus pemilihan provinsi, kabupaten/kota, kecamatan lalu kelurahan/desa.

 

Masing masing pilihan disiapkan pada menu yang berbeda.
Berikut ini urutan proses pada menu yang akan kita buat.

 

1. Halaman menyajikan 4 buah pilihan menu select.
yaitu provinsi, kabupaten/kota, kecamatan lalu kelurahan/desa.

2. Saat halaman pertama kali dimuat/ditampilkan, menu provinsi telah tersedia data dan siap untuk dipilih. Dan menu lainnya masih belum memiliki data pilihan.

3. Kerika user memilih data pada menu provisi, menu ‘kabupaten/kota’ akan mengasilkan pilihan data daftar kabupaten/kota kota sesuai provinsi yang dipilih pada menu provinsi.

4. Begitupun ketika user memilih data pada menu ‘kabupaten/kota’, menu ‘kecamatan’ akan memuat pilihan data sesuai kabupaten/kota yang dipilih.

5. Begitu seterusnya hingga menu ‘kelurahan/desa’ menghasilkan data sesuai kecamatan yang dipilih.

 

2. Mempersiapkan Kelengkapan Project
Pada tutorial kali ini kita akan menggunakan framework kesayangan kita yaitu framework Codeigniter , dan untuk manghandel Ajax kita akan menggunakan libary Jquery.

Dan pastinya untuk mengasilkan data tentu diperlukan databasenya. Untuk database nya silahkan download datanya disini. Dan silahkan diekstrak.
Buka phpmyadmin. Buat database baru dengan nama apa saja, misalnya ‘latihan’. Lalu import file indonesia.sql yang kamu download tadi kedalamnya.

Jika berhasil, database kamu akan memiliki table-table seperti gambar dibawah ini.

 

 

 

Penjelasan table

 

 

provinces = Povinsi
regencies = Kabupaten- kota
districts = kecamatan
villages = kelurahan - Desa

 
Sekarang, buat folder project baru pada localhost kamu. Buat folder apa nama apa saja, misalnya folder ‘latihan’. Lalu ekstrak file file codeigniter didalam nya.

 

 

 

 

buka folder application/config lalu edit file database.php.
Atur nama databasenya,username,dan password.

 

 

 
buka folder application/config lalu edit file config.php.
atur base url nya menjadi

$config[‘base_url’] = ‘http://localhost/latihan&#8217;;

 

 

Buat file php baru sebagai controller didalam folder application/controllers buat dengan nama misalnya Select.php

 

 

 

 
Sekarang buat file php baru sebagai model didalam folder application/models buat dengan nama misalnya Model_select.php

 

 

 
Buat file php baru sebagai view didalam folder application/views buat dengan nama misalnya view_select.php

 

 

 

 
Sebagai assetnya, kita akan menggunakan ‘bootstrap’ sebagai bantuan CSS.
Buat folder seperti ini ‘assets/bootstrap’ lalu didalamnya file file Bootstrap dan jQuery

 

 

 

 
3. Coding

 

buka file pada application/controllers/Select.php

lalu masukan code berikut ini.

 

 

 

<?php

Class Select extends CI_Controller

{


function __construct(){

parent::__construct();

$this->load->database();

$this->load->helper(array('url'));

$this->load->model('model_select');


}


function index(){


$data['provinsi']=$this->model_select->provinsi();

$this->load->view('view_select',$data);


}

function ambil_data(){
}

}

 

 

 

buka file pada application/views/views_select.php

lalu masukan code berikut ini.

 

 

 

<html>

<head>

<title>Latihan Select dnanmis</title>

<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/bootstrap/css/bootstrap.min.css') ?>">
<script type="text/javascript" src="<?php echo base_url('assets/bootstrap/jquery.min.js') ?>"></script>

</head>

<body>

<div class='container'>

<div class='row'>

<div class='col-md-5'>

<h3>Menu Select Dinamis</h3>

<div class='form-group'>
<label>Provinsi</label>
<select class='form-control' id='provinsi'>
<option value='0'>--pilih--</option>
<?php 
foreach ($provinsi as $prov) {
echo "<option value='$prov[id]'>$prov[name]</option>";
}
?>
</select>
</div>

<div class='form-group'>
<label>Kabupaten/kota</label>
<select class='form-control' id='kabupaten-kota'>
<option value='0'>--pilih--</option>
</select>
</div>


<div class='form-group'>
<label>Kecamatan</label>
<select class='form-control' id='kecamatan'>
<option value='0'>--pilih--</option>
</select>
</div>


<div class='form-group'>
<label>Kelurahan/desa</label>
<select class='form-control' id='kelurahan-desa'>
<option value='0'>--pilih--</option>
</select>
</div>

</div>

</div>

</div>

</body>

</html>

 
buka file pada application/models/Models_select.php

lalu masukan code berikut ini.

 

 

 

<?php

Class Model_select extends CI_Model
{

function __construct(){

parent::__construct();

}


function provinsi(){


$this->db->order_by('name','ASC');
$provinces= $this->db->get('provinces');


return $provinces->result_array();


}

function kabupaten($provId){
}


function kecamatan($kabId){

}

function kelurahan($kecId){

}


} 

 
Sekarang buka browser kamu lalu buka
http://localhost/latihan/index.php/select

Kamu akan mendapatkan hasil seperti ini

 

 

 

 

 
Pada menu provinsi telah tersedia hasilnya.
Tapi belum pada menu yang lainnya

 
Kembali file kepada file application/controllers/Select.php
Lalu tambahkan beberapa code didalamnya sehingga jadi seperti ini

 

 

<?php

Class Select extends CI_Controller

{


function __construct(){

parent::__construct();

$this->load->database();

$this->load->helper(array('url'));

$this->load->model('model_select');


}


function index(){


$data['provinsi']=$this->model_select->provinsi();

$this->load->view('view_select',$data);


}

function ambil_data(){

$modul=$this->input->post('modul');
$id=$this->input->post('id');

if($modul=="kabupaten"){
echo $this->model_select->kabupaten($id);
}
else if($modul=="kecamatan"){

}
else if($modul=="kelurahan"){

}
}

}

 
Pada file application/models/Models_select.php
Tambahkan juga code didalamnya

 

 

<?php

Class Model_select extends CI_Model
{

function __construct(){

parent::__construct();

}


function provinsi(){


$this->db->order_by('name','ASC');
$provinces= $this->db->get('provinces');


return $provinces->result_array();


}


function kabupaten($provId){

$kabupaten="<option value='0'>--pilih--</pilih>";

$this->db->order_by('name','ASC');
$kab= $this->db->get_where('regencies',array('province_id'=>$provId));

foreach ($kab->result_array() as $data ){
$kabupaten.= "<option value='$data[id]'>$data[name]</option>";
}

return $kabupaten;

}

function kecamatan($kabId){

}

function kelurahan($kecId){

}


}

 

 

kembali kepada file application/views/views_select.php
lalu tambahkan kode berikut ini

 

<script type="text/javascript">

$(function(){

$.ajaxSetup({
type:"POST",
url: "<?php echo base_url('index.php/select/ambil_data') ?>",
cache: false,
});

$("#provinsi").change(function(){

var value=$(this).val();
if(value>0){
$.ajax({
data:{modul:'kabupaten',id:value},
success: function(respond){
$("#kabupaten-kota").html(respond);
}
})
}

});


$("#kabupaten-kota").change(function(){
});

$("#kecamatan").change(function(){
});

})

</script>

 

 

 

Refresh browser kamu. Sekarang ketika kamu memilih sebuah provinsi, maka daftar kabupaten dan kota sudah tersedia untuk dipilih

 

 

 
Kini waktunya menyelesaikan sisa codingnya

file application/controllers/Select.php

 

 

<?php

Class Select extends CI_Controller

{


function __construct(){

parent::__construct();

$this->load->database();

$this->load->helper(array('url'));

$this->load->model('model_select');


}


function index(){


$data['provinsi']=$this->model_select->provinsi();

$this->load->view('view_select',$data);


}

function ambil_data(){

$modul=$this->input->post('modul');
$id=$this->input->post('id');

if($modul=="kabupaten"){
echo $this->model_select->kabupaten($id);
}
else if($modul=="kecamatan"){
echo $this->model_select->kecamatan($id);

}
else if($modul=="kelurahan"){
echo $this->model_select->kelurahan($id);
}
}

}

 

 
file application/models/Models_select.php

 

 

<?php

Class Model_select extends CI_Model
{

function __construct(){

parent::__construct();

}


function provinsi(){


$this->db->order_by('name','ASC');
$provinces= $this->db->get('provinces');


return $provinces->result_array();


}


function kabupaten($provId){

$kabupaten="<option value='0'>--pilih--</pilih>";

$this->db->order_by('name','ASC');
$kab= $this->db->get_where('regencies',array('province_id'=>$provId));

foreach ($kab->result_array() as $data ){
$kabupaten.= "<option value='$data[id]'>$data[name]</option>";
}

return $kabupaten;

}

function kecamatan($kabId){
$kecamatan="<option value='0'>--pilih--</pilih>";

$this->db->order_by('name','ASC');
$kec= $this->db->get_where('districts',array('regency_id'=>$kabId));

foreach ($kec->result_array() as $data ){
$kecamatan.= "<option value='$data[id]'>$data[name]</option>";
}

return $kecamatan;
}

function kelurahan($kecId){
$kelurahan="<option value='0'>--pilih--</pilih>";

$this->db->order_by('name','ASC');
$kel= $this->db->get_where('villages',array('district_id'=>$kecId));

foreach ($kel->result_array() as $data ){
$kelurahan.= "<option value='$data[id]'>$data[name]</option>";
}

return $kelurahan;
}


}

 

 
file application/views/views_select.php

 

 

<html>

<head>

<title>Latihan Select dnanmis</title>

<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/bootstrap/css/bootstrap.min.css') ?>">
<script type="text/javascript" src="<?php echo base_url('assets/bootstrap/jquery.min.js') ?>"></script>


<script type="text/javascript">

$(function(){

$.ajaxSetup({
type:"POST",
url: "<?php echo base_url('index.php/select/ambil_data') ?>",
cache: false,
});

$("#provinsi").change(function(){

var value=$(this).val();
if(value>0){
$.ajax({
data:{modul:'kabupaten',id:value},
success: function(respond){
$("#kabupaten-kota").html(respond);
}
})
}

});


$("#kabupaten-kota").change(function(){
var value=$(this).val();
if(value>0){
$.ajax({
data:{modul:'kecamatan',id:value},
success: function(respond){
$("#kecamatan").html(respond);
}
})
}
})

$("#kecamatan").change(function(){
var value=$(this).val();
if(value>0){
$.ajax({
data:{modul:'kelurahan',id:value},
success: function(respond){
$("#kelurahan-desa").html(respond);
}
})
} 
})

})

</script>


</head>

<body>

<div class='container'>

<div class='row'>

<div class='col-md-5'>

<h3>Menu Select Dinamis</h3>

<div class='form-group'>
<label>Provinsi</label>
<select class='form-control' id='provinsi'>
<option value='0'>--pilih--</option>
<?php 
foreach ($provinsi as $prov) {
echo "<option value='$prov[id]'>$prov[name]</option>";
}
?>
</select>
</div>

<div class='form-group'>
<label>Kabupaten/kota</label>
<select class='form-control' id='kabupaten-kota'>
<option value='0'>--pilih--</option>
</select>
</div>


<div class='form-group'>
<label>Kecamatan</label>
<select class='form-control' id='kecamatan'>
<option value='0'>--pilih--</option>
</select>
</div>


<div class='form-group'>
<label>Kelurahan/desa</label>
<select class='form-control' id='kelurahan-desa'>
<option value='0'>--pilih--</option>
</select>
</div>

</div>

</div>

</div>

</body>

</html>

 

 

Berikut ini adalah hasil akhirnya.

 

 

 

 

 

Demikian tutorial kita pada artikel kali ini.

Semoga bisa bermanfaat untuk kita semua.

Sumber = https://www.sandro.id/artikel/23-membuat-select-combo-box-dinamis-dengan-ajax-dan-codeigniter

Fungsi substr() di php

Akan saya jelaskan dulu apa kegunaan fungi substr(); di dalam PHP. Substring adalah fungsi yang digunakan untuk memperolek karakter dalam sebuah variable.

Begini jelasnya:

misalkan : $data berisi nama file gambar1.jpg . Nah disini saya mau ambil nama file nya saja tidak dengan ekstensinya . Caranya :

<?php
//data yang akan di substring
$data= "gambar1.jpg";
//proses mensubstring
$namafile= substr($data,0,-4);
//menampilkan hasil substring
echo $namafile;
?>

Dari rumus diatas akan menghasilkan “gambar1”  dan ekstensinya tidak ikut tampil.

Selain itu Substring juga dapat digunakan untuk mengambil karakter dari sisi kanan.Seperti berikut :

<?php
$data= "gambar1.jpg";
$namafile= substr($data,-4);
echo $namafile;
?>

Fungsi diatas akan menghasilkan “.jpg” karena ia hanya mengambil karakter dari sisi kanan.

Fungsi substr() umumnya digunakan untuk mengambil beberapa karakter dari sisi kiri saja. Seperti:

<?php
$data= "gambar1.jpg";
$namafile= substr($data,0,5);
echo $namafile;


//Fungsi diatas akan menghasilkan "gambar"