menu

Engine PHP - Upload and download file


Hello codedoctors,

Kali ini codedoct akan sharing ilmu untuk membuat sebuah engine yang dapat meng-upload dan men-download suatu file. engine ini akan kita buat menggunakan bahasa PHP native.

Oke langsung saja kita mulai tutorialnya,

Pertama, buat folder projectnya terlebih dahulu dalam hal ini codedoct akan memberi nama file test-upload-download-file dan buat folder baru juga didalammnya dengan nama file sehingga struktur foldernya akan tampak seperti ini,


Kemudian, buat tabel pada database dengan struktur seperti ini,


Setelah itu, buat file baru dengan nama index.php seperti struktur diatas, dan isikan code berikut,
<?php
 include_once('uploadController.php');
?>
<head>
 <title>Hello | Budy</title>
</head>
<body>
 <div class="show-file">
  <ul>
   <?php
     $sql="SELECT * FROM upload_and_download_file";
     $hsl=mysql_query($sql,$db);
     $no=0;
     while(list($id,$name,$created_at)=mysql_fetch_array($hsl)){
       $no++;?>
      <li><?=$no?></li>
        <ul>
       <li><?=$name?></li>
       <li><?=$created_at?></li>
       <li><a href="downloadController.php?file_name=<?=$name?>">Download</a></li>
      </ul>
    <?php }
   ?>
  </ul>
 </div>
 <div class="upload-file">
  <form action="uploadController.php" method="post" enctype="multipart/form-data">
   <input type="file" name="uploadFile">
   <input type="submit" value="Upload" name="upload">
  </form>
 </div>
</body>

Selanjutnya, buat file baru dengan nama connection.php dan isikan code berikut,
<?php
 $servername = "localhost";
 $username = "root";
 $password = "root";
 $dbname = "test";

 $db=mysql_connect($servername,$username,$password);
 mysql_select_db($dbname,$db);
?>

Kemudian, buat file baru dengan nama model.php dan isikan code berikut,
<?php
 class FileController 
 {
  public function saveFile($name)
  {
   include 'connection.php';
   $sql="INSERT INTO upload_and_download_file (name,created_at) VALUES ";
      $sql.="('$name',NOW())";
    $save = mysql_query($sql,$db);

   if ($save) {
       return true;
   } else {
       echo "Error";
   } 
  }
 }
?>

Terakhir buat file baru dengan nama uploadController.php dan downloadController.php dan isikan code berikut,
uploadController.php
<?php
 include_once('connection.php');
 include_once('model.php');

 if (isset($_POST['upload'])) {
  $errors  = array();
  $file_name  = $_FILES['uploadFile']['name'];
  $file_size  = $_FILES['uploadFile']['size'];
  $file_tmp  = $_FILES['uploadFile']['tmp_name'];
  $file_ext = strtolower(end(explode('.',$_FILES['uploadFile']['name'])));

  $extensions = array("txt");

  if(in_array($file_ext,$extensions)===false){
   $errors[]="extension not allowed, please choose a TXT file.";
  }

  if($file_size > 1024000){
   $errors[]='File size must be excately 1 MB';
  }

  if(empty($errors)==true){
   //save file to folder file
   $filename = strtotime('now').'_'.$file_name;
   move_uploaded_file($file_tmp,"file/".$filename);

   //save file to database
   $model = new FileController;
   $save_file = $model->saveFile($filename);
   if ($save_file) {
    //back to project
    $path_project = "http://localhost/test/test-upload-download-file/";
    header("Location: $path_project");
   }
  }else{
   print_r($errors);
   ?><br><a href="/test/test-upload-download-file">Back</a><?php
  }
 }
?>

downloadController.php
<?php
    $file_name = $_GET['file_name'];
    $file = "file/".$file_name;

    if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");

    header("Pragma: public", true);
    header("Expires: 0"); // set expiration time
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Disposition: attachment; filename=".basename($file));
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".filesize($file));
    die(file_get_contents($file));
?>

Sehingga hasilnya akan tampak seperti gambar dibawah ini


Untuk enginenya bisa didownload disini,

===DONE!===

Laravel - Relation pada model (belongsToMany)


Hello codedoctors,

Setelah pada tutorial sebelumnya kita sudah membuat relasi tabel hasOne, tutorial kali ini kita akan membuat sebuah relasi tabel pada model dengan fungsi relasi belongsToMany yang berarti banyak field pada suatu tabel mempunyai banyak field pada tabel lain.

Dalam tutorial kali ini kita akan merelasikan antara tabel users dan tabel users itu sendiri dengan menggunakan pivot yang akan kita beri nama followes.

Oke untuk lebih memahaminya kita mulai saja tutorialnya,

Pertama, buat terlebih dahulu tabel pivotnya dengan nama followes, dengan cara php artisan migrate:make create_followes_table pada terminal atau cmd, sehingga akan otomatis membuat file migrate baru dengan nama <tanggal>_create_followes_table.php pada path protected/app/database/migrations/. Kemudian isi dengan code berikut,
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateFollowesTable extends Migration {

 /**
  * Run the migrations.
  *
  * @return void
  */
 public function up()
 {
  Schema::create('followes', function($table){
   $table->integer('following_user_id')->index('followes_following_user_id');
   $table->integer('follower_user_id')->index('followes_follower_user_id');
   $table->timestamps();
   $table->softDeletes();
   $table->primary(['following_user_id','follower_user_id']);
  });

  Schema::table('followes', function(Blueprint $table)
  {
   $table->foreign('following_user_id', 'followes_ibfk_1')->references('id')->on('users')->onUpdate('CASCADE')->onDelete('CASCADE');
   $table->foreign('follower_user_id', 'followes_ibfk_2')->references('id')->on('users')->onUpdate('CASCADE')->onDelete('CASCADE');
  });
 }

 /**
  * Reverse the migrations.
  *
  * @return void
  */
 public function down()
 {
  Schema::table('followes', function(Blueprint $table)
  {
   $table->dropForeign('followes_ibfk_1');
   $table->dropForeign('followes_ibfk_2');
  });

  Schema::drop('followes');
 }

}

Selanjutnya, buat file seeder baru dengan nama FollowSeeder.php pada path protected/app/database/seeds/ isi dengan code berikut,
<?php
 
class FollowSeeder extends Seeder
{
    public function run()
    {
        DB::table('followes')->delete();
        DB::table('followes')->insert(array (
            array (
                'following_user_id'       => 1,
                'follower_user_id'     => 2,
            ),
            array (
                'following_user_id'       => 2,
                'follower_user_id'     => 1,
            ),
            array (
                'following_user_id'       => 1,
                'follower_user_id'     => 3,
            ),
            array (
                'following_user_id'       => 2,
                'follower_user_id'     => 3,
            ),
        ));
    }
}

Kemudian, edit file seeder UserSeeder.php dan DatabaseSeeder.php pada path protected/app/database/seeds/ edit menjadi seperti ini,
UserSeeder.php
<?php
 
class UserSeeder extends Seeder
{
    public function run()
    {
        DB::table('users')->delete();
        DB::table('users')->insert(array (
            array (
                'id'       => 1,
                'name'     => 'Dracule Mihawk',
                'username' => 'mihawk',
                'email'    => 'mihawk@gmail.com',
                'role_id'     => 1,
                'password' => Hash::make('rahasiakampret'),
            ),
            array (
                'id'       => 2,
                'name'     => 'Trafalgar Law',
                'username' => 'trafa',
                'email'    => 'trafa@gmail.com',
                'role_id'     => 2,
                'password' => Hash::make('rahasiakampret'),
            ),
            array (
                'id'       => 3,
                'name'     => 'Dark King',
                'username' => 'dk',
                'email'    => 'dk@gmail.com',
                'role_id'     => 2,
                'password' => Hash::make('rahasiakampret'),
            ),
        ));
    }
}
Pada UserSeeder diatas kita menambahkan seeder user baru yaitu Dark King.

DatabaseSeeder.php
<?php

class DatabaseSeeder extends Seeder {

 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
  // Eloquent::unguard();
  DB::statement('SET FOREIGN_KEY_CHECKS=0;');

  $this->call('UserSeeder');
  $this->call('AddressSeeder');
  $this->call('RoleSeeder');
  $this->call('CompanySeeder');
  $this->call('FollowSeeder');

  DB::statement('SET FOREIGN_KEY_CHECKS=1;');
  \Cache::flush();
 }

}

Setelah itu, buat file model baru dengan nama Follow.php pada path protected/app/models/ dan isi dengan code berikut,
<?php namespace Model;

class Follow extends \Eloquent {

 /**
  * The database table used by the model.
  *
  * @var string
  */
 protected $table = 'followes';

 /**
  * The attributes excluded from the model's JSON form.
  *
  * @var array
  */
 protected $hidden = array('');
}

Edit file model User.php pada path protected/app/models/ menjadi seperti ini,
<?php namespace Model;

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
use Illuminate\Database\Eloquent\Model;
use \Eloquent;

class User extends Eloquent implements UserInterface, RemindableInterface {

 use UserTrait, RemindableTrait;

 /**
  * The database table used by the model.
  *
  * @var string
  */
 protected $table = 'users';

 /**
  * The attributes excluded from the model's JSON form.
  *
  * @var array
  */
 protected $hidden = array('password', 'remember_token');

 // Relation
 public function addresses()
    {
        return $this->hasMany('Model\Address');
    }

    public function role()
    {
        return $this->belongsTo('Model\Role');
    }

    public function company()
    {
        return $this->hasOne('Model\Company');
    }

    // follower dan following berbeda, coba pahami lebih detail
    public function follower()
    {
        return $this->belongsToMany('Model\User', 'followes', 'following_user_id', 'follower_user_id');
    }

    public function following()
    {
        return $this->belongsToMany('Model\User', 'followes', 'follower_user_id', 'following_user_id');
    }
}
Pada code diatas pahamilah code berikut: belongsToMany('nama_model_yang_akan berelasi', 'nama_tabel_pivot', 'foreign_key', 'relasi_foreign_key').

Edit pula file controller UserController.php pada path protected/app/controllers/relation/ menjadi seperti ini,
<?php namespace Controller\Relation;

use Model\User;
use \View;

class UserController extends \BaseController 
{
 public function getUserDetail($user_id)
 {
  $user = User::where('id', $user_id)->first();
  //code dibawah untuk panggil relasi dari model user
  if($user){
   $address = $user->addresses;
   $role = $user->role;
   $company = $user->company;
   $follower = $user->follower;
   $following = $user->following;
  }

  return View::make('web.relation.show-user-detail')->with('user', $user);
 }
}

Terakhir edit file blade show-user-detail.blade.php pada path protected/app/views/web/relation/ menjadi seperti ini,
@extends('layouts/web/master')
@section('content')
 <?php $title = "User" ?>
 <div class="isi">
  <div class="row">
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
           <th>ID</th>
           <th>NAME</th>
           <th>USERNAME</th>
           <th>EMAIL</th>
        </tr>
      </thead>
      <tbody>
        <tr>
      <td>{{ $user->id }}</td>
      <td>{{ $user->name }}</td>
      <td>{{ $user->username }}</td>
      <td>{{ $user->email }}</td>
        </tr>
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Nama alamat</th>
      <th>Kota</th>
      <th>Provinsi</th>
      <th>Alamat</th>
      <th>Zipcode</th>
      <th>Phone</th>
        </tr>
      </thead>
      <tbody>
       @forelse($user['addresses'] as $address)
         <tr>
       <td>{{ $address->name_address }}</td>
       <td>{{ $address->city }}</td>
       <td>{{ $address->province }}</td>
       <td>{{ $address->address }}</td>
       <td>{{ $address->zipcode }}</td>
       <td>{{ $address->phone }}</td>
         </tr>
        @empty
         Address not found
        @endforelse
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Role ID</th>
      <th>Role Name</th>
        </tr>
      </thead>
      <tbody>
       @if($user['role'])
         <tr>
       <td>{{ $user['role']->id }}</td>
       <td>{{ $user['role']->name }}</td>
         </tr>
        @else
         Role not found
        @endif
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Company Name</th>
      <th>Position</th>
        </tr>
      </thead>
      <tbody>
       @if($user['company'])
         <tr>
       <td>{{ $user['company']->name }}</td>
       <td>{{ $user['company']->position }}</td>
         </tr>
        @else
         Role not found
        @endif
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>No</th>
      <th>Follower</th>
        </tr>
      </thead>
      <tbody>
       <?php $no=1 ?>
       @forelse($user['follower'] as $follower)
         <tr>
       <td>{{ $no++ }}</td>
       <td>{{ $follower->name }}</td>
         </tr>
        @empty
         Follower not found
        @endif
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>No</th>
      <th>Following</th>
        </tr>
      </thead>
      <tbody>
       <?php $no=1 ?>
       @forelse($user['following'] as $following)
         <tr>
       <td>{{ $no++ }}</td>
       <td>{{ $following->name }}</td>
         </tr>
        @empty
         Follower not found
        @endif
       </tbody>
   </table>
  </div>
 </div>
@stop

Jangan lupa untuk mengcompile composer setelah membuat file model baru dengan cara


Sehingga hasilnya akan tampak seperti ini,


===DONE!===

Laravel - Relation pada model (hasOne)


Hello codedoctors, kembali lagi codedoct akan share ilmu gratis.

Melanjutkan tutorial sebelumnya, kita sudah membuat sebuah relasi belongsTo pada model. Pada tutorial kali ini kita akan membuat relasi hasOne pada model, dimana pada prinsipnya relasi ini akan membuat sebuah field tabel berelasi dengan sebuah field dari tabel lain.

Tabel yang akan kita relasikan adalah tabel user dengan tabel company, oke langsung saja kita mulai tutorialnya,

Pertama, kita buat dulu tabel company-nya dengan cara php artisan migrate:make create_companies_table pada terminal atau cmd, sehingga akan otomatis membuat file migrate baru dengan nama <tanggal>_create_companies_table.php pada path protected/app/database/migrations/. Kemudian isi dengan code berikut,
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCompaniesTable extends Migration {

 /**
  * Run the migrations.
  *
  * @return void
  */
 public function up()
 {
  Schema::create('companies', function($table){
   $table->integer('id', true);
   $table->integer('user_id')->index('companies_user_id');
   $table->string('name');
   $table->string('position');
   $table->timestamps();
  });

  Schema::table('companies', function(Blueprint $table)
        {
            $table->foreign('user_id', 'companies_ibfk_1')->references('id')->on('users')->onUpdate('CASCADE')->onDelete('CASCADE');
        });
 }

 /**
  * Reverse the migrations.
  *
  * @return void
  */
 public function down()
 {
  Schema::table('companies', function(Blueprint $table)
  {
   $table->dropForeign('companies_ibfk_1');
  });

  Schema::drop('companies');
 }

}

Kemudian, buat file seeder baru dengan nama CompanySeeder.php pada path protected/app/database/seeds/ isi dengan code berikut,
<?php
 
class CompanySeeder extends Seeder
{
    public function run()
    {
        DB::table('companies')->delete();
        DB::table('companies')->insert(array (
            array (
                'id'       => 1,
                'user_id'  => 1,
                'name'     => 'PT. HAHA',
                'position' => 'Software Engineer',
            ),
            array (
                'id'       => 2,
                'user_id'  => 2,
                'name'     => 'PT. HUHU',
                'position' => 'Marketing',
            ),
        ));
    }
}

Edit file DatabaseSeeder.php pada path protected/app/database/seeds/ dengan menambahkan seeder CompanySeeder menjadi seperti ini,
<?php

class DatabaseSeeder extends Seeder {

 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
  // Eloquent::unguard();
  DB::statement('SET FOREIGN_KEY_CHECKS=0;');

  $this->call('UserSeeder');
  $this->call('AddressSeeder');
  $this->call('RoleSeeder');
  $this->call('CompanySeeder');

  DB::statement('SET FOREIGN_KEY_CHECKS=1;');
  \Cache::flush();
 }

}

Setelah itu edit file UserController.php pada path protected/app/controllers/relation/ menjadi seperti ini,
<?php namespace Controller\Relation;

use Model\User;
use \View;

class UserController extends \BaseController 
{
 public function getUserDetail($user_id)
 {
  $user = User::where('id', $user_id)->first();
  //code dibawah untuk panggil relasi dari model user
  if($user){
   $address = $user->addresses;
   $role = $user->role;
   $company = $user->company;
  }
  return View::make('web.relation.show-user-detail')->with('user', $user);
 }
}

Edit file model User.php dan buat file model baru dengan nama Company.php pada path protected/app/models/ sehingga code keduanya akan tampak seperti ini,
User.php

<?php namespace Model;

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
use Illuminate\Database\Eloquent\Model;
use \Eloquent;

class User extends Eloquent implements UserInterface, RemindableInterface {

 use UserTrait, RemindableTrait;

 /**
  * The database table used by the model.
  *
  * @var string
  */
 protected $table = 'users';

 /**
  * The attributes excluded from the model's JSON form.
  *
  * @var array
  */
 protected $hidden = array('password', 'remember_token');

 // Relation
 public function addresses()
    {
        return $this->hasMany('Model\Address');
    }

    public function role()
    {
        return $this->belongsTo('Model\Role');
    }

    public function company()
    {
        return $this->hasOne('Model\Company');
    }
}

Company.php
<?php namespace Model;

class Company extends \Eloquent {

 /**
  * The database table used by the model.
  *
  * @var string
  */
 protected $table = 'companies';

 /**
  * The attributes excluded from the model's JSON form.
  *
  * @var array
  */
 protected $hidden = array('');
}

Terakhir edit file blade dengan nama show-user-detail.blade.php pada path protected/app/views/web/relation/ menjadi seperti ini,
@extends('layouts/web/master')
@section('content')
 <?php $title = "User" ?>
 <div class="isi">
  <div class="row">
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
           <th>ID</th>
           <th>NAME</th>
           <th>USERNAME</th>
           <th>EMAIL</th>
        </tr>
      </thead>
      <tbody>
        <tr>
      <td>{{ $user->id }}</td>
      <td>{{ $user->name }}</td>
      <td>{{ $user->username }}</td>
      <td>{{ $user->email }}</td>
        </tr>
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Nama alamat</th>
      <th>Kota</th>
      <th>Provinsi</th>
      <th>Alamat</th>
      <th>Zipcode</th>
      <th>Phone</th>
        </tr>
      </thead>
      <tbody>
       @forelse($user['addresses'] as $address)
         <tr>
       <td>{{ $address->name_address }}</td>
       <td>{{ $address->city }}</td>
       <td>{{ $address->province }}</td>
       <td>{{ $address->address }}</td>
       <td>{{ $address->zipcode }}</td>
       <td>{{ $address->phone }}</td>
         </tr>
        @empty
         Address not found
        @endforelse
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Role ID</th>
      <th>Role Name</th>
        </tr>
      </thead>
      <tbody>
       @if($user['role'])
         <tr>
       <td>{{ $user['role']->id }}</td>
       <td>{{ $user['role']->name }}</td>
         </tr>
        @else
         Role not found
        @endif
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Company Name</th>
      <th>Position</th>
        </tr>
      </thead>
      <tbody>
       @if($user['company'])
         <tr>
       <td>{{ $user['company']->name }}</td>
       <td>{{ $user['company']->position }}</td>
         </tr>
        @else
         Role not found
        @endif
       </tbody>
   </table>
  </div>
 </div>
@stop

Jangan lupa untuk mengcompile composer setelah membuat file model baru dengan cara


Sehingga tampilannya akan tampak seperti ini,


Coba cek database (phpmyadmin), saat anda menghapus salah satu field dari tabel users maka relasi tabel companies dan addresses juga ikut terhapus sedangkan field pada tabel role tidak terhapus, hal ini disebabkan karena relasi tabel companies menggunakan hasOne dan relasi tabel addresses menggunakan relasi hasMany dimana keduanya membutuhkan tabel users sebagai induknya (untuk lebih jelasnya pahamilah sendiri).

===DONE!===