Skip to main content

problem dengan session

November 21, 2010 by merom

merom's picture

kk saya mau tanya...gini saya sedang buat halaman login dengan session berikut syntaxnya..

***bagian view->formlogin.php

$this->load->helper('form');
$this->load->library('table');
$this->table->set_caption('login sebagai admin');
echo form_open("test/cek");
$this->table->add_row("username : ",form_input('uname'));
$this->table->add_row("password : ",form_password('upass'));
$this->table->add_row(form_submit('submit','login'));
echo $this->table->generate();
echo form_close();

****bagian controller->user.php

Class User extends Controller {
	function User(){
		parent::Controller();
	}
 
	function index(){
	$this->load->view('formlogin');
	}
 
function ceklogin()
{
 
$username = $_POST['uname'];
$password = $_POST['upass'];
 
if ($username == 'abcde' &&  $password== '12345')
{
$this->session->set_userdata('userid','1');
redirect('user/utama/','refresh');
}else{
$this->index();
}
}
function utama(){
 
if ($this->session->user_data('userid')=='1')
{
echo "<h3 align='center'>halaman utama admin</h3>";
echo "halaman ini hanya diakses admin<br><br>";
echo anchor ("user/logout","logout");
}
else{
redirect('user/index','refresh');
}
}
function logout(){
$this->session->unset_userdata('$userid');
redirect('user/index','refresh');
}
}

============================================================

setelah di compaile saya menemuin masalah padahal setting autoload untuk session sudah di aktifkan...

hasil compile dengan setting autoload session aktif dan tampilan formlogin ada tp ada pesan seperti ini:

A PHP Error was encountered

Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\lagi\system\application\config\config.php:1)

Filename: libraries/Session.php

Line Number: 662

============================================================
jika setting session di hilangkan tidak ada masalah tapi..sewaktu login nemuin pesan error seperti ini:

A PHP Error was encountered

Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\lagi\system\application\config\config.php:1)

Filename: helpers/url_helper.php

Line Number: 541

dengan error di bagian ini:
$this->session->set_userdata('userid','1');

trus saya ikutin tutorialnya ubah bagian ini jadi array dengan $userid=array():

$username = $_POST['uname'];
$password = $_POST['upass'];

tpi tetap error di bagian ini:
$this->session->set_userdata('userid','1');

mohon pencerahannya dunk kk,mas2,dll...........

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

hehehe...tanya2 lagi....

December 16, 2010 by merom, 33 weeks 6 days ago
Comment: 7474

merom's picture

makasiih gan...masalah kmren dah tak coba utak-atik ternyata bisa...skrang mw tanya gmna caranya meng include khan jquery ke dalam CI...trus gmna caranya scrpit2 jquerynya ga kliatan kalo di view source...??? maaf banyak tanya....

akhirnya ketemu jawabannya tapi...

November 27, 2010 by merom, 36 weeks 5 days ago
Comment: 7423

merom's picture

makasiih gan atas saran2nya....masalah ini saya udah dapat jawabannya ternyata bermasalah di ci editornya...jadi saya kroscek ulang pake manual...bisa...

tpi saya ada pertanyaan..kalo misal dibagian ceklogin di controllernya pengen dibuat pake database user kira2 gmana ya...jadi ceklogin itu ngecek dulu di database ada ga user dengan data yg kita input..

Buat di model and kulik dikit controller-nya

December 8, 2010 by andrewmalachel, 35 weeks 15 hours ago
Comment: 7460

andrewmalachel's picture

Untuk urusan soal database or pengelolaan penyimpanan data lainnya, buat di model...

karena ingin buat pengecekan login yang berhubungan dengan user, buat aja misalnya model dengan nama: user_model.php

di dalamnya buat fungsi utk check user sama pass nya...

mis.:

class User_model extends Model {
    function User_model() {
        parent::Model();
    }
    function authorize_login($nama, $pass) {
        $hasil = $this->db
            ->select('userid')
            ->from('nama_table_user')
            ->where('field_nama', $nama)
            ->where('field_pass', $pass)
            ->get();
        if($hasil->num_rows() != 1) return FALSE;
        else return $hasil->row()->userid;
    }
}

untuk di controllernya, bagian ceklogin tinggal buat:
(PS: di contoh anda,
controllernya: "test", and
method nya: "cek" bukan "ceklogin")

function ceklogin() {
    // biasakan pakai input handler nya CI...
    // xss clean nya canggih!
    $username = $this->input->post('uname', TRUE); 
    $password = $this->input->post('upass', TRUE);
    // kalau username/password ada yg kosong, 
    // lsg aja lempar ke index...
    if( ! $username || ! $password ) {
        $this-index();
    } else {
        // load model nya
        $this->load->model('user_model');
        // check otorisasinya user dan pass
        $checkpoint = 
            $this->user_model->
                authorize_login($username, $password);
        // kalau gagal, lempar balik ke index...
        if( ! $checkpoint) {
            $this->index();
        } else {
            // masukin di session dulu, userid nya..
            $this->session
                ->set_userdata('userid',$checkpoint);
            // menuju ke method "utama"...
            $this->utama();
        }
    }
}

gitu deh kira2...
btw, ada typo di function logout...
ntar bisa ngga logout lho...

keep practicing!

HEX?

November 26, 2010 by andrewmalachel, 36 weeks 6 days ago
Comment: 7411

andrewmalachel's picture

Kalau pakai notepad++ (or ada program buat HEXA editor), coba liat config.php nya... kadang (ngga tau kenapa, tapi kejadian beberapa kali sama saya) di sebelah kiri dari < ?php ada karakter yang ngga keliatan kecuali diliat dari hexa nya...

di notepad++, ada di:
Plugins >> Hex-Editor >> View in HEX ..
klo lum ada plugins nya, yaaa donlot dulu, gan...

Hmmm.... (bergumam.. sebelum bicara... bukan hmmm sinis... pis:)

November 22, 2010 by cahndeso, 37 weeks 3 days ago
Comment: 7395

cahndeso's picture

Ok... cek beberapa hal berikut:
1. Pastikan memang tidak ada baris kosong / spasi sebelum open tag pada file config.php
2. Pastikan file (model, controller, helper kita) tidak ada closing tag.
3. Jika tetap tidak berjalan, coba copy-kan file config.php yang baru (dari arsip download, mungkin) bila perlu download ulang, copy file config.php baru ini. (hapus dulu yang lama tentunya)..kemudian sesuaikan konfigurasinya sesuai keinginan anda.. (sebab bisa juga memang file config.php nya rusak..)
4. Ada juga yang melaporkan bahwa text editor juga berpengaruh (yang dilaporkan adalah macromedia dreamweaver, karena bermasalah dengan encoding UTF-8 yang dipakai CI), notepad++ aman. sy sendiri pakai netbeans (source code default encode-nya UTF-8).
5. Jika semua hal diatas tetap tidak membuahkan hasil, mau tidak mau (ini langkah diambil jika anda punya akses ke php.ini) ubah konfigurasi php.ini, ubah value pada pada bagian output_buffering menjadi on:
output_buffering = On / jangan Off.
restart apache anda..
6. Jika semua tetap tidak berjalan....? saya harap ada hal diatas yang menjadi solusi..

pis... happy coding..

Hmmm.... (bergumam.. sebelum bicara... bukan hmmm sinis... pis:)

November 22, 2010 by cahndeso, 37 weeks 3 days ago
Comment: 7394

cahndeso's picture

(sorry... send 2 kali...), gak sengaja... waktu send pertama, modem langsung off... jadi resend.. eh malah 2 kali..

Ok... cek beberapa hal berikut:
1. Pastikan memang tidak ada baris kosong / spasi sebelum open tag.
2. Pastikan file (model, controller, helper kita) tidak ada closing tag.
3. Jika tetap tidak berjalan, coba copy-kan file config.php yang baru (dari arsip download, mungkin) bila perlu download ulang, copy file config.php baru ini. (hapus dulu yang lama tentunya)..kemudian sesuaikan konfigurasinya sesuai keinginan anda.. (sebab bisa juga memang file config.php nya rusak..)
4. Ada juga yang melaporkan bahwa text editor juga berpengaruh (yang dilaporkan adalah macromedia dreamweaver, karena bermasalah dengan encoding UTF-8 yang dipakai CI), notepad++ aman. sy sendiri pakai netbeans (source code default encode-nya UTF-8).
5. Jika semua hal diatas tetap tidak membuahkan hasil, mau tidak mau (ini langkah diambil jika anda punya akses ke php.ini) ubah konfigurasi php.ini, ubah value pada pada bagian output_buffering menjadi on:
output_buffering = On / jangan Off.
restart apache anda.
6. Jika semua tetap tidak berjalan....? saya harap ada hal diatas yang menjadi solusi..

pis... happy coding..

Nyambung lagi Mas

November 22, 2010 by harisbag, 37 weeks 3 days ago
Comment: 7391

harisbag's picture

Kemarin dan hari ini saya juga menemui hal yang mirip dengan anda. Errornya adalah header already been sent pada saat saya memunculkan view untuk generate PDF. Nah saya utak-atik pake cara biasa ngga bisa... baris pertama udah mentok ga ada spasi atau ketikan yg bikin header terkirim duluan sebelum pdf padahal. baru sembuh en bisa nongol tuh si PDF setelah aku timpa dengan file baru dimana isi codingnya sama persis krn sy copy paste. Pengalaman sy error bisa terjadi karena struktur file agak error/rusak. (Sering ubah dan simpan serta bolak-balik kena RAR/kompresi). Semoga ini bisa menjadi inspirasi anda mas. Kali aja file config.phpnya yg error .... [Sekedar berbagi]

hmmm..

November 22, 2010 by merom, 37 weeks 3 days ago
Comment: 7390

merom's picture

saya udah coba cek kesalahan d config.php katanya di baris 1 ini tampilan baris 1 config.php saya...kalo bisa kasih tau errornya dmana...

  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
|	http://example.com/
|
*/
$config['base_url']	= "http://localhost/lagi/";
 
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = "index.php";
 
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string.  The default setting of "AUTO" works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'AUTO'			Default - auto detects
| 'PATH_INFO'		Uses the PATH_INFO
| 'QUERY_STRING'	Uses the QUERY_STRING
| 'REQUEST_URI'		Uses the REQUEST_URI
| 'ORIG_PATH_INFO'	Uses the ORIG_PATH_INFO
|
*/
$config['uri_protocol']	= "AUTO";
 
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/urls.html
*/
 
$config['url_suffix'] = "";
 
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language']	= "english";
 
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
*/
$config['charset'] = "UTF-8";
 
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the "hooks" feature you must enable it by
| setting this variable to TRUE (boolean).  See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
 
 
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries.  For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
 
 
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify with a regular expression which characters are permitted
| within your URLs.  When someone tries to submit a URL with disallowed
| characters they will get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible.  By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
 
 
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string "words" that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] 	= 'c';
$config['function_trigger'] 	= 'm';
$config['directory_trigger'] 	= 'd'; // experimental not currently in use
 
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| If you have enabled error logging, you can set an error threshold to 
| determine what gets logged. Threshold options are:
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
|	0 = Disables logging, Error logging TURNED OFF
|	1 = Error Messages (including PHP errors)
|	2 = Debug Messages
|	3 = Informational Messages
|	4 = All Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
 
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| system/logs/ folder.  Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
 
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
 
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| system/cache/ folder.  Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
 
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class or the Sessions class with encryption
| enabled you MUST set an encryption key.  See the user guide for info.
|
*/
$config['encryption_key'] = "";
 
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'session_cookie_name' = the name you want for the cookie
| 'encrypt_sess_cookie' = TRUE/FALSE (boolean).  Whether to encrypt the cookie
| 'session_expiration'  = the number of SECONDS you want the session to last.
|  by default sessions last 7200 seconds (two hours).  Set to zero for no expiration.
| 'time_to_update'		= how many seconds between CI refreshing Session Information
|
*/
$config['sess_cookie_name']		= 'ci_session';
$config['sess_expiration']		= 7200;
$config['sess_encrypt_cookie']	= FALSE;
$config['sess_use_database']	= FALSE;
$config['sess_table_name']		= 'ci_sessions';
$config['sess_match_ip']		= FALSE;
$config['sess_match_useragent']	= TRUE;
$config['sess_time_to_update'] 	= 300;
 
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path'   =  Typically will be a forward slash
|
*/
$config['cookie_prefix']	= "";
$config['cookie_domain']	= "";
$config['cookie_path']		= "/";
 
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
*/
$config['global_xss_filtering'] = FALSE;
 
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads.  When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| VERY IMPORTANT:  If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts.  For
| compression to work, nothing can be sent before the output buffer is called
| by the output class.  Do not "echo" any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
 
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are "local" or "gmt".  This pref tells the system whether to use
| your server's local time as the master "now" reference, or convert it to
| GMT.  See the "date helper" page of the user guide for information
| regarding date handling.
|
*/
$config['time_reference'] = 'local';
 
 
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files.  Options are TRUE or FALSE (boolean)
|
*/
$config['rewrite_short_tags'] = FALSE;
 
 
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy IP
| addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR
| header in order to properly identify the visitor's IP address.
| Comma-delimited, e.g. '10.0.1.200,10.0.1.201'
|
*/
$config['proxy_ips'] = '';
 
 
/* End of file config.php */
/* Location: ./system/application/config/config.php */

pencerahan

November 22, 2010 by merom, 37 weeks 3 days ago
Comment: 7387

merom's picture

thx...saya juga binggung errornya kok k config...y nanti saya cek lagi config dan pengaturannya....soalnya udah utak-atik masih error...

umm kayaknya bukan itu deh

November 21, 2010 by heidymadia, 37 weeks 3 days ago
Comment: 7386

heidymadia's picture

mas meron,

saya sudah coba buat ulang code mas meron di local saya.
Berikut hasil nya

1. line ini
if ($this->session->user_data('userid')=='1')
harusnya
if ($this->session->userdata('userid')=='1')
2. perhatikan file config/config.php seperti yang mas harisbag tulis di comment sebelumnya. Plus perhatikan line
$config['base_url']     =
dan ini
$config['index_page']   =
3. semua error mas meron seperti ini

Message: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\lagi\system\application\config\config.php:1)

Error ini terjadi bila mas meron sudah menuliskan sesuatu ke layar lalu melakukan redirect. (Entah karena echo, var_dump, atau print_r). Yang jelas coba lagi cek file config.php mas meron line 1.

berikut file yang saya buat
controller

<?php
Class User extends Controller {
	function User()
	{
		parent::Controller();
		$this->load->library('session');
		$this->load->helper('url');
	}
 
	function index()
	{
		$this->load->view('merom/formlogin');
	}
 
	function ceklogin()
	{
 
		$username = $_POST['uname'];
		//$username = 'abcde';
		$password = $_POST['upass'];
		//$password = '12345';
 
		if ($username == 'abcde' &&  $password== '12345')
		{
			$this->session->set_userdata('userid','1');
			redirect('merom/user/utama/','refresh');
		}
		else
		{
			$this->index();
		}
	}
 
	function utama()
	{
 
		if ($this->session->userdata('userid')=='1')
		{
			echo "<h3 align='center'>halaman utama admin</h3>";
			echo "halaman ini hanya diakses admin<br><br>";
			echo anchor ("merom/user/logout","logout");
		}
		else
		{
			redirect('merom/user/index','refresh');
		}
	}
 
	function logout()
	{
		$this->session->unset_userdata('$userid');
		redirect('merom/user/index','refresh');
	}
}

view

<div id="formlogin">
	<form method="post" action="ceklogin" >
		Username&nbsp;&nbsp;&nbsp;<input type="text" name="uname" id="uname"/><br/>
		Pass&nbsp;&nbsp;&nbsp;<input type="password" name="upass" id="upass"/><br/>
		<input type="submit" />
	</form>
</div>

happy coding.

h.m

PS: saya berharap ini bukan cuma pertanyaan hit and run seperti "biasanya" :P

Hmmmm.....

November 21, 2010 by cahndeso, 37 weeks 3 days ago
Comment: 7385

cahndeso's picture

pastikan di baris pertama file config.php sebelum open tag (<?php) tidak ada spasi atau baris kosong.

Pada file-file lain yang kita buat... jangan beri closing tag ( ?> ). Jika memang lebih senang menggunakan closing tag.. (sebagaimana aturan penulisan program php) ... pastikan tidak ada spasi atau baris baru sesudahnya... (praktek yang lebih baik adalah jangan gunakan closing tag di file yang kita buat)...

semoga membantu... happy coding...

Form Login

November 21, 2010 by harisbag, 37 weeks 4 days ago
Comment: 7381

harisbag's picture

hmmm ... mungkin configurasi nya ada masalah mengenai $config['sess_time_to_update'] ; sebab saya juga menemuinya meski agak beda. Setelah saya set ke lebih dari 5 menit, akhirnya tidak ada kendala. Warning itu muncul setelah halaman ditampilkan kemudian saya diamkan selang 5 menit ( = 300 ). Saya ga sadar pertama kali, namun karena seringnya muncul, akhirnya saya ubah $config['sess_time_to_update'] = '7200' baru sembuh. config ini sepertinya membatasi idle hubungan dengan server, apabila idle melebihi batas waktu yg ditentukan maka session akan dianggap expired. Mungkin begitu ...
===========================================
contoh Error
A PHP Error was encountered

Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at C:\server\htdocs\new\application\controllers\penilaian\nilai_akhir.php:1)

Filename: codeigniter/Common.php

Line Number: 360

Premium Drupal Themes by Adaptivethemes