Tampilkan postingan dengan label programing. Tampilkan semua postingan
Tampilkan postingan dengan label programing. Tampilkan semua postingan

Selasa, 10 Mei 2016

PHP - Move Array to Beginning or End of array

Tidak ada komentar:
PHP - Move Array to Beginning or End of array

Move element to first array by key

$myArray = array('one' => $myArray['one']) + $myArray;


Move element to end array by key

$myArray = $myArray + array('one' => $myArray['one']);

Senin, 24 Juni 2013

Convert Date Format to YYYY-MM-DD with PHP

Tidak ada komentar:

How Convert Date Format to YYYY-MM-DD with PHP


$date = "07/12/2010";
$your_date = date("Y-m-d", strtotime($date));

Senin, 12 November 2012

How to Detect Browser Internet Explorer with PHP

Tidak ada komentar:

How to Detect Browser Internet Explorer with PHP


You know, if you are website programmer or website designer you will understand why so important to detect Internet Explorer browser, cause generaly this browser have different treatment  in processing html, css and javascript. So maybe you need different page for this browser.
So this is PHP script will help you for detect Internet Explorer Browser or not.

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], '(compatible; MSIE ')!==FALSE) {
   //action for internet explorer
   header('location:form-ie.php?idu='.$_GET['idu']);  
} else {
      //action for other browser
header('location:form.php?idu='.$_GET['idu']);
}


Rabu, 07 November 2012

Handling Event Window Close or Reload With jQuery

Tidak ada komentar:

Handling Event Window Close or  Reload With jQuery

         When we want to know that the user will leave the pages of the website, we need a trigger that can be used as a reference to determine the user has left the website pages.
There are some conditions in which the user can leave the web page:

- Refresh or reload page
- Back to previous page
- Close page

example with javascript:
window.onunload=function(){SomeJavaScriptCode};

example with jquery
$(window).unload(function() {
    //some javascript code
}

Some Problem :
onUnload only working on Firefox , Internet Explorer and Opera

Senin, 22 Oktober 2012

Sejarah Bahasa Pemrograman PHP

Tidak ada komentar:

                 Sejarah Bahasa Pemrograman PHP

Logo PHP Banyak Programmer PHP tidak mengetahui sejarah dari PHP, berikut adalah sedikit sejarah pendek dari bahasa pemrograman yang sangat populer di seluruh dunia.  

PHP diciptakan oleh Rasmus Lerdorf, seorang pemrograman C yang andal. semula PHP hanya digunakan untuk mencatat jumlah pengunjung pada homepagenya. Pada waktu itu PHP masih bernama Form Interpreted (FI), yang wujudnya berupa sekumpulan skrip yang digunakan untuk mengolah data formulir dari web.
Selanjutnya Rasmus merilis kode sumber tersebut untuk umum dan menamakannya PHP/FI. Dengan perilisan kode sumber ini menjadi sumber terbuka, maka banyak pemrogram yang tertarik untuk ikut mengembangkan PHP.
zeev suraski PHPrasmus lerdorf Founder PHPandi gutsman PHP

Pada November 1997, dirilis PHP/FI 2.0. Pada rilis ini, interpreter PHP sudah diimplementasikan dalam program C. Dalam rilis ini disertakan juga modul-modul ekstensi yang meningkatkan kemampuan PHP/FI secara signifikan. Pada tahun 1997, sebuah perusahaan bernama Zend yang terdiri  dari sebuah kelompok pengembangan software yang terdiri dari Rasmus, Zeew Suraski, Andi Gutman, Stig Bakken, Shane Caraveo dan Jim Winstead bekerja selama tujuh bulan ulang interpreter PHP menjadi lebih bersih, lebih baik, dan lebih cepat. Kemudian pada Juni 1998, perusahaan tersebut merilis interpreter baru untuk PHP dan meresmikan rilis tersebut sebagai PHP 3.0 dan singkatan PHP diubah menjadi akronim berulang PHP: Hypertext Preprocessing.

zend logo php company

Pada pertengahan tahun 1999, Zend merilis interpreter PHP baru dan rilis tersebut dikenal dengan PHP 4.0. PHP 4.0 adalah versi PHP yang paling banyak dipakai pada awal abad ke-21. Versi ini banyak dipakai disebabkan kemampuannya untuk membangun aplikasi web kompleks tetapi tetap memiliki kecepatan dan stabilitas yang tinggi.
Pada Juni 2004, Zend merilis PHP 5.0. Dalam versi ini, inti dari interpreter PHP mengalami perubahan besar. Versi ini juga memasukkan model pemrograman berorientasi objek ke dalam PHP untuk menjawab perkembangan bahasa pemrograman ke arah paradigma berorientasi objek.

Kelebihan PHP dari bahasa Pemrograman lain

  1. 'Bahasa pemrograman PHP adalah sebuah bahasa script yang tidak melakukan sebuah kompilasi dalam penggunaanya.'
  2. 'Web Server yang mendukung PHP dapat ditemukan dimana - mana dari mulai apache, IIS, Lighttpd, hingga Xitami dengan konfigurasi yang relatif mudah.'
  3. 'Dalam sisi pengembangan lebih mudah, karena banyaknya milis - milis dan developer yang siap membantu dalam pengembangan.'
  4. 'Dalam sisi pemahamanan, PHP adalah bahasa scripting yang paling mudah karena memiliki referensi yang banyak.'
  5. 'PHP adalah bahasa open source yang dapat digunakan di berbagai mesin (Linux, Unix, Macintosh, Windows) dan dapat dijalankan secara runtime melalui console serta juga dapat menjalankan perintah-perintah system.'

sumber : - http://id.wikipedia.org/wiki/PHP
               - Pemrograman Web dengan PHP karya Yudhi Purwanto

Rabu, 10 Oktober 2012

Senin, 19 Desember 2011

How To Create Array to XML with PHP

Tidak ada komentar:
How to Create Array to XML with PHP

Extensible Markup Language (XML) is a markup language which defines a set of rules for encoding documents in a format which is both human-readable and machine-readable. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications, all  open standards.

<?php
$data = array(
  'name' => array(
    'first' => 'Randy',
    'last' => 'Septian'
  ),
  'phone' => array(
    'personal' => array(
      'mobile' => '085687xxxxx',
      'home' => '0217788xxxx'
    ),
    'office' => array(
      'fax' => '0217788xxxx'
    )
  ),
  'gender' => 'male'
);

$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('root');

function write(XMLWriter $xml, $data){
    foreach($data as $key => $value){
        if(is_array($value)){
            $xml->startElement($key);
            write($xml, $value);
            $xml->endElement();
            continue;
        }
        $xml->writeElement($key, $value);
    }
}
write($xml, $data);
$xml->endElement();
echo $xml->outputMemory(true);
?>

Minggu, 11 Desember 2011

Get Date Yesterday in PHP

Tidak ada komentar:
 How to get date of yesterday in php ??
$yesterday = date("Y-m-d",strtotime("-1 day"));

echo $yesterday;

Kamis, 24 November 2011

How To Insert and View Vietnam Font To Mysql And PHP

Tidak ada komentar:
Later I 've got problem with Vietnam Font when I insert Vietnam font on my web, can't save on Mysql, then i change colation with utf8_general_ci


ALTER TABLE `table-name` CHANGE  `table-name`. `field_name` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL

Jumat, 18 November 2011

PHP Error Logging Reporting Handler

Tidak ada komentar:
PHP Error, Logging, Reporting and Handler 


1. error_get_last()
example:
echo $testing;print_r(error_get_last());?>
Output :
Array([type] => 8[message] => Undefined variable: testing[file] => C:\webfolder\test.php[line] => 2)



2. error_log(error,type,destination,headers)
ParameterDescription
errorRequired. The error message to log
typeOptional. Specifies the error log type.
Possible log types:
  • 0 - Default. The error is sent to the servers logging system or a file, depending on how the error_log configuration is set in the php.ini file
  • 1 - The error is sent by email to the address in the destination parameter. This message type is the only one that uses the headers parameter
  • 2 - The error is sent through the PHP debugging connection. This option is only available in PHP 3
  • 3 - The error is added to the file destination string
destinationOptional. Specifies where to send the error message. The value of this parameter depends on the value of the "type" parameter
headersOptional. Only used if the "type" parameter is "1". Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n).Note: When sending an email, it must contain a From header. This can be set with this parameter or in the php.ini file.
example:
$test=2;
if ($test>1){error_log("A custom error has been triggered",1,"someone@example.com","From: webmaster@example.com");}?>
Output:
A custom error has been triggered


3. error_reporting(report_level)
ValueConstantDescription
1E_ERRORFatal run-time errors. Errors that can not be recovered from. Execution of the script is halted
2E_WARNINGNon-fatal run-time errors. Execution of the script is not halted
4E_PARSECompile-time parse errors. Parse errors should only be generated by the parser
8E_NOTICERun-time notices. The script found something that might be an error, but could also happen when running a script normally
16E_CORE_ERRORFatal errors at PHP startup. This is like an E_ERROR in the PHP core
32E_CORE_WARNINGNon-fatal errors at PHP startup. This is like an E_WARNING in the PHP core
64E_COMPILE_ERRORFatal compile-time errors. This is like an E_ERROR generated by the Zend Scripting Engine
128E_COMPILE_WARNINGNon-fatal compile-time errors. This is like an E_WARNING generated by the Zend Scripting Engine
256E_USER_ERRORFatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
512E_USER_WARNINGNon-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
1024E_USER_NOTICEUser-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
2048E_STRICTRun-time notices. PHP suggest changes to your code to help interoperability and compatibility of the code
4096E_RECOVERABLE_ERRORCatchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
8191E_ALLAll errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)
example:
//Disable error reportingerror_reporting(0);
//Report runtime errorserror_reporting(E_ERROR | E_WARNING | E_PARSE);
//Report all errorserror_reporting(E_ALL);?>


4. restore_error_handler()
example:
//custom error handler functionfunction customError($errno, $errstr, $errfile, $errline)  {  echo "Custom error: [$errno] $errstr
";
  echo " Error on line $errline in $errfile
";
  }
//set user-defined error handlerset_error_handler("customError");
$test=2;
//trigger errorif ($test>1)  {  trigger_error("A custom error has been triggered");  }
//restore built-in error handlerrestore_error_handler();
//trigger error againif ($test>1)  {  trigger_error("A custom error has been triggered");  }?>
Output
Custom error: [1024] A custom error has been triggeredError on line 14 in C:\webfolder\test.php
Notice: A custom error has been triggered in C:\webfolder\test.php on line 21

Jumat, 04 November 2011

Case Studies on PHP Website Security from XSS Attack and Sql Injection

Tidak ada komentar:
XSS (Cross Side Scripting) is a way to enter tag/script HTML  (injection) in to website for disrupt thats website.
Example attack with XSS: entered HTML or Javascript Code in some form, such like Comment Form. entered comment like this

I want to enter comment with  <script>alert('this xss attack'); </scipt>

if thats website don't have XSS filtering, when the comment appear, the alert script will working.
In PHP there are so many function, where we can use for xss attack filtering, and we can combine to make own xss filtering function



function xss_filtering($text) {
     $f = stripslashes (strip_tags (htmlspecialchars ($text, ENT_QUOTES)));
    return $f;
}
$text_comment = xss_filtering($_POST['comment']);



SQL Injection is a technic for manipulation sql command ..
Example Sql Injection in login form with " 'OR 1=1;//     " , thats logic will like this

SELECT * FROM user_table WHERE username=' ' OR 1=1;// ' AND password ='anything';

the logic is true, and whos ever can enter, ok lets make anti sql injection with PHP.

function sql_injection_filtering($data){
    $filter = mysql_real_escape_string($data);
     return $filter;
}
$username = sql_injection_filtering($_POST['username']);
$password = sql_injection_filtering($_POST['password']);
if (!ctype_alnum($username) OR !ctype_alnum($password)){
    echo "Only alpha numeric";
} else {
    echo "Login Succes";
}

Sabtu, 20 Agustus 2011

Skema Warna untuk Netbeans mirip Gvim

Tidak ada komentar:

Mungkin hanya beberapa programer yang mengenal text Editor Gvim, saya juga baru mengenal text editor ini, dan saya langsung menyukainya, salah satu hal yang membuat saya menyukai text editor ini adalah tampilan skema warnanya yang sangat menarik.
Namun dari kekurangan fungsi gvim, saya masih tetap menggunakan netbeans, tapi yang saya inginkan memiliki tampilan skema warna yang sama seperti gvim untuk netbeans saya... dan akhirnya saya temukan..
berikut link download untuk skema warna untuk netbeans yang bernama desert

Senin, 08 Agustus 2011

Mengambil URL Dengan PHP

Tidak ada komentar:
Untuk mengambil URL yang sedang aktif menggunakan PHP dapat menggunakan fungsi PHP dibawah ini:


<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>

Kamis, 30 Juni 2011

View Logs From Console with tail greep APP

Tidak ada komentar:
~$ tail -f logs_name | grep APP

Resize Image PHP for Transparant Png or Gif Image

Tidak ada komentar:
$vdir_upload = FCPATH.'public/images/logo_theme/';
$vfile_upload = $vdir_upload . $this->upload->file_name;
switch($this->upload->file_ext)
{
case '.jpg':
case '.jpeg':
$im_src = imagecreatefromjpeg($vfile_upload);
break;
case '.gif':
$im_src = imagecreatefromgif($vfile_upload);
break;
case '.png':
$im_src = imagecreatefrompng($vfile_upload);
break;
default:
$im_src = false;
break;
}
$src_width = imageSX($im_src);
$src_height = imageSY($im_src);
$dst_width = 120;
$dst_height = 20;
$im = imagecreatetruecolor($dst_width,$dst_height);
//==========================================
$trnprt_indx = imagecolortransparent($im_src);
// If we have a specific transparent color
if ($trnprt_indx >= 0) {
// Get the original image's transparent color's RGB values
$trnprt_color = imagecolorsforindex($im_src, $trnprt_indx);
// Allocate the same color in the new image resource
$trnprt_indx = imagecolorallocate($im, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
// Completely fill the background of the new image with allocated color.
imagefill($im, 0, 0, $trnprt_indx);
// Set the background color for new image to transparent
imagecolortransparent($im, $trnprt_indx);
}
// Always make a transparent background color for PNGs that don't have one allocated already
elseif ($this->upload->file_ext == '.png') {
// Turn off transparency blending (temporarily)
imagealphablending($im, false);
// Create a new transparent color for image
$color = imagecolorallocatealpha($im, 0, 0, 0, 127);
// Completely fill the background of the new image with allocated color.
imagefill($im, 0, 0, $color);
// Restore transparency blending
imagesavealpha($im, true);
}
//===========================================
imagecopyresampled($im, $im_src, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
switch($this->upload->file_ext)
{
case '.jpg':
case '.jpeg':
imagejpeg($im,$vdir_upload . "mobile_" . $this->upload->file_name);
break;
case '.gif':
imagegif($im,$vdir_upload . "mobile_" . $this->upload->file_name);
break;
case '.png':
imagepng($im,$vdir_upload . "mobile_" . $this->upload->file_name);
break;
default:
break;
}

imagedestroy($im_src);
imagedestroy($im);

Rabu, 18 Mei 2011

Image Resize with PHP, mengubah ukuran gambar dengan PHP

Tidak ada komentar:
nih kodingnya...

<?php
$ext_image = $_FILES['namafile']['type']; // mendapatkan extension file yang di upload
$name_image = $_FILES['namafile']['nama']; // mendapatkan nama file yang di upload

$vdir_upload = $_SERVER['DOCUMENT_ROOT'].'/webgw/images/upload/'; // menentukan direktori untuk tempat gambar asli dan hasil di folder yang sama, ini gw pake ubuntu jadi bisa tentuin direktori lo aja
$vfile_upload = $vdir_upload . $name_image; // ini ambil file asli

// menyesuaikan type gambar yang akan di resize
switch($ext_image)
{
case 'image/jpg':
case 'image/jpeg':
$im_src = imagecreatefromjpeg($vfile_upload);
break;
case 'image/gif':
$im_src = imagecreatefromgif($vfile_upload);
break;
case 'image/png':
$im_src = imagecreatefrompng($vfile_upload);
break;
default:
$im_src = false;
break;
}

// mengambil ukuran asli dari gambar width dan height
$src_width = imageSX($im_src);
$src_height = imageSY($im_src);

// menentukan ukuran file yang akan dibuat
$dst_width = 120;
$dst_height = 20;

// Proses pembuatan image
$im = imagecreatetruecolor($dst_width,$dst_height);
imagecopyresampled($im, $im_src, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);

// nah ini proses penyimpanan image hasil ke folder yang sama berdasarkan extensinya, trus hasil gambar gw kasi nama hasil_namafile.pg
switch($ext_image)
{
case 'images/jpg':
case 'iamges/jpeg':
imagejpeg($im2,$vdir_upload . "hasil_" . $name_image);
break;
case 'images/gif':
imagegif($im2,$vdir_upload . "hasil_" . $name_image);
break;
case 'images/png':
imagepng($im2,$vdir_upload . "hasil_" . $name_image);
break;
default:

break;
}

//hapus gambar di memory
imagedestroy($im_src);
imagedestroy($im);

Minggu, 15 Mei 2011

Script untuk mengetahui device yang digunakan mobile phone atau PC/laptop

Tidak ada komentar:
kmaren sempet bingung nyari2 script php untuk menentukan device yang digunakan hanphone atau pc/laptop.. setelah nyari2 d internet ketemu dah nih script
<?php
function isMobile() {
if(isset($_SERVER["HTTP_X_WAP_PROFILE"])) {
return true;
}

if(preg_match("/wap\.|\.wap/i",$_SERVER["HTTP_ACCEPT"])) {
return true;
}

if(isset($_SERVER["HTTP_USER_AGENT"])){
$user_agents = array("midp", "j2me", "avantg", "docomo", "novarra", "palmos", "palmsource", "240x320", "opwv", "chtml", "pda", "windows\ ce", "mmp\/", "blackberry", "mib\/", "symbian", "wireless", "nokia", "hand", "mobi", "phone", "cdm", "up\.b", "audio", "SIE\-", "SEC\-", "samsung", "HTC", "mot\-", "mitsu", "sagem", "sony", "alcatel", "lg", "erics", "vx", "NEC", "philips", "mmm", "xx", "panasonic", "sharp", "wap", "sch", "rover", "pocket", "benq", "java", "pt", "pg", "vox", "amoi", "bird", "compal", "kg", "voda", "sany", "kdd", "dbt", "sendo", "sgh", "gradi", "jb", "\d\d\di", "moto");
foreach($user_agents as $user_string){
if(preg_match("/".$user_string."/i",$_SERVER["HTTP_USER_AGENT"])) {
return true;
}
}
}

if(preg_match("/iphone/i",$_SERVER["HTTP_USER_AGENT"])) {
return false;
}

return false;
}

if (isMobile()) {
echo "mobile";
}else{
echo "web";
}
?>

Jumat, 15 April 2011

Menggunakan URL SEO Friendly

Tidak ada komentar:
Mengapa harus menggunakan URL SEO Friendly ?
intinya.. kalau website kamu mau berada di posisi teratas pada pencarian Search Engine atau mesin pencari seperti Google, Yahoo atau Bing, digunakan metode Search Engine Optimizer, dari berbagai metode yang digunakan, salah satunya pada bagian URL.

Apa bedanya?
ini contoh URL yang tidak SEO Friendly example.com/baca_berita.php?data=berita&id=5
ini contoh URL yang SEO Friendly example.com/berita/5/menggunakan-seo-friendly


Bagaimana cara ubahnya.
Berikut ini adalah contoh prakteknya :


pertama kita bikin Database nya

CREATE TABLE berita
(
id_berita INT PRIMARY KEY AUTO_INCREMENT,
judul TEXT UNIQUE,
isi TEXT,
url_seo TEXT UNIQUE,
);

form_berita.php

<html>
<head>
<title>Form Berita</title>

</head>
<body>
<form action="input.php" method="post" >
<input type="text" name="judul" />
<textarea name="isi" ></textarea>
<input type="submit" value="Input" />
</form>
</body>
</hrml>

input.php

<?php
include 'db.php';
//menghalau XSS attack
$judul = mysql_real_escape_string($_POST['judul']);
$isi = mysql_real_escape_string($_POST['isi']);
$judul = htmlentities($judul);
$isi = htmlentities($isi);

//Mengganti judul biasa menjadi judul SEO
$judul_baru= $judul;
$judul_baru=preg_replace('/[^a-z0-9]/i',' ', $judul_baru);
$judul_seo=str_replace(" ","-",$judul_baru);

//Input data ke database
mysql_query("insert into berita(judul, isi, url_seo) values('$judul','$isiy','$judul_seol')");

header('location:tampil_berita.php');

?>

tampil_berita.php

<?php
include('db.php');
//tampil berita
$sql=mysql_query("select * from berita");
$count=mysql_num_rows($sql);
$body = '<table&gt';
while ($row=mysql_fetch_array($sql))
{
$body .= ' <tr&gt <td&gt < a href ="berita-$row[id_berita]-$row[url_seo]" > $row[judul] </a> </td&gt </tr&gt';
}
?>
$body .= '</table&gt';
//HTML Part
<body>
<?php
if($count)
{
echo "<h1>$title</h1><div class='body'>$body</div>";
}
else
{
echo "<h1>404 Page.</h1>";
}
?>


baca.php
<?php
$id_berita = $_GET['id'];

$query = mysql_fetch_array(mysql_query("select * from berita where id_berita = $id_berita "));

echo '<p>'.$query['judul'].'</p>';
echo '<p>'.$query['isi'].'</p>';

?>
sekarang bagian .htaccsess untuk membuat .htaccess bikin di notepad ketik

RewriteEngine On

RewriteRule ^berita-(.*).html$ baca.php?id=$1

lalu simpan dengan nama .htaccess


Senin, 11 April 2011

Codeigniter Upload Image

Tidak ada komentar:
Berikut ini adalah cara menggunakan library upload pada Codeigniter, untuk kali ini saya akan menggunakan file image atau gambar dengan format 'jpg, gif atau png'

pertama kita mulai pada bagian view:
pada bagian view terdapat dua halaman yang pertama untuk halaman utama/halaman gagal upload, yang kedua adalah halaman sukses upload.

hal_utama.php

<html>
<head>
<title>Upload Form</title>
</head>
<body>

<?php echo $error;?>
// jika file gagal d upload maka muncul error messgae

<?php echo form_open_multipart('upload/upload_file');?>
//form pembuka yg telah dilengkapi multipart form data

<input type="file" name="fupload" size="20" />

<br /><br />

<input type="submit" value="upload" />

</form>

</body>
</html>

hal_sukses.php

<html>
<head>
<title>Upload Form</title>
</head>
<body>

<h3>Your file was successfully uploaded!</h3>

<ul>
<?php foreach($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li> // jika file berhasil di upload akan muncul informasi tentang file trsebut
<?php endforeach; ?>
</ul>

<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>

</body>
</html>


selanjutnya pada bagian Controller

upload.php

<?php

class Upload extends CI_Controller {

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

function index()
{
$this->load->view('hal_utama', array('error' => ' ' ));
}

function upload_file()
{
$config['upload_path'] = './file/gambar/'; //direktori tempat gambar
$config['allowed_types'] = 'gif|jpg|png'; // jenis file yg boleh di upload
$config['max_size'] = '100'; // max ukuran file
$config['max_width'] = '1024';
$config['max_height'] = '768';

$this->load->library('upload', $config); // perintah konfigurasi pada library upload

if ( ! $this->upload->do_upload()) // perintah upload
{
$error = array('error' => $this->upload->display_errors());

$this->load->view('hal_utama', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());

$this->load->view('hal_ sukses', $data);
}
}
}
?>

kode di atas sudah cukup berfungsi, tpi saya pernah mengalami error atau gagal upload, dan solusi yang saya temukan sebagai berikut , saya hanya menambahakan 'fupload' = nama file, pada controller

........
$this->load->library('upload', $config); // perintah konfigurasi pada library upload

if ( ! $this->upload->do_upload(fupload)) // saya menambahkan pada bagian ini
{
$error = array('error' => $this->upload->display_errors());

$this->load->view('hal_utama', $error);
}
else
.........

Sabtu, 12 Desember 2009

Script untuk melihat Browser yang digunakan

2 komentar:
Bagaimana caranya website kita dapat mengenal Browser yang digunakan beserta versi browser yang digunakan.
mengapa ini perlu diketahui, karena pada saat pembuatan website ternyata tidak semua browser dapat membaca script, khususnya javascript dengan baik dan benar sesuai dengan yang kita inginkan..
oke... ini JavaScript yang dapat digunakan:


<div id="example"></div>

<script type="text/javascript">

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";

document.getElementById("example").innerHTML=txt;

</script>