Posts tagged PHP

PHP in very short

posted on 2016-04-24 11:56

After having eschewed PHP for as long as I could, heres an extremely quick rundown on its syntax so I can read code more easily in the future instead of just guessing wether a linter would accept my changes. This is designed to be an EXTREMELY quick overview, so bear with me. I don't want to do stuff in php either.

So, with that out of the way, a quick look on this dynamic, weakly-typed language.

website "hello world"

        Does PHP work here?

        <?php echo "Yes."; ?>

Instead of <?php echo "Yes."; ?>, also this should work:

<script language="php">
    echo "Yes.";


Prefixing lines with // does work.

variables and arrays

Are all prefixed by $:

$string = "I'm a string."
$number = 1234;
$decimal = 1.5;
$bool = true
$array = array(1, 2, 'three');
$associative_array = array('first_element' => 'one', 'second_entry' => '3');

$associative_array[0] is the same as $associative_array['first_element'] when referencing contents.

Arrays can be multi-dimensional, too.

Scope is usually within the contained block, except they are 'globals' or 'super-globals'.

Examples for super-globals are $_SERVER (contains server information), $_GET and $_POST (contain the respective HTTP requests) and can be used from everywhere. GET parameters can also be found in the $QUERY_STRING var as far as I read.

If you want to reference a variable within a function body, you have to make this possible through a global $varname.

To get all contents of an array outputted: var_dump($arrayname)

constants are used like this:

define("CONST_NAME", "CONST_NAME = 0.003")

Usually php does call-by-value (content is passed) instead of call-by-reference (memory address is passed, if memory changes in the background your value changes, too). To force passing references, prepend a &:


If you want to let one variable reference another's content directly:

$new_var =& $varname

Lastly there also exist static variables. There are not globals, but they don't lose their definition in between runs of a function. Keyword is is used like 'global', and is called static.


  • +=, -=, *= and /= do exist
  • as well as -- and ++, and can be pre- or appended
  • = simply defines variables
  • == is comparison with weak type checking (equality check)
  • === is comparison with strong type checks (`2 === '2' results in false, identity check)
  • and or && and or and || are also present, as well as ! and xor
  • !=, <=, >=, >, < also exist
  • . and .= concatenate strings

control structures

On conditionals:

  • if ($var) { ... } else if ($other_var == true) { ... } else { ... }
  • for one-line checks braces can be omitted
  • ternary operator also exists: condition ? result_if_yes : result_if_no;

switch-case exists, too:

switch($var) {
    case "one":
        // do something
    case "two":
        // do something else
        // do that if nothing else worked

On looping:

  • while ( ... ) { ... }

  • do { .... } while ( ... )

  • break can be used to escape loops, too

  • for ($i=0; $i<10; $i++) { ... }

  • foreach ($arrayname as $value) { ... }; // $value can be used in loop body

  • foreach ($assoc_array as $key => $val) { ... } // $key and $val can be used in loop body


PHP comes with lot of built-in stuff, should you ever need it.

  • math functions
  • date functions
  • string operations
  • printf / formatted printing

Just a quick example how to send mails via PHP:

  • mail('address@host.tld', 'subject', $mailtext)

structuring code

To semantically group your code, you can split it into several files. include and require let you load files (usually with suffix .inc) with further php code into the current file.

'require' is used for function libraries, include for excluding certain parts of your code.

mysql database usage


if (!mysql_connect('hostname', 'user', 'password')) die('connection to database cannot be established');

mysql code:

$my_query1 = 'insert into mytablename (row1, row2) values ('one', 'two');
$my_query2 = 'insert into mytablename (row1, row2) values ('" . $_POST['name'] . "', '". $_POST['surname'] . "')';
if (!mysql_query1($my_query)) die('insertion failed');
if (!mysql_query2($my_query)) die('insertion failed');


Object-orientation is also here... Usually you load your class definitions via require instructions from seperate files.

Class definition including a constructor: (function with same name as the class)

class MyClass {
    var $class_var1 = 'asdf';
    var $class_var2 = '';

    function MyClass(){
        $this->class_var2 = 20;

Calling the constructor:

var $obj_instance = new MyClass);

Referencing variable values inside functions within your class, as shown with the constructor:



class SomeOtherClass extends MyClass {

Anywaw, favor 'composition over inheritance' I heard somewhere...

filesystem access

Open filehandle, do stuff, close filehandle:

$file = fopen("/path/to/file");
echo fget($file, 100);

Instead of fget there also exists fread, for writing use fwrite. Further there is fgetcsv for reading .csv files.

This should do for now. Maybe I will also something similar for javascript in the next posting after having grabbed something to eat.

This blog covers .csv, .htaccess, .pfx, .vmx, /etc/crypttab, /etc/network/interfaces, /etc/sudoers, /proc, 10.04, 14.04, AS, ASA, ControlPanel, DS1054Z, GPT, HWR, Hyper-V, IPSEC, KVM, LSI, LVM, LXC, MBR, MTU, MegaCli, PHP, PKI, R, RAID, S.M.A.R.T., SNMP, SSD, SSL, TLS, TRIM, VEEAM, VMware, VServer, VirtualBox, Virtuozzo, XenServer, acpi, adaptec, algorithm, ansible, apache, apachebench, apple, applet, arcconf, arch, architecture, areca, arping, asa, asdm, autoconf, awk, backup, bandit, bar, bash, benchmarking, binding, bitrate, blackarmor, blockdev, blowfish, bochs, bond, bonding, booknotes, bootable, bsd, btrfs, buffer, c-states, cache, caching, ccl, centos, certificate, certtool, cgdisk, cheatsheet, chrome, chroot, cisco, clamav, cli, clp, clush, cluster, coleslaw, colorscheme, common lisp, configuration management, console, container, containers, controller, cron, cryptsetup, csync2, cu, cups, cygwin, d-states, database, date, db2, dcfldd, dcim, dd, debian, debug, debugger, debugging, decimal, desktop, df, dhclient, dhcp, diff, dig, display manager, dm-crypt, dmesg, dmidecode, dns, docker, dos, drivers, dtrace, dtrace4linux, du, dynamictracing, e2fsck, eBPF, ebook, efi, egrep, emacs, encoding, env, error, ess, esx, esxcli, esxi, ethtool, evil, expect, exportfs, factory reset, factory_reset, factoryreset, fail2ban, fbsd, fdisk, fedora, file, filesystem, find, fio, firewall, firmware, fish, flashrom, forensics, free, freebsd, freedos, fritzbox, fsck, fstrim, ftp, ftps, g-states, gentoo, ghostscript, git, git-filter-branch, github, gitolite, global, gnutls, gradle, grep, grml, grub, grub2, guacamole, hardware, haskell, hdd, hdparm, hellowor, hex, hexdump, history, howto, htop, htpasswd, http, httpd, https, i3, icmp, ifenslave, iftop, iis, imagemagick, imap, imaps, init, innoDB, innodb, inodes, intel, ioncube, ios, iostat, ip, iperf, iphone, ipmi, ipmitool, iproute2, ipsec, iptables, ipv6, irc, irssi, iw, iwconfig, iwlist, iwlwifi, jailbreak, jails, java, javascript, javaws, js, juniper, junit, kali, kde, kemp, kernel, keyremap, kill, kpartx, krypton, lacp, lamp, languages, ldap, ldapsearch, less, leviathan, liero, lightning, links, linux, linuxin3months, lisp, list, livedisk, lmctfy, loadbalancing, locale, log, logrotate, looback, loopback, losetup, lsblk, lsi, lsof, lsusb, lsyncd, luks, lvextend, lvm, lvm2, lvreduce, lxc, lxde, macbook, macro, magento, mailclient, mailing, mailq, manpages, markdown, mbr, mdadm, megacli, micro sd, microsoft, minicom, mkfs, mktemp, mod_pagespeed, mod_proxy, modbus, modprobe, mount, mouse, movement, mpstat, multitasking, myISAM, mysql, mysql 5.7, mysql workbench, mysqlcheck, mysqldump, nagios, nas, nat, nc, netfilter, networking, nfs, nginx, nmap, nocaps, nodejs, numberingsystem, numbers, od, onyx, opcode-cache, openVZ, openlierox, openssl, openvpn, openvswitch, openwrt, oracle linux, org-mode, os, oscilloscope, overview, parallel, parameter expansion, parted, partitioning, passwd, patch, pct, pdf, performance, pfsense, php, php7, phpmyadmin, pi, pidgin, pidstat, pins, pkill, plasma, plesk, plugin, posix, postfix, postfixadmin, postgres, postgresql, poudriere, powershell, preview, profiling, prompt, proxmox, ps, puppet, pv, pveam, pvecm, pvesm, pvresize, python, qemu, qemu-img, qm, qmrestore, quicklisp, quickshare, r, racktables, raid, raspberry pi, raspberrypi, raspbian, rbpi, rdp, redhat, redirect, registry, requirements, resize2fs, rewrite, rewrites, rhel, rigol, roccat, routing, rs0485, rs232, rsync, s-states, s_client, samba, sar, sata, sbcl, scite, scp, screen, scripting, seafile, seagate, security, sed, serial, serial port, setup, sftp, sg300, shell, shopware, shortcuts, showmount, signals, slattach, slip, slow-query-log, smbclient, snmpget, snmpwalk, software RAID, software raid, softwareraid, sophos, spacemacs, spam, specification, speedport, spi, sqlite, squid, ssd, ssh, ssh-add, sshd, ssl, stats, storage, strace, stronswan, su, submodules, subzone, sudo, sudoers, sup, swaks, swap, switch, switching, synaptics, synergy, sysfs, systemd, systemtap, tar, tcpdump, tcsh, tee, telnet, terminal, terminator, testdisk, testing, throughput, tmux, todo, tomcat, top, tput, trafficshaping, ttl, tuning, tunnel, tunneling, typo3, uboot, ubuntu, ubuntu 16.04, udev, uefi, ulimit, uname, unetbootin, unit testing, upstart, uptime, usb, usbstick, utf8, utm, utm 220, ux305, vcs, vgchange, vim, vimdiff, virtualbox, virtualization, visual studio code, vlan, vmstat, vmware, vnc, vncviewer, voltage, vpn, vsphere, vzdump, w, w701, wakeonlan, wargames, web, webdav, weechat, wget, whois, wicd, wifi, windowmanager, windows, wine, wireshark, wpa, wpa_passphrase, wpa_supplicant, x11vnc, x2x, xfce, xfreerdp, xmodem, xterm, xxd, yum, zones, zsh

Unless otherwise credited all material Creative Commons License by sjas