{dev_notes}

MySQL Users

Create a New User CREATE USER `my_app_user`@localhost IDENTIFIED BY ‘my_app_user_passord’; Verify the user exists SELECT DISTINCT User FROM mysql.user; +————-+ | User | +————-+ | root | | my_app_user | +————-+ 2 rows in set (0.002 sec) Get the users hashed password Get the users hashed password in order to grant privileges. Here, the users […]

JavaScript Messages

Alert Alert a message to the browser. alert(‘You are being alerted!’); Confirm Open a confirmation message in the browser. if( confirm(‘Are you sure?’) ) { // Continue… } Console Log Log text or objects to the console. // Text console.log( ‘loggin text here’ ); // Object console.log( myObj ); // Testing for ‘window.console’ prevents errors […]

CSS Fixed Aspect Ratio

Scaling an element while retaining it’s aspect ratio relies on the surprising fact that padding-top percentages are relative to width. This div scales responsively at a 16:9 aspect ratio. HTML <div class=”wrapper”> <div class=”main”> This div scales responsively at a 16:9 aspect ratio. </div> </div> CSS .wrapper { width: 100%; /* whatever width you want […]

PHP Autoloading

In order to instantiate a PHP class defined in a separate file, that file must be included or required into the file currently being executed. Using include_once(), require() or any other variation to pull-in class files will work, but it will not scale well if the app adds features and or libraries. With this pattern […]

PHP Strings

Leading zeroes // Prints a leading zero if the `$number` is a single digit. echo sprintf(‘%02d’, $number); Variables in strings Variable echo “The quick brown fox $my_variable over the lazy dog.\n”; Array echo “The quick brown fox {$my_array[‘animal_action’]} over the lazy dog.\n”; Class property echo “The quick brown fox $my_class->my_text_var over the lazy dog.\n”;

PHP Serialize an Array

If your string contains a “, ‘, :, or ; character in any of the array values the serialization will get corrupted. In order to avoid this, always base64 encode and decode along with serializing. // Safely serialize. $safe_string_to_store = base64_encode(serialize($array)); // Safely unserialize… $array_restored_from_db = unserialize(base64_decode($array));

PHP Convert Bytes to KB, MG, GB, etc.

/** * Convert bytes to proper abbreviation. */ private function format_bytes($bytes, $precision = 2) { $units = array(‘B’, ‘KB’, ‘MB’, ‘GB’, ‘TB’); $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = min($pow, count($units) – 1); $bytes /= pow(1024, $pow); return round($bytes, $precision) . ‘ ‘ . $units[$pow]; }

AWS SDK for PHP

Setup AWS Credentials If it does not already exist, make an .aws directory in the current users home (~/) directory. mkdir ~/.aws Create the credentials file inside the .aws directory: nano ~/.aws/credentials Put the AWS account login credentials into the file: [default] aws_access_key_id = ZKOLJQC7IB5JHEKCWLAV aws_secret_access_key = D92I6o89ks2F3g2PFn24hGSCmoK9FByeDZyhDAES S3 Test App Create the aws_test.php file […]

Composer

Composer is a tool for dependency management in PHP. Declare what libraries a project depends on and Composer will manage (install/update) them for you. Composer is not a package manager like Yum or Apt are. Yes, it deals with “packages” or libraries, but it manages them on a per-project basis, installing them in a directory […]

Linux

Process Forking In multitasking operating systems, processes (running programs) need a way to create new processes, e.g. to run other programs. fork is an operation whereby a process creates a copy of itself which runs concurrently. Forking is typically the only way of launching new processes in Unix-like systems and is required for compliance with […]

LAMP on AWS

Setup an AWS Cloud LAMP stack. Before you begin, be sure that you’ve got access to AWS account Amazon EC2. Make and Launch an EC2 Instance https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html An instance is a virtual server in the AWS Elastic Compute Cloud (EC2). You launch an instance from an Amazon Machine Image (AMI). The AMI provides the operating […]

Install MySQL MariaDB

Update apt packages First use the apt-get alternative apt to update the packages index by typing: sudo apt update Install MariaDB Once the packages list is updated, install MariaDB by running the following command: sudo apt install mariadb-server The MariaDB service will start automatically. Verify MariaDB is running sudo systemctl status mariadb You should see […]

RCS

About Revision Control System (RCS) is an early version control system released in 1982 by Walter F. Tichy at Purdue University. It is a set of UNIX commands that allow multiple users to develop and maintain program code or documents. With RCS, users can make their own revisions of a document, commit changes, and merge […]

PHP and JSON

Decode a JSON File function get_json_file($file_path) { if (file_exists($file_path)) { return json_decode(file_get_contents($file_path)); } return false; }

JavaScript On-Click, Event Listeners and Binding

Delegated An event-delegation approach to on attaches an event handler to only one outer element #my-nav, and the inner element’s event (click on a.item) only bubbles up one level. This also allows you to dynamically add new a.item elements to #my-nav which will immediately bind. $(‘#’ + target_id).on(‘click’, ‘a.item’, function(e) { e.preventDefault(); // Stops the […]

JavaScript AJAX

Posting Data NOTE: POSTing data to a URL which gets rewritten can cause the query parameters to get lost. Ajax request handler function /** * POSTs an ajax request and handles the json response * * Takes a URL, the post-data, and a callback function and subclass name. * An asynchronous request is sent to […]

.gitignore Example File

##### Windows # Windows thumbnail cache files Thumbs.db Thumbs.db:encryptable ehthumbs.db ehthumbs_vista.db # Dump file *.stackdump # Folder config file [Dd]esktop.ini # Recycle Bin used on file shares $RECYCLE.BIN/ # Windows Installer files *.cab *.msi *.msix *.msm *.msp # Windows shortcuts *.lnk ##### Linux *~ # temporary files which can be created if a process still […]

PHP Documentation Standards

DocBloc Examples Single line comment // Double forward slash will comment everything after it. Multi-line comment Multi-line comments must not begin with /** (double asterisk) as the parser might mistake it for a DocBlock. Use /* (single asterisk) instead. /* * This is a comment that is long enough to warrant being stretched over * […]

Python Programming Language

Python Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It can be used for everything from web and software development to scientific applications. Anaconda Anaconda is a free and open-source distribution of the Python and R programming languages for scientific computing. The distribution aims to simplify package management and deployment for Windows, […]

Computer Parts and Structure

The Hardware The Motherboard BIOS RAM The Software Operating System Kernel https://www.geeksforgeeks.org/difference-between-operating-system-and-kernel/ Applications

LDAP

The Lightweight Directory Access Protocol (LDAP) is a vendor-neutral, request-response protocol used to maintain distributed directory info. Active Directory (AD), for example, is the proprietary directory service provided by Microsoft. LDAP allows servers to communicate with Active Directory using queries to find, view, or edit information. Distributed Directories, directory information services, or just Directories are […]

HTTPS, TSL, SSL, and X.509 Certificates

HTTPS Hypertext Transfer Protocol Secure (HTTPS) is an extension of the Hypertext Transfer Protocol (HTTP). HTTPS creates a secure channel over an insecure network, and is widely used on the Internet. HTTPS utilizes the TLS protocol to send data over a network. TLS and SSL Transport Layer Security (TLS) and Secure Sockets Layer (SSL) are […]

Authentication

Authentication vs Authorization Authentication is the act of verifying an identity—making sure a user is who they say they are. Often times when people talk about app security, they confuse the concepts of Authentication and Authorization, or use them interchangeably. But they are actually independent and orthogonal ideas, and understanding the difference between them is […]

OpenSSL

About OpenSSL is an open-source command line tool that is commonly used to generate private keys, create CSRs, install your SSL/TLS certificate, and identify certificate information. OpenSSL is usually included in most Linux distributions. On Windows it is a bit trickier as you need to install a pre-compiled binary to get started. Version and Info […]

Apache HTTP Server

The Apache HTTP Server, colloquially called Apache, is a free and open-source cross-platform web server software. Apache is developed and maintained by an open community of developers under the auspices of the Apache Software Foundation. Virtual Hosts The term Virtual Host refers to the practice of running more than one web site (such as company1.example.com […]

Shells, Terminals and Consoles

More Resources unix.stackexchange.com https://www.thegeekdiary.com/unix-linux-what-is-a-shell-what-are-different-shells/ https://www.tutorialspoint.com/unix/unix-shell.htm

Bash Profile

Bash is the shell, or CLI (Command Language Interpreter) for the Linux operating system. A shell defines the environment in which the user can execute programs, and accepts commands from the keyboard and executes them. User Profiles When you work with the command line frequently you will want to customize the environment. This can mean […]

XAMPP

XAMPP is a completely free, easy to install Apache distribution containing MariaDB, PHP, and Perl. The XAMPP open source package has been set up to be incredibly easy to install and to use. Privileges An account with admin access is required to install and configure XAMPP on Mac. This does not mean running as an […]

Linux Filesystem Hierarchy Standard (FHS)

The Filesystem Hierarchy Standard (FHS) defines the directory structure and directory contents for Linux distributions. It is maintained by the Linux Foundation. Although each Linux distribution has its own quirks, the majority mostly conform to the FHS. The top-level hierarchical directory on a linux file system is called the root (/). Directories directly under root […]

Linux grep Command

About grep is a string and pattern matching utility that displays matching lines found in files using common regular expressions. It can also work with piped output from other commands. The utility was named after the ed command string g/re/p, which translates as “global regular expression search.” Syntax: grep <search pattern> <location> Examples Find a […]

Linux find Command

About The find command returns the file paths of files which match the search criteria. Find searches by file name and file meta data (size, time, owner, etc). To search based on file content, use grep. Syntax: find <options> <starting path> <expression> options attribute will control the behavior and optimization method of the find process. […]

JavaScript Loops

jQuery Arrays var my_array = [52, 97]; $.each(my_array, function(index, value) { console.log(index + “: ” + value); }); Objects var obj = { “flammable”: “inflammable”, “duh”: “no duh” }; $.each(obj, function(key, value) { console.log(key + “: ” + value); });

Linux NIS

The Network Information Service, or NIS, is a client–server directory service protocol for distributing system configuration data such as user and host names between computers on a computer network. Sun Microsystems developed the NIS; the technology is licensed to virtually all other Unix vendors. The Network Information Service (NIS) provides a simple network lookup service […]

Google Chrome Extensions

About Extensions are small event-based software programs that tailor the functionality and behavior of the Google Chrome browser. Extensions are built with HTML, JavaScript, and CSS, and work by listening for events, or browser triggers, such as clicking the extension icon, navigating to a new page, downloading a file, removing a bookmark, or closing a […]

Web Fonts

About Google Fonts Font Display https://fonts.googleapis.com/css?family=Open+Sans:400,400i,700,700i&display=fallback https://developers.google.com/web/updates/2016/02/font-display More Resources https://www.litmus.com/blog/the-ultimate-guide-to-web-fonts/ https://fonts.google.com/

Animate Transitions with CSS

.icon { opacity: 0; transition: opacity 0.3s ease 0s; } .icon.active { opacity: 1; } https://developer.mozilla.org/en-US/docs/Web/CSS/transition-property https://www.w3schools.com/css/css3_transitions.asp

Color SVG with CSS

It’s possible to color embedded SVG graphics with CSS. CSS: svg { width: 2.5rem; height: 2.5rem; } svg path { fill: #000; } Inline SVG: <div class=”user-icon”> <svg version=”1.1″ id=”Layer_1″ xmlns=”http://www.w3.org/2000/svg” xmlns:xlink=”http://www.w3.org/1999/xlink” x=”0px” y=”0px” width=”512px” height=”512px” viewBox=”0 0 512 512″ enable-background=”new 0 0 512 512″ xml:space=”preserve”> <path fill=”#020201″ d=”M454.426,392.582c-5.439-16.32-15.298-32.782-29.839-42.362c-27.979-18.572-60.578-28.479-92.099-39.085 c-7.604-2.664-15.33-5.568-22.279-9.7c-6.204-3.686-8.533-11.246-9.974-17.886c-0.636-3.512-1.026-7.116-1.228-10.661 c22.857-31.267,38.019-82.295,38.019-124.136c0-65.298-36.896-83.495-82.402-83.495c-45.515,0-82.403,18.17-82.403,83.468 c0,43.338,16.255,96.5,40.489,127.383c-0.221,2.438-0.511,4.876-0.95,7.303c-1.444,6.639-3.77,14.058-9.97,17.743 c-6.957,4.133-14.682,6.756-22.287,9.42c-31.521,10.605-64.119,19.957-92.091,38.529c-14.549,9.58-24.403,27.159-29.838,43.479 c-5.597,16.938-7.886,37.917-7.541,54.917h205.958h205.974C462.313,430.5,460.019,409.521,454.426,392.582z”/> </svg> […]

Emoji and Emoticons

¯\_(ツ)_/¯ Mellow, shrug 🍺 (´ー`) (´~`) (╯°□°)╯ Table flip ^(;,;)^ Cthulhu More Resources https://en.wikipedia.org/wiki/List_of_emoticons

Linux chmod Command

The chmod command sets the permissions of files or directories. chmod <options> <permissions> <file name> sudo chmod -R 755 /var/www/my_website There are two ways to represent permissions Octal numbers (the digits 0, 1, 2, 4, 5, and 7) Symbols (alphanumeric characters) Octal numbers Octal permissions notation uses a pattern of three single-digit numbers to define […]

HTML Document Outline

Rules of Thumb Make <h1> the main heading of your page, then use <h2> through <h6>, etc. in a proper hierarchy without skipping levels. <section> can be used with aria-label to signal to a screen reader user where a particular sub-part of an article begins and ends. Otherwise, forget about it, or use another element, […]

HTML Forms

Only values from form elements with a name attribute will be submitted. Likewise, the name attribute becomes the name of the key for the value in the request.

RESTful API Development

The REST (Representational state transfer) model separates the API into logical resources. These resources are manipulated using HTTP requests where the method (GET, POST, PUT, PATCH, DELETE) has specific meaning. Before Development Before creating a public API for a web app, some requirements should be considered: The data model must be relatively stable It can […]

HTML Document

An HTML Document is a text file written for web browsers to read. Absolute Basic HTML5 Document The absolute basic HTML structure needed to define a document: <!DOCTYPE html> <html lang=”en”> <head> <meta charset=”utf-8″> <title>Doc Title</title> </head> <body> <!– Document content goes here. –> </body> </html> Basic HTML5 Document Same as the most basic HTML […]

Apache Virtual Host Setup on Debian Buster

The Apache web server can use virtual hosts (similar to server blocks in Nginx) to encapsulate configuration details and host more than one domain from a single server. Prerequisites You must have a regular, non-root user with sudo privileges configured on the server. A Fully Qualified Domain Name (FQDN) pointing to the server. Running an […]

JavaScript Modules

JavaScript modules are the best way to organize code which will be used in the wild.

JavaScript Script Tags

The HTML script tag is used to identify and run javaScript code. The browser reads each script tag in the order in which it appears in the document. The javascript defined by a script tag is compiled and run immediately after the tag is recognized by the browser. There is no limit to the number […]

WebHooks

Webhooks send real-time data from one application to another whenever a specified event occurs. The “event” is a process which runs inside App A. This can be a login, a purchase, a timed event, anything really. App A holds a list of URLs called “webhook URLs” which point to other applications which have requested to […]

Computer Programming Languages

Programming is the act of defining the operations needed to achieve a desired outcome. A programming language defines the vocabulary and set of grammatical rules which comprise a set of instructions for how to implement a program. A computer programming language specifically instructs a computer or computing device to perform computations or run algorithms. Programming […]

Version Control

Version control is a system that records changes to files over time. Software developers use version control software to maintain current and historical versions of files such as source code, web pages, and documentation. With version control a versioned file can be restored to a previous state. Git Git is a free and open source […]

PHP Debugging

echo ‘<pre>’; print_r($this); echo ‘<pre>’; exit; Dev Bookmark —————- echo ‘PARSING in ‘ . __FILE__ . ‘ on line ‘ . __LINE__; error_log(‘PARSING in ‘ . __FILE__ . ‘ on line ‘ . __LINE__, 0); // LOGGING Class Info —————- echo ‘<pre>$GLOBALS: ‘; if (isset($GLOBALS)) { print_r($GLOBALS);} else { echo ‘$GLOBALS NOT SET’;} echo ‘</pre>’; […]

PHP Programming Language

PHP Version php -v php.ini The PHP configuration file (php.ini) is read when PHP starts up. For the server module versions of PHP, this happens only once when the web server is started. For the CGI and CLI versions, it happens on every invocation. There are a number of possible PHP configuration files, each for […]

Messaging

Messages need a severity level 0 emergencies System is unusable. 1 alert Immediate action is needed. 2 critical Critical conditions. 3 error Error conditions. 4 warning Warning conditions. 5 notification Normal but significant conditions. 6 informational Informational messages only. 7 debugging Debugging messages only.

JavaScript Programming Language

About JavaScript, often abbreviated as JS, and also known as ES6 is the primary programming language for web browsers. JavaScript can update and change both HTML and CSS. JavaScript can calculate, manipulate and validate data. JavaScript can make HTTP requests without refreshing the browser window (AJAX). JavaScript is an object-oriented, prototype-based and text-based scripting language. […]

PHP Configurations

There are multiple versions of php.ini used depending on the sever configurations. php.ini is located in several different directories of an active PHP version. The correct one to use depends on the sever configurations and use case. Find the active PHP directory Search for the current PHP directory: php -i | grep “Loaded Configuration File” […]

Google Chrome Extensions

Extensions APIs Name Description Definition chrome.pageAction Use the chrome.pageAction API to put icons in the main Google Chrome toolbar, to the right of the address bar. Page actions represent actions that can be taken on the current page, but that aren’t applicable to all pages. Page actions appear grayed out when inactive. “page_action”: {…}

MacOS Setup

System Settings Hot Corners Goto System Preferences > Mission Control > Hot Corners. In the top-left, set to Mission Control. In the top-right, set to Application Windows. Click OK. Format the Time Click on the time in the upper-right hand corner of the desktop. Click Open Date and Time Preferences…. Go to the Clock tab. […]

Linux Commands

About Commands Parameters and Flags A single hyphen (-) can be followed by multiple single-character flags. A double hyphen (–) prefixes a single, multi-character option. Consider this example: tar -czf In this example, -czf specifies three single-character flags: c, z, and f. Now consider another example: tar –exclude In this case, –exclude specifies a single, […]

WordPress Enqueue CSS and JS

https://developer.wordpress.org/themes/basics/including-css-javascript/ wp_enqueue_style() Enqueue styles with wp_enqueue_style(): wp_enqueue_style( $handle, $src, $deps, $ver, $media ); Parameter Description $handle (string) (Required) Name of the stylesheet. Should be unique. $src (string) (Optional) Full URL of the stylesheet, or path of the stylesheet relative to the WordPress root directory. Default value: “ $deps (string[]) (Optional) An array of registered stylesheet […]

Linux Symlinks and Hardlinks

┌── ln(1) link, ln — make links │ ┌── Create a symbolic link (instead of a hard link). │ │ ┌── the optional path to the intended symlink │ │ │ if omitted, symlink is in . named as destination │ │ │ can use . or ~ or other relative paths │ │ ┌─────┴────────┐ […]

HTML Semantics

Main Site Nav The main site navigation menu can be put anywhere on a page, it just needs to be wrapped with the nav tag. It should never be put inside a main tag, unless the navigation is specific to that page. main elements are specific to a page, while headers and footers are generally […]

Daemons

A daemon is a long-running (runs continuously as long as the system is running) background process that answers requests for services. Daemons don’t have a direct user interface. The term originated with Unix, but most operating systems use daemons in some form or another. In Unix, the names of daemons conventionally end in “d”. Some […]

Linux CRON Jobs

Cron cron is a system daemon which manages time-based job scheduling on Linux operating systems. The app runs every minute and inspects a set of predefined directories for tasks which need to be run at given intervals. A cron job can be scheduled to run by on the minute, hour, day of the month, month, […]

SVN Apache Subversion

Apache Subversion is a software versioning and revision control system distributed as open source under the Apache License. Software developers use Subversion to maintain current and historical versions of files such as source code, web pages, and documentation. https://subversion.apache.org/ http://svnbook.red-bean.com/ http://maverick.inria.fr/~Xavier.Decoret/resources/svn/ Common Commands Checkout a remote repo Checkout the my_repo SVN repo starting from its […]

Perl Programming Language

About Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more. Using Perl In order to use Perl on a machine, it must be installed. The Perl installation basically consists of the Perl compiler, […]

Regular Expressions

Regular expressions are strings called patterns with very particular syntax and meaning. Patterns are used to determine if some other string, called the target, has (or doesn’t have) the characteristics specified by the pattern. https://www.cs.wcupa.edu/rkline/index/regular-expressions.html

WordPress Theme Development

WordPress themes are more than just the front-end HTML and styles of the website, a theme enables and defines specific WordPress features and controls the display of everything. Common features which make WordPress what it is like Widgets and Menus are not enabled by default and require the theme to setup and configure them. New […]

WordPress Widgets and Sidebars

Widgets In WordPress widgets are blocks of content that admin users can add to their site’s widget areas also known as sidebars. WordPress widgets were created to provide an easy way for WordPress admin users to control the design and content of their site without having to code. Most WordPress themes support widgets. Sidebars In […]

WordPress

About At it’s core WordPress consists of the WordPress Admin Area for site admin users to configure things, and a public front-end UI (the website). WordPress uses software packages called themes to control the look and to extend the core functionality. Different themes can be used to provide different configurations, but only one theme can […]

WordPress Menus

A navigation menu is a list of links to important pages of a website. Navigation menus give your site structure and help visitors find what they’re looking for. Menu Locations In WordPress Navigation Menus or just Menus are a theme feature which allow admin users of a WP site to create navigation menus and then […]

PHP Classes

Instantiate a class and then call a method: $my_class = new my_class(); $my_value = $my_class->get_value(); Instantiate a class and call a method in one line (PHP 5.4+): $my_value = (new my_class)->get_value();

WordPress Initial Setup

Initial configurations Settings Goto Settings > General. Verify the Site Title and Tagline. If changes are made click the Save Changes button. Goto Settings > Discussion. Under Default post settings uncheck Allow people to submit comments on new posts. Under Other comment settings check Users must be registered and logged in to comment. Under Before […]

Form and Input Security

Web Security Issues XSS – Cross-Site Scripting Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications. XSS enables attackers to inject client-side script into Web pages viewed by other users. The media has helped make cross-site scripting (XSS) a familiar term, and the attention is deserved. It is one […]

Sublime Text

Sublime Text 3 is a very simple yet powerfully extensible text editor. The basic app is only 16 MB, but the real power comes from installing packages which extend functionality. Documentation is at http://www.sublimetext.com/docs/3/ and http://docs.sublimetext.info/en/latest/index.html. Setup Sublime Text 3 Download Sublime Download Sublime Text 3 from sublimetext.com. Install the app on your OS. The […]

MySQL, MariaDB and SQL

Common datatypes Types Description Default Value BLOB BLOB (Binary Large OBject) and TEXT hold large values. BLOB values are treated as binary strings (byte strings) and can hold anything from text to file data (images, PDF’s, etc.). TEXT strings are treated as non-binary character strings. BLOB and TEXT columns cannot have DEFAULT values. Sizes: TINYBLOB […]

PHP Date and Time

PHP date format parameters PHP global time zones PHP American time zones Datetime Get the current UTC Date-Time $utc_date_and_time = gmdate(“Y-m-d H:i:s”); Convert to UTC /* * @param string $local_datetime A datetime string. * @param string $local_time_zone A timezone identifier, like `UTC`, `Africa/Lagos`, * etc. The list of valid identifiers is available in * the […]

PHP Send Email

Sending email messages is a common task for web applications. You can use the built-in PHP mail() function to dynamically create and send email messages to one or more recipients. The mail() function is a part of the PHP core but to use it you must have a mail server setup on your domain. Mail […]

PHP Incrementing Values

$i = 1; $i++; echo $i; // 2 $i = 1; $i += 1; echo $i; // 2 $s = ‘s’; $s++; echo $s; // t $s = ‘s’; $s += 1; echo $s; // 1

PHP Truthy, Falsey

A falsey value is considered false when encountered in a Boolean context. A truthy value is considered true when encountered in a Boolean context. The idea of truthy and falsey values allow comparison between what would otherwise be two incomparable data types in a programming language. For instance, in PHP you can compare a number […]

PHP info

Create a default PHP info file to test PHP configurations. sudo nano /var/www/html/info.php Add this content to the files and save: <?php phpinfo❨❩; ?> Visit the URL: http://mydomain.com/info.php Remove the info file after your done to ensure security: sudo rm /var/www/html/info.php

PHP cURL

Working with cURL requires the use of these methods: curl_init(); // Initialize a cURL session. curl_setopt(); // Changes the cURL session behavior with options. curl_exec❨❩; // Executes the started cURL session. curl_close(); // Closes the cURL session and deletes the variable made by curl_init();

PHP Sessions

Test-for and start a session The $_SESSION variable cannot be accessed without first starting a session. PHP will throw a warning if a session exists and you call session_start(). if (!session_id()) { session_start(); }

PHP MySQLi

DB Connect // Get the database credentials. $db_creds = [ ‘host’ => ‘127.0.0.1’, ‘username’ => ‘root’, ‘password’ => ‘root’, ‘database’ => ‘my_database’ ]; // Connect to the database. $db_handle = new mysqli( $db_creds[‘host’], $db_creds[‘username’], $db_creds[‘password’], $db_creds[‘database’] ); // Check for a connection. if ($db_handle->connect_errno) { echo ‘The MySQL query failed.’ . $db_handle->connect_error; } Select if […]

Git

About Git is a free and open source distributed version control system – which just means that when you do a git clone (+url of your repository) what you are actually getting is a complete copy of your entire history of that project. This means all your commits! Woot! Git has a staging area. This […]

HTML Elements

HTML tags mark the beginning and end of an HTML element. Elements may contain attributes. Everything is a tag HTML elements or tags are used to define the content and meaning of an HTML document. Tags have meaning HTML elements represent things; that is, they have intrinsic meaning, also known as semantics. Normal tags wrap […]

PHP Settings php.ini

Resource Limits ;;;;;;;;;;;;;;;;;;; ; Resource Limits ; ;;;;;;;;;;;;;;;;;;; max_execution_time = 240 ; Maximum execution time of each script, in seconds max_input_time = 120 ; Maximum amount of time each script may spend parsing request data memory_limit = 128M ; Maximum amount of memory a script may consume (8MB) max_input_vars = 3000 ; Maximum number of […]

PHP Files and Directories

Include a file Include local files using the include() or require() methods. Both methods are the same except for the fact that require() produces a fatal error if it fails while include() only produces a warning. include(‘../my_file.php’); Get the current file path // Get the absolute path to the directory containing the current working file. […]

PHP Validation

Validation means testing a variable for specific requirements. If the requirements are met, validation passes, if not, validation fails. The value being tested is never altered. Validation is used primarily when evaluating input parameters from GET or POST. PHP has provided a number of methods to work with input parameters. Alphanumeric ctype_alnum() will return false […]

PHP Starts and Ends With

/** * Returns `true` if the string (haystack) starts with the search-string (needle). * See: https://stackoverflow.com/questions/834303/startswith-and-endswith-functions-in-php */ function starts_with($haystack, $needle){ return substr($haystack, 0, strlen($needle)) === $needle; } // Tests. $string = ‘Test test test this is a test.’; echo (starts_with($string, ’27’) ? 1 : 0); // 0 echo (starts_with($string, ‘Rest’) ? 1 : 0); // […]

PHP Constants

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script. Do not use the define() method for declaring a constant as it does not work within classes. Constants defined in a class are READ-ONLY and STATIC (shared by all instances of […]

PHP Random String Generator

Run this code on 3v4l.org /** * Generate a random string, using a cryptographically secure * pseudorandom number generator (random_int) * * per https://stackoverflow.com/a/31107425 */ function get_random_string($length = 16, $keyspace = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’) { $str = ”; $max = mb_strlen($keyspace, ‘8bit’) – 1; for ($i = 0; $i < $length; ++$i) { $str .= $keyspace[random_int(0, $max)]; […]

PHP Variables

Variables are named storage spaces for data types. They act as identifiers to access memory locations. A PHP variable name must start with a $ sign and consist only of alphanumeric characters and underscores, are case sensitive. Variables are assigned with the = operator, with the variable name on the left-hand side and the value […]

PHP Loops

Loop Over New Lines foreach(preg_split(“/((\r?\n)|(\r\n?))/”, $subject) as $line){ // do stuff with $line } For Loops for ($x = 0; $x <= 100; $x+=10) { echo “loop: $x <br>”; } While Loops $x = 1; while ($x <= 5) { echo “loop: $x <br>”; $x++; }

PHP HTML and DOM Parsing

DOMDocument PHP core comes with a very handy HTML parser called DOMDocument. Parse html DOM with DOMDocument // Create a new DOMDocument object. $dom = new DOMDocument; // Load the HTML page into the object. $dom->loadHTML($html); // Once the HTML is loaded into the object, access nodes and child elements: // Get an element by […]

PHP URL

Get the current URL $url = ‘http’ . (isset($_SERVER[‘HTTPS’]) ? ‘s’ : ” ) . ‘://’ . “{$_SERVER[‘HTTP_HOST’]}{$_SERVER[‘REQUEST_URI’]}”; Get the parts of a URL $url = ‘http://username:password@hostname:9090/path?arg=value#anchor’; echo parse_url($url, PHP_URL_SCHEME); // Returns “http” echo parse_url($url, PHP_URL_USER); // Returns “username” echo parse_url($url, PHP_URL_PASS); // Returns “password” echo parse_url($url, PHP_URL_HOST); // Returns “hostname” echo parse_url($url, PHP_URL_PORT); // […]

PHP Date and Time

Unix Timestamp The Unix Timestamp (Unix time, Unix epoch, or POSIX time) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT). # Get the current timestamp in seconds. $current_time = time(); # Get the current timestamp in microseconds. $current_microtime = microtime(true); Convert Seconds to Readable Time function get_time_from_seconds( $seconds ) […]

PHP Error Handling

Error Reporting // Report all PHP errors. ini_set(‘display_errors’, 1); ini_set(‘display_startup_errors’, 1); error_reporting(E_ALL); This alone doesn’t make PHP show parse errors. The only way to show parse errors is to set display_errors = on in the php.ini file. trigger_error() trigger_error() can be used to trigger a PHP notice, warning, or fatal error. By default a NOTICE […]

PHP Print and Echo

// FAILS: return echo implode(“\n”, $html); // GOOD: return print implode(“\n”, $html);