Redirect halaman digunakan untuk mengarahkan halaman tertentu ke halaman lain. Misalnya jika session time out maka page user akan diarahkan ke halaman index (otomatis) atau ada link tertentu (menggunakan a href atau button ).
Berikut beberapa contoh redirect halaman (tanpa menggunakan frame)
1. < a href="halamanlain.html">Klik disini </a>
2. <meta http-equiv="refresh" content="0; url=index.php">
3. header("Location: index.php");
4. <script type="text/javascript">window.location = "index.php";</script>
Jika menggunakam frame, biasanya kita akan meletakkan link redirect disalah satu frame. Jika yang dimaksud redirect tersebut adalah untuk mengubah header url maka kita harus menutup semua frame. Sebagai contoh, link Log Out difungsikan untuk menutup semua session dan akan diarahkan ke halaman index. Berikut contoh redirect pada frame:
1. <a href="logout_process.php" target="_top">Log Out</a>
2. <SCRIPT LANGUAGE='JavaScript'>
window.parent.location='index.php'
</SCRIPT>
Semoga bermanfaat ^^
Tampilkan postingan dengan label teknologi. Tampilkan semua postingan
Tampilkan postingan dengan label teknologi. Tampilkan semua postingan
Jumat, 22 Juli 2011
Rabu, 11 Mei 2011
.htaccess CodeIgniter - PHP
Sekedar sharing penggunaan .htacces di CodeIgniter.
Script dibawah akan mengubah
http://localhost/testing/index.php/login
Menjadi
http://localhost/testing/login
1. Copy paste script dibawah, beri nama .htacess. Letakkan file dibawah folder web kamu. Jika berdasarkan link diatas, maka .htacces berada di testing/.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /testing/
#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin
ErrorDocument 404 /index.php
</IfModule>
2 Pastikan mod_rewrite di server jalan
3. Kosongkan string $config['index_page'] = ''; di application/config/config.php
Semoga berhasil
Semoga berhasil
Label:
teknologi
Senin, 09 Mei 2011
Import Dari Excel ke Database pada CodeIgniter - PHP
Untuk meng-import excel, pastinya menggunakan upload excel form. Contoh sistem upload excel yang saya buat ini masih sederhana. Data akan diupdate jika ada yang sama. Jika tidak, data akan di insert (dianggap sebagai data baru). Sebelumnya lagi-lagi ngingetin agar konfigurasi code igniter di awal seperti database.php, config.php harus sudah benar ^_^
1. Buat file chapter.php di application/views/. Copy paste script berikut diantara tag <body></body>
<?php echo form_open_multipart('chapter') . "\n"; ?>
<table>
<tr>
td><input type="file" id="file_upload" name="userfile" size="20" /></td>
</tr>
<tr>
<td> </td>
<td valign="top" >
<?php echo form_submit('submit', 'Upload'); ?></td>
</tr>
</table>
<?php echo form_close(); ?>
<?php
if ($this->session->flashdata('msg_excel')){
?>
<div class="msg"><?php echo $this->session->flashdata('msg_excel'); ?></div>
<?php } ?>
<tr>
td><input type="file" id="file_upload" name="userfile" size="20" /></td>
</tr>
<tr>
<td> </td>
<td valign="top" >
<?php echo form_submit('submit', 'Upload'); ?></td>
</tr>
</table>
<?php echo form_close(); ?>
<?php
if ($this->session->flashdata('msg_excel')){
?>
<div class="msg"><?php echo $this->session->flashdata('msg_excel'); ?></div>
<?php } ?>
2. Buat file chapter.php di application/controllers/
<?php
class Chapter extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('Querypage');
$this->load->helper(array('form', 'url', 'inflector'));
$this->load->library('form_validation');
}
public function index()
{
if ($this->input->post('submit'))
{
class Chapter extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('Querypage');
$this->load->helper(array('form', 'url', 'inflector'));
$this->load->library('form_validation');
}
public function index()
{
if ($this->input->post('submit'))
{
$this->do_upload();
// $this->load->view('chapter', $data);
}
else
{
$this->load->view('chapter', $data);
}
}
// $this->load->view('chapter', $data);
}
else
{
$this->load->view('chapter', $data);
}
}
function do_upload()
{
$config['upload_path'] = './temp_upload/';
$config['allowed_types'] = 'xls';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$data = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg_excel', 'Insert failed. Please check your file, only .xls file allowed.');
}
else
{
$data = array('error' => false);
$upload_data = $this->upload->data();
$this->load->library('excel_reader');
$this->excel_reader->setOutputEncoding('CP1251');
$file = $upload_data['full_path'];
$this->excel_reader->read($file);
error_reporting(E_ALL ^ E_NOTICE);
// Sheet 1
$data = $this->excel_reader->sheets[0] ;
$dataexcel = Array();
for ($i = 1; $i <= $data['numRows']; $i++) {
if($data['cells'][$i][1] == '') break;
$dataexcel[$i-1]['chapternumber'] = $data['cells'][$i][1];
$dataexcel[$i-1]['title'] = $data['cells'][$i][2];
$dataexcel[$i-1]['text1'] = $data['cells'][$i][3];
$dataexcel[$i-1]['text2'] = $data['cells'][$i][4];
}
//cek data
$check= $this->Querypage->search_chapter($dataexcel);
if (count($check) > 0)
{
$this->Querypage->update_chapter($dataexcel);
// set pesan
$this->session->set_flashdata('msg_excel', 'update data success');
}else{
$this->Querypage->insert_chapter($dataexcel);
// set pesan
$this->session->set_flashdata('msg_excel', 'inserting data success');
}
}
redirect('chapter');
}
}
?>
{
$config['upload_path'] = './temp_upload/';
$config['allowed_types'] = 'xls';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$data = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg_excel', 'Insert failed. Please check your file, only .xls file allowed.');
}
else
{
$data = array('error' => false);
$upload_data = $this->upload->data();
$this->load->library('excel_reader');
$this->excel_reader->setOutputEncoding('CP1251');
$file = $upload_data['full_path'];
$this->excel_reader->read($file);
error_reporting(E_ALL ^ E_NOTICE);
// Sheet 1
$data = $this->excel_reader->sheets[0] ;
$dataexcel = Array();
for ($i = 1; $i <= $data['numRows']; $i++) {
if($data['cells'][$i][1] == '') break;
$dataexcel[$i-1]['chapternumber'] = $data['cells'][$i][1];
$dataexcel[$i-1]['title'] = $data['cells'][$i][2];
$dataexcel[$i-1]['text1'] = $data['cells'][$i][3];
$dataexcel[$i-1]['text2'] = $data['cells'][$i][4];
}
//cek data
$check= $this->Querypage->search_chapter($dataexcel);
if (count($check) > 0)
{
$this->Querypage->update_chapter($dataexcel);
// set pesan
$this->session->set_flashdata('msg_excel', 'update data success');
}else{
$this->Querypage->insert_chapter($dataexcel);
// set pesan
$this->session->set_flashdata('msg_excel', 'inserting data success');
}
}
redirect('chapter');
}
}
?>
3. Buat file querypage.php di application/models/
<?php
class Querypage extends CI_Model {
function __construct()
{
parent::__construct();
}
function insert_chapter($dataarray)
{
for($i=1;$i<count($dataarray);$i++){
$data = array(
'chapternumber'=>$dataarray[$i]['chapternumber'],
'title'=>$dataarray[$i]['title'],
'text1'=>$dataarray[$i]['text1'],
'text2'=>$dataarray[$i]['text2'],
'dateinserted' => date('Y-m-d H:i:s', now())
);
$this->db->insert('content', $data);
}
}
function update_chapter($dataarray)
{
for($i=1;$i<count($dataarray);$i++){
$data = array(
'chapternumber'=>$dataarray[$i]['chapternumber'],
class Querypage extends CI_Model {
function __construct()
{
parent::__construct();
}
function insert_chapter($dataarray)
{
for($i=1;$i<count($dataarray);$i++){
$data = array(
'chapternumber'=>$dataarray[$i]['chapternumber'],
'title'=>$dataarray[$i]['title'],
'text1'=>$dataarray[$i]['text1'],
'text2'=>$dataarray[$i]['text2'],
'dateinserted' => date('Y-m-d H:i:s', now())
);
$this->db->insert('content', $data);
}
}
function update_chapter($dataarray)
{
for($i=1;$i<count($dataarray);$i++){
$data = array(
'chapternumber'=>$dataarray[$i]['chapternumber'],
'title'=>$dataarray[$i]['title'],
'text1'=>$dataarray[$i]['text1'],
'text2'=>$dataarray[$i]['text2'],
'dateupdated' => date('Y-m-d H:i:s', now())
);
$param = array(
'chapternumber'=>$dataarray[$i]['chapternumber']
);
$this->db->where($param);
return $this->db->update('content',$data);
}
}
function search_chapter($dataarray){
for($i=1;$i<count($dataarray);$i++){
$search = array(
'chapternumber'=>$dataarray[$i]['chapternumber']
);
}
$data = array();
$this->db->where($search);
$this->db->limit(1);
$Q = $this->db->get('content');
if($Q->num_rows() > 0){
$data = $Q->row_array();
}
$Q->free_result();
return $data;
}
?>
'text1'=>$dataarray[$i]['text1'],
'text2'=>$dataarray[$i]['text2'],
'dateupdated' => date('Y-m-d H:i:s', now())
);
$param = array(
'chapternumber'=>$dataarray[$i]['chapternumber']
);
$this->db->where($param);
return $this->db->update('content',$data);
}
}
function search_chapter($dataarray){
for($i=1;$i<count($dataarray);$i++){
$search = array(
'chapternumber'=>$dataarray[$i]['chapternumber']
);
}
$data = array();
$this->db->where($search);
$this->db->limit(1);
$Q = $this->db->get('content');
if($Q->num_rows() > 0){
$data = $Q->row_array();
}
$Q->free_result();
return $data;
}
?>
keterangan: data akan diupdate jika ada chapternumber yang sama dalam file excel.
4. Download excel reader disini. Ekstrak, kemudian copy paste ke folder application/libraries/
5. Buat folder temp_upload sejajar dengan application, system, css (jika ada)
6. Jangan lupa siapin database-nya
4. Download excel reader disini. Ekstrak, kemudian copy paste ke folder application/libraries/
5. Buat folder temp_upload sejajar dengan application, system, css (jika ada)
6. Jangan lupa siapin database-nya
CREATE TABLE `content` (
`id` int(11) NOT NULL auto_increment,
`id` int(11) NOT NULL auto_increment,
`ChapterNumber` int(3) NOT NULL default '0',
`Title` varchar(50) default NULL,
`Title` varchar(50) default NULL,
`Text1` text,
`Text2` text,
`Text2` text,
`DateInserted` datetime default NULL,
`DateUpdated` datetime default NULL,
PRIMARY KEY (`Code`,`ChapterNumber`),
UNIQUE KEY `ID` (`id`)
)
`DateUpdated` datetime default NULL,
PRIMARY KEY (`Code`,`ChapterNumber`),
UNIQUE KEY `ID` (`id`)
)
7. Done.
8. Jalankan dibrowser http://localhost/namaweb/index.php/chapter
Selamat mencoba :)
8. Jalankan dibrowser http://localhost/namaweb/index.php/chapter
Selamat mencoba :)
Label:
teknologi
Kamis, 05 Mei 2011
Membuat Paging dengan CodeIgniter - PHP
Paging, fitur untuk mempercantik list daftar dihalaman website. Tentunya supaya rapi dan enak diliat. Maka ketika saya belajar Code Igniter, langsung googling2 gimana caranya. Berikut scriptnya:
1. Buat halaman untuk menampilkan list data kita, contoh category.php di application/views . Letakkan diantara tag <body></body>
<table class="list" width="54%">
<tr class="list">
<th class="list">Code</th><th>Category</th>
</tr>
<?php foreach ($datacategory as $row): ?>
<tr class="list">
<td class="list"><?php echo $row -> code ?></td>
<td class="list"><?php echo $row -> name ?></td>
</tr>
<?php endforeach ?>
</table>
<?php echo $this->pagination->create_links(); ?>
2. Buat file category.php di application/controlles
<?php
class Category extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('Querypage');
$this->load->library('pagination'); //load library pagination
}
public function index($offset = 0)
{
$perpage =10; //tentukan jumlah data per halaman
//untuk konfigurasi pagination
$config = array(
'base_url' => base_url() . 'index.php/category/index/',
'total_rows' => count($this->Querypage->get_type()),
'per_page' => $perpage,
); //inisialisasi pagination dn config di atas
$this->pagination->initialize($config);
$data['datacategory'] = $this->Querypage->get_type(array('perpage' => $perpage, 'offset' => $offset));
$this->load->view('category', $data);
}
}
?>
3. File untuk modelnya, buat quarypage.php di application/models
class Querypage extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_type($limit = array()) //paging category
{
if ($limit == NULL)
return $this->db-> order_by("id", "desc") -> get('type') -> result();
else
return $this->db->limit($limit['perpage'], $limit['offset'])-> order_by("id", "desc") -> get('type') -> result();
}
}
4. Tambahkan file pagination.php di application/config/
<?php
$config['full_tag_open'] = '<div class="pagination">';
$config['full_tag_close'] = '</div>';
$config['next_link'] = 'Next »';
$config['prev_link'] = '« Prev';
$config['num_tag_open'] = '<div class="digit">';
$config['num_tag_close'] = '</div>';
$config['cur_tag_open'] = '<div class="digit current">';
$config['cur_tag_close'] = '</div>';
$config['num_links'] = 1 ;
$config['last_link'] = '<b>Last ›</b>';
$config['first_link'] = '<b>‹ First</b>';
?>
5. Tambahkan script ini di css, agar paging terlihat lebih cantik
@author Cheyuz => untuk paging
**/
.pagination{margin: 5px; padding: 10px 0px;}
.pagination .digit{padding: 0 10px 0 10px; display: inline;}
.pagination .digit:hover, .pagination .current{padding: 2px 10px 2px 10px; background: #eee; font-weight: 900; -moz-border-radius:5px}
6. Selesai. Mudahkan ^_^
Referensi: UserGuide
Label:
teknologi
Contoh Form Validation CodeIgniter - PHP
Kali ini saya saya akan membuat contoh sederhana submit form yang disertai dengan validasi, tentunya menggunakan Code Igniter. Saya anggap konfigurasi awal sudah oke ya...(atau baca postingan ini).
Baiklah langsung aja, berikut langkah2 nya:
1. Buat file home.php di applications/views . Copy paste script berikut diantara tag <body></body>
<?php echo form_open_multipart('home') . "\n"; ?>
<table>
<tr>
<td>Category</td>
<td><?php echo form_dropdown('category', $category); ?></td>
<td></td>
</tr>
<tr>
<td>Title</td>
<td><input type="text" name="judul" value="<?php echo set_value('judul'); ?>" id="txtinput" />
</td>
<td><font color="#FF0000"><?php echo form_error('judul'); ?></font>
</td>
</tr>
<tr>
<td>Writer</td>
<td><input type="text" name="writer" value="<?php echo set_value('writer'); ?>" id="txtinput" /></td>
<td><font color="#FF0000"><?php echo form_error('writer'); ?></font></td>
</tr>
<tr>
<td>Image Name</td>
<td><input type="file" id="userfile" name="userfile" size="20" value="<?php echo set_value('userfile'); ?>"/></td>
<td><font color="#FF0000"><?php echo form_error('userfile'); ?></td></tr>
<tr>
<tr>
<td valign="top">Synopis <br /><font size="-2">*max 200 words</font></td>
<td><textarea name="sinopsis" value="<?php echo set_value('sinopsis'); ?>" id="sinopsis" ></textarea></td>
<td><font color="#FF0000"><?php echo form_error('sinopsis'); ?></font></td>
</tr>
<tr>
<td valign="top">Jumlah Chapter</td>
<td><input type="text" name="jumlah_chapter" value="<?php echo set_value('jumlah_chapter'); ?>" id="txtinput" /></td>
<td><font color="#FF0000"><?php echo form_error('jumlah_chapter'); ?></font></td>
</tr>
<tr>
<td> </td>
<td valign="top" align="right">
<?php echo form_submit('submit', 'Submit'). form_reset('reset', 'Clear'); ?></td>
<td></td>
</tr>
</table>
<?php echo form_close(); ?>
<?php
if ($this->session->flashdata('msg_title')){
?>
<div class="msg"><?php echo $this->session->flashdata('msg_title'); ?></div>
<?php } ?>
2. Buat file home.php di application/controlles
<?php
class Home extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('Querypage');
$this->load->helper(array('form', 'url','inflector'));
$this->load->library('form_validation');
}
public function index()
{
$rules = array(
array(
'field' => 'judul',
'label' => 'Judul',
'rules' => 'trim|required'
),
array(
'field' => 'writer',
'label' => 'Writer',
'rules' => 'trim|required'
),
array(
'field' => 'sinopsis',
'label' => 'Sinopis',
'rules' => 'required|trim'
),
array(
'field' => 'userfile',
'label' => 'File',
'rules' => 'trim'
),
array(
'field' => 'jumlah_chapter',
'label' => 'Jumlah Chapter',
'rules' => 'trim|required|numeric'
)
);
$this->form_validation->set_rules($rules);
$this->form_validation->set_message('required', 'Required');
$this->form_validation->set_message('numeric', 'Numeric');
if ($this->input->post('submit'))
{
if ($this->form_validation->run() == FALSE)
{
$this->load->view('home', $data);
}
else
{
$this->add_title();
}
}else{
$this->load->view('home', $data);
}
}
function add_title(){
$config['upload_path'] = './img_upload/';
$config['allowed_types'] = 'png|gif';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload() and $_FILES['userfile']['error']!=4 )
{
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg_title', 'Insert failed. Please check your image file, only .png or.gif file allowed.');
}
else
{
$data_upload = $this->upload->data();
$filename = $data_upload['file_name']; // imagename.png
$rawname = $data_upload['raw_name']; //imagename
// save data
$arr_data = array( 'type' => $this->input->post('category'),
'title' => humanize($this->input->post('judul')),
'writername' => humanize($this->input->post('writer')),
'sinopsis' => $this->input->post('sinopsis'),
'TotalChapter' => $this->input->post('jumlah_chapter'),
'imagename' => $rawname,
'dateinserted' => date('Y-m-d H:i:s', now())
);
$this->Querypage->insert_title($arr_data); //Query untuk insert data
// set pesan
$this->session->set_flashdata('msg_title', 'insert data sukses');
}
redirect('home');
}
}
?>
3. Buat file querypage.php di application/models
<?php
class Querypage extends CI_Model {
function __construct()
{
parent::__construct();
}
function insert_title($data)
{
return $this->db->insert('namatable', $data);
}
}
?>
4. Selesai ^__^
Sedikit penjelasan, untuk upload image pada form diatas tidak diharuskan diisi sehingga saya menggunakan $_FILES['userfile']['error']!=4. Jika file harus diisi, hapus saja script ini.
Untuk mempermudah dan infomasi lebih lanjut tentang form validation di Code Igniter, check this out.
Label:
teknologi
Langganan:
Postingan (Atom)