Koleksi fungsi-fungsi PHP favorit OmPuter

Di bawah ini adalah snippet kode function-function PHP yang saya buat dan sebagian saya ambil dari internet, saya kumpulkan dalam sebuah file bernama functions.php dan sering saya gunakan di tutorial-tutorial saya di channel YouTube saya.

Silahkan jika ingin copy paste, berikut ini source nya:

<?php

//Make table if not exists
function maketable($table){
	global $connection;
    mysqli_query($connection, "CREATE TABLE IF NOT EXISTS $table (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY
    )");
}

//Check column and make it if not exist
function makecolumn($columnname, $tablename, $ctype){
	global $connection;
    if(!mysqli_query($connection, "SELECT $columnname FROM $tablename")){
        mysqli_query($connection, "ALTER TABLE $tablename ADD $columnname $ctype");
    }
}

//Esc sql
function escsql($data){
	global $connection;
	return mysqli_real_escape_string($connection, $data);
}

//Query
function query($q){
	global $connection;
	return mysqli_query($connection, $q);
}

//Make option data
function getoption($optionname){
	global $connection;
	global $tableoptions;
	$sql = "SELECT optionvalue FROM $tableoptions WHERE optionname = '$optionname'";
	$result = mysqli_query($connection, $sql);
	if($result){
		if(mysqli_num_rows($result) > 0){
			return mysqli_fetch_assoc($result)["optionvalue"];
		}else{
			return false;
		}
	}else{
		return false;
	}
}

//Set option data
function setoption($optionname, $optionvalue){
	global $connection;
	global $tableoptions;
	
	//check if row exists
	$sql = "SELECT * FROM $tableoptions WHERE optionname = '$optionname'";
	$result = mysqli_query($connection, $sql);
	if($result){
		if(mysqli_num_rows($result) > 0){
			//update
			mysqli_query($connection, "UPDATE $tableoptions SET optionvalue = '$optionvalue' WHERE optionname = '$optionname'");
		}else{
			//add
			mysqli_query($connection, "INSERT INTO $tableoptions (optionname, optionvalue) VALUES ('$optionname', '$optionvalue')");
		}
	}
}

//Secure input
function secureinput($text){
	$text = str_replace("<", "*", $text);
	$text = str_replace(">", "*", $text);
	$text = str_replace("script", "*", $text);
	return $text;
}

//Generate random numbers
function randnum($count){
    return substr(str_shuffle(str_repeat("0123456789", 5)), 0, $count);
}

//Generate random characters
function randchar($count){
    return substr(str_shuffle(str_repeat("abcdefghijklmnopqrstuvwxyz", 5)), 0, $count);
}

//Mil to date
function miltodate($mil){
	if(is_numeric($mil)){
    $seconds = $mil / 1000;
		$date = date("d-m-Y", $seconds); 
		$time = date("h:i:sa", $seconds);
		return $date . " " . $time . "<br>(" . humanTiming($seconds) . " yang lalu)";
	}else{
		return "-";
	}
}


//Readable human timing
function humanTiming ($time){
    $time = time() - intval($time); // to get the time since that moment
    $time = ($time<1)? 1 : $time;
    $tokens = array (
        31536000 => 'tahun',
        2592000 => 'bulan',
        604800 => 'minggu',
        86400 => 'hari',
        3600 => 'jam',
        60 => 'menit',
        1 => 'detik'
    );

    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'':'');
    }
}

//Get current millisecond
function getCurrentMillisecond(){
    return round(microtime(true) * 1000);
}

//Space separator
function spacesep($content, $digits){
	return chunk_split($content . "", $digits, " ");
}

//New new lines
function nonewline($text){
	return trim(preg_replace('/\s\s+/', '', $text));
}

//Get user ip address
function getuserip() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

//Get Today date
function todaydate(){
	return date("m/d/Y");
}

//Slugify
function slugify($text, string $divider = '-')
{
  // replace non letter or digits by divider
  $text = preg_replace('~[^\pL\d]+~u', $divider, $text);

  // transliterate
  $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

  // remove unwanted characters
  $text = preg_replace('~[^-\w]+~', '', $text);

  // trim
  $text = trim($text, $divider);

  // remove duplicate divider
  $text = preg_replace('~-+~', $divider, $text);

  // lowercase
  $text = strtolower($text);

  if (empty($text)) {
    return 'n-a';
  }

  return $text;
}

Selain itu, ada juga snippet yang sering saya pakai sebagai setingan koneksi database MySQL yang bentuknya seperti ini:

<?php

$baseurl = "http://localhost/DM/donasi/";
date_default_timezone_set('Asia/Jakarta');

//Database connection
$host = "localhost";
$dbuser = "root";
$dbpassword = "";
$databasename = "mydatabase";

$connection = mysqli_connect($host, $dbuser, $dbpassword, $databasename);
$connection->set_charset("utf8"); 

Itu biasanya saya simpan sebagai file dbconnection.php dan ketika diinclude kita akan mempunyai variable $connection yang dapat kita pakai untuk konek ke database jika ingin menjalankan perintah-perintah query.

Ada juga snippet ini yang isinya snippet yang jika dijalankan dia akan men-generate tabel-tabel database yang diperlukan aplikasi web kita:

<?php


//Table Prefix
$tableprefix = "mysite_";

//Table Names with Prefix
$tableoptions = $tableprefix . "options";

//Table Options -> don't modify
maketable($tableoptions);
makecolumn("optionname", $tableoptions, "VARCHAR (300) NOT NULL");
makecolumn("optionvalue", $tableoptions, "VARCHAR (2000) NOT NULL");
//--> don't modify

Biasanya saya simpan snippet ini dalam sebuah file bernama dbinit.php

loading...

Tinggalkan Balasan

Alamat email Anda tidak akan dipublikasikan.