Posts

Showing posts with the label PHP

Install XAMPP/LAMPP On Android (Non-Root)

Image
php apache setup on android with Termux (without root) Download Termux (allow installation from unknwon sources and install the termux app) Termux Setup Steps update packages (If it asks you, choose yes in both cases.) apt update -y && apt upgrade -y Install Apache and PHP 7 There is as of now a bundle that serves to introduce these two things together. That is, through apache PHP documents are prepared. To introduce our LAMPP on Android we will run: apt install php-apache That will install apache, PHP and a few libraries that will permit us to join the two things. configure apache to process the PHP files We are going to configure the httpd.conf file. Attention here, because the route is important. The apache configuration file is in /data/data/com.termux/files/usr/etc/apache2/httpd.conf You can change to that folder with: cd /data/ data /com.ter

Fix Uncaught Error Call to undefined function str_starts_with()

Image
Uncaught Error: Call to undefined function str_starts_with() Fix Solutions if (!function_exists('str_starts_with')) { function str_starts_with($haystack, $needle, $case = true) { if ($case) { return strpos($haystack, $needle, 0) === 0; } return stripos($haystack, $needle, 0) === 0; } } if (!function_exists('str_ends_with')) { function str_ends_with($haystack, $needle, $case = true) { $expectedPosition = strlen($haystack) - strlen($needle); if ($case) { return strrpos($haystack, $needle, 0) === $expectedPosition; } return strripos($haystack, $needle, 0) === $expectedPosition; } }

[PHP] Detect User Client IP (XAMPP or Localhost Machine Supported)

Usage: var_dump(get_client_ip()); /** * Detect is localhost * * @return boolean */ function isLocalHost() { $whitelist = [ '127.0.0.1', '::1', ]; return in_array($_SERVER['REMOTE_ADDR'], $whitelist); } /** * Get client ip, when getenv supported (maybe cli) * * @return string */ function get_client_ip() { $ipaddress = ''; if (isLocalHost()) { $ipaddress = getLocalIp(); } else { if (getenv('HTTP_CLIENT_IP')) { $ipaddress = getenv('HTTP_CLIENT_IP'); } elseif (getenv('HTTP_X_FORWARDED_FOR')) { $ipaddress = getenv('HTTP_X_FORWARDED_FOR'); } elseif (getenv('HTTP_X_FORWARDED')) { $ipaddress = getenv('HTTP_X_FORWARDED'); } elseif (getenv('HTTP_FORWARDED_FOR')) { $ipaddress = getenv('HTTP_FORWARDED_FOR'); } elseif (getenv('HTTP_FORWARDED')) { $ipaddress = getenv('HTTP_FORWARDED'); } elseif (ge

Calculate Swatch Internet Time Codes

PHP 12 bytes: <?php echo date('B'); ?> 48 bytes: <?php echo sprintf("%03d",((time()+3600)%86400)/86.4|0); ?> C,  56 bytes main(){printf("%03d",(int)((time(0)+3600)%86400/86.4));} Explanation: %03d  - tells printf to zero-pad up to 3 digits. time(NULL)+3600  - gets amount of seconds (UTC) elapsed since epoch and adds an hour to it (UTC+1). %86400  - divides epoch by the amount of seconds in a 24hr day and gets the remainder (representing seconds elapsed, so far, "today"). /86.4  - divide remaining seconds by 86.4 to get the ".beat" count since midnight (UTC+1). Compile (MSVC): C:> cl swatch.c Compile (GCC): $ gcc swatch.c Java 143 bytes import  java.time. * ; interface A  {   static void main(String[] a) {     System.out.format("%03.0f" ,  LocalTime.now(ZoneId.of("UT+1")).toSecondOfDay() / 86.4);    } } Javascript d=new Date();t=;console.log(Math.floor((360*d.getHours()+60*d.

PHP array magic trick and manipulations

manipulating multidimensional array using array_map /** * Ilterate multidimensional array simplicity * @desc modify and manipulate or populate multidimensional array with simple tricks * @param array $arr * @param function $callback * @return Array **/ function Map($arr, $callback) { if (!is_callable($callback)) { throw new Exception("Callback must be function", 1); } return array_map(function ($key, $val) use ($callback) { return call_user_func($callback, $key, $val); }, array_keys($arr), $arr); }

PHP Mailer work with AJAX

Image
Basic Mailer basic php mailer php <?php header('Access-Control-Allow-Origin: *'); header('Content-Type: application/json'); /* * CONFIGURE EVERYTHING HERE */ // an email address that will be in the From field of the email. $from = isset($_REQUEST['from']) ? $_REQUEST['from'] : 'example@mail.com'; $from = filter_var($from, FILTER_VALIDATE_EMAIL) ? $from : null; // an email address that will receive the email with the output of the form $sendTo = 'dimaslanjaka.superuser@blogger.com'; // subject of the email $subject = 'New message'; // form field names and their translations. // array variable name => Text to appear in the email $fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // message that will be displayed when everything is OK :) $okMess

Check if current function called statically or not

Image
$static = !(isset($this) && get_class($this) == __CLASS__); if ($static) { return self; } else { return $this; } in class example: class Foo { function bar() { $static = !(isset($this) && get_class($this) == __CLASS__); if ($static) { return self; } else { return $this; } } } or simply create below function to test: class A { function foo() { if (isset($this)) { echo '$this is defined ('; echo get_class($this); echo ")\n"; } else { echo "\$this is not defined.\n"; } } } How do I check in PHP that I'm in a static context (or not)?

Remove index.php?route= from opencart

Image
How to remove index.php?route= common issue from url bar for SEO url I Also have the same problem and any that I found not solved my problem. But! I remember that I also working with Laravel and in this engine well working url path. Don't ask why I associated OpenCart with Laravel. So I enable SEO radio button in System -> Settings -> Server you also can disable it I don't see difference in the site work. This solution consist from several part: 1. In your root folder replace .htaccess file content with next shapshot: <IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI}

Fix openssl encrypt decrypt [PHP]

Image
Warning: openssl_decrypt(): IV passed is only 12 bytes long, cipher expects an IV of precisely 16 bytes, padding with \0 in PATH_FILE on line LINE_N openssl_encrypt(): IV passed is only 12 bytes long, cipher expects an IV of precisely 16 bytes, padding with \0 in PATH_FILE on line LINE_N How to fix the errors Ensure your SALT  only using NUMBER ONLY  and Minimum length of SALT  is 12 . Ensure your PHP version is 7 or above That's how to fix openssl_encrypt() and openssl_decrypt() errors

Membuat PHP argumen dengan '='

Image
Cara Membuat argumen PHP CLI dengan ' = ' ' --= ' Buat file php <?php function arguments($argv) { $_ARG = array(); foreach ($argv as $arg) { if (ereg('--([^=]+)=(.*)',$arg,$reg)) { $_ARG[$reg[1]] = $reg[2]; } elseif(ereg('-([a-zA-Z0-9])',$arg,$reg)) { $_ARG[$reg[1]] = 'true'; } } return $_ARG; } ?> Contoh penggunaan php myscript.php --user=nobody --password=secret -p --access="host=127.0.0.1 port=456" Output Array ( [user] => nobody [password] => secret [p] => true [access] => host=127.0.0.1 port=456 )

Put execution arg into $_GET

PHP CLI <?php if ( $argv ) {     foreach ( $argv as $k => $v )     {         if ( $k == 0 ) continue;         $it = explode ( "=" , $argv [ $i ]);         if (isset( $it [ 1 ])) $_GET [ $it [ 0 ]] = $it [ 1 ];     } } ?>

Menggunakan PHP di termux

Instalasi pkg update -y pkg upgrade -y pkg install php curl wget git -y Contoh Penggunaan PHP (CLI) pada termux buat file php <?php parse_str ( implode ( '&' , array_slice ( $argv , 1 )), $_GET ); ?> Usage/penggunaan php -f namafile.php a=1 b[]=2 b[]=3 //output //$_GET['a'] to '1' and $_GET['b'] to array('2', '3').

[PHP][JS] CryptoJS encrypt decrypt

Image
 CryptoJS encrypt decrypt support PHP 5, PHP 7.x. See the Pen PHP CryptoJS Encrypt Decrypt by dimas lanjaka ( @dimaslanjaka ) on CodePen . Code PHP and details variable [JS] /** * @package https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.js */ var salt = 'salt'; //salt var iv = '1111111111111111'; //pass salt minimum length 12 chars var iterations = '999'; //iterations /** * Get key * @param string passphrase * @param string salt */ function getKey(passphrase, salt) { var key = CryptoJS.PBKDF2(passphrase, salt, { hasher: CryptoJS.algo.SHA256, keySize: 64 / 8, iterations: iterations }); return key; } /** * Encrypt function * @param string passphrase * @param string plainText */ function userJSEncrypt(passphrase, plainText) { var key = getKey(pas

[JS][PHP] Membuat Websocket Javascript

Image
Cara membuat websocket dengan Javascript (JS) dan PHP Update: Simple Websocket Requirements: PHP 5.6+ (minimum)  Websocket merupakan standard baru untuk berkomunikasi, dan cocok untuk aplikasi chat, live server, live listener. Hampir sama dengan AJAX namun perbedaannya ada pada kecepatan dan CPU usage pada device client maupun server. Intinya lebih ringan lah. Websocket ini dapat menerima request apapun dan mendistribusikannya secara instant dari perubahan data sebelumnya. Berikut Cara membuat websocket tanpa NODEJS menggunakan Pure Javascript dan PHP: websocket.js /** websocket steam */ var socket; socket_start(); //start websocket function socket_start() { if (!socket) { //if socket is null console.log('WebSocket Started'); //start server socket = socket_server(); } try { socket.onopen = function (msg) { //console.log('socket initialized'); }; socket.onmessage = function (msg) { var data = JSON.parse(msg.data);

PHP check session has started

Image
PHP >= 5.4.0 , PHP 7 if (session_status() == PHP_SESSION_NONE) { session_start(); } Reference: http://www.php.net/manual/en/function.session-status.php For versions of PHP < 5.4.0 if(session_id() == '') { session_start(); } PHP Check if session has started or not, then session_start()

[JS][PHP] Regexp for matching URL Pattern

Image
Regexp Pattern Untuk mencocokkan semua jenis URL, kode berikut seharusnya berfungsi: <?php $regex = "((https?|ftp)://)?"; // SCHEME $regex .= "([a-z0-9+!*(),;?&=$_.-]+(:[a-z0-9+!*(),;?&=$_.-]+)?@)?"; // User and Pass $regex .= "([a-z0-9\-\.]*)\.(([a-z]{2,4})|([0-9]{1,3}\.([0-9]{1,3})\.([0-9]{1,3})))"; // Host or IP $regex .= "(:[0-9]{2,5})?"; // Port $regex .= "(/([a-z0-9+$_%-]\.?)+)*/?"; // Path $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+/$_.-]*)?"; // GET Query $regex .= "(#[a-z_.-][a-z0-9+$%_.-]*)?"; // Anchor ?> Example: correctly way for matching URL <?php if(preg_match("~^$regex$~i", 'www.example.com/etcetc', $m)) var_dump($m); if(preg_match("~^$regex$~i", 'http://www.example.com/etcetc', $m)) var_dump($m); ?> Pattern diatas bisa digunakan di javascript. Bedanya dengan diatas hanya dari segi vari

Cara install heroku CLI di Termux

Image
Heroku adalah platform cloud sebagai layanan (PaaS) yang mendukung beberapa bahasa pemrograman. Heroku, salah satu platform cloud pertama, telah dikembangkan sejak Juni 2007, ketika hanya mendukung bahasa pemrograman Ruby, tetapi sekarang mendukung Java, Node.js, Scala, Clojure, Python, PHP, dan Go. Untuk alasan ini, Heroku dikatakan sebagai platform polyglot karena memungkinkan pengembang membangun, menjalankan, dan menskala aplikasi dengan cara yang sama di semua bahasa. Heroku diakuisisi oleh Salesforce.com pada 2010 sebesar $ 212 juta. Berikut tutorial untuk install Heroku App dan pre-requirements nya: Instalasi PHP di Termux Instalasi Composer di Termux Instalasi Node.js di Termux Instalasi Heroku App CLI di Termux Tahap 1: update & upgrade apt cd $HOME apt update -y apt upgrade -y Tahap 2: install PHP dan Composer cd $HOME apt install php -y php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" php -r "if (hash_file

Install PHP Web Server on Termux

Image
Install PHP Web Server on Termux Install PHP Web Server on Termux connect the previous article about how to install maria db in termux ( Install MariaDB on Termux ), as a complement we will install the apache web server in termux . due to the differences in termux compared to native Linux, the default ports for web servers like 80 etc cannot be used, so later we will use other ports to run the web server . Install Apache WEb server to install Apache web server is quite easy, just type #apt install Apache2 wait until the process is complete, if it's already running it it's easy enough. all we need to do is type the command. #php -S ip: port -t /path/to/web/file.php where ip is the ip address of the web that we want, the port is the port we want to use as an http port, if by chance port 80 is not used it can use port 80, and /path/to/web/file.php is the directory of the php file that we want to run. suppose I have a file at

Installation Ubuntu On Android Tutorial

Image
Install Ubuntu on an Android phone after struggling finally managed to also install Ubuntu on my beloved android phone. the installation is easy, the hard one is to download it, make it like that.breaking up disconnecting disconnects, once it breaks it can't be resumed , if you want to download , it must be dawn, the speed is still god 😀 * Pffftttt 😂 INSTALLATION Ok, proceed to the first stage, which must be downloaded is the Image file from Ubuntu that has been remastered using X-Window LXDE. 3.5 GB file size is quite something for the internet in Indonesia, files can be downloaded at http://minus.com/mKGww7gIl#2 . the form is a Zip file and if extracted it will produce 3 ubuntu.img, ubuntu.sh, and the ubuntu.sh.

Gmail SMTP error please log in via your web browser

Image
You having problems with gmail smtp server. Like this Gmail SMTP error please log in via your web browser , Then Goggle says: Please log in via your web browser and then try again. 534-5.7.14 Learn more at https://support.google.com/mail/bin/answer.py?answer=787 ?. I know this is an older issue, but I recently had the same problem and was having issues resolving it, despite attempting the DisplayUnlockCaptcha fix. This is how I got it alive. Firstly you must activate less secure apps at https://myaccount.google.com/security?hl=en Enable less secure apps Head over to Account Security Settings ( https://www.google.com/settings/security/lesssecureapps ) and enable "Access for less secure apps", this allows you to use the google smtp for clients other than the official ones. Enable less secure apps Update Google has been so kind as to list all the potential problems and fi