Best of PHP Functions

When working with PHP I have a bunch of go-to functions and things I come back to often. Below, you can find a little list I compiled. Hope someone out there finds them useful. Let’s start with the basics:

To view the php version:

php -v
To view the installed php modules:
php -m

To view phpinfo() information:

php -i

To lint a php file:

php -l file.php

To lint all php files within the cwd:

find . -name "*.php" -print0 | xargs -0 -n1 -P8 php -l

To enter an interactive shell:

php -a

To locate the system’s php.ini files:

php -i | grep "php.ini"

To start a local webserver for the cwd on port 3000 (requires php >= 5.4):

php -S localhost:3000

This next one I use often, I use it as a snippet, outputs a pretty, formatted, legible output when testing or debugging things in PHP:

echo '<pre style="max-height: 400px; overflow-y: scroll; padding: 20px; font-size: 12px; border: 1px dashed #aaa; margin-bottom: 20px; background-color: #ccc;">';
print_r(####);
echo '</pre>';

Quick format a number for legibility:

$num = number_format(9999);
echo $num; // 9,999

Sometimes the server hangs up and needs to be killed, another snippet I use in that instance is:

killall php && php -S localhost:3000

Below is the standard function for connecting to a database:

// Make that connection
$mysqli = mysqli_connect('localhost', 'DATABASE_USER', 'DATABASE_PASS', 'DATABASE_NAME');

// How We check for errors
if (mysqli_connect_errno()) {
	die('Error: ' . mysqli_connect_error());
}

// Make your query
$result = $mysqli->query('SELECT * FROM table');
while ($row = $result->fetch_assoc()) {
	print_r($row['field']);
}

// Close connection after done
$mysqli->close();

To redirect a webpage right away, nitty gritty:

header("Location: https://example.com");

This is a common one, decode JSON:

$string = file_get_contents('https://mb4.in/?rest_route=/wp/v2/posts&per_page=20');
$json = json_decode($string, true);

Now onto some more advanced functions. This function is for formatting time into a human readable, relative timestamp. ie, 2minutes ago, 1 hour ago, etc. Pass it a unix timestamp and it’ll spit out a relative time.

function _ago($tm,$rcs = 0) {
   $cur_tm = time(); $dif = $cur_tm-$tm;
   $pds = array('second','minute','hour','day','week','month','year','decade');
   $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
   for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);

   $no = floor($no); if($no <> 1) $pds[$v] .='s'; $x=sprintf("%d %s ",$no,$pds[$v]);
   if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
   return $x;
}

This next function is for truncating long strings for things like excerpts. Feed it a string, pass a integer character limit, and $break is what the limit looks for, I usually pass a space there. $pad is just what gets appended at the end.

function truncate_by_word($string, $limit, $break = ".", $pad = "...") {
    if (strlen($string) <= $limit) return $string;
    if (false !== ($breakpoint = strpos($string, $break, $limit))) {
        if ($breakpoint < strlen($string) - 1) {
            $string = substr($string, 0, $breakpoint) . $pad;
        }
    }
    return $string;
}

This next one I’ve used on several content/media sites, it generates a read-time estaimate if you feed it the content of the article in string format. It assumes an average read time of 200 words per minute.

function read_time( $content ) {
    $mycontent = $content;
    $word = str_word_count(strip_tags($mycontent));
    $m = floor($word / 200);
    $s = floor($word % 200 / (200 / 60));
    $est = $m . 'm';
    return ( $est < 1 ? 'Quick' : $est );
}

This is a CURL script for grabbing data and displaying it in the browser. Below, we’re grabbing the JSON of one of my Wordpress sites and storing that info in $result as well as printing it out.

$url = 'https://mb4.in/?rest_route=/wp/v2/posts&per_page=20';
$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

$result = curl_exec($curl);
curl_close($curl);

print_r($result);

Send an e-mail. Reference:

$to = 'mb@markobajlovic.com';
$subject = 'Yerr';
$message = 'Galaxies globular star cluster muse about the carbon in our apple pies two ghostly white figures in coveralls and helmets are soflty dancing courage of our questions. Great turbulent clouds Orion\'s sword white dwarf hearts of the stars great turbulent clouds extraordinary claims require extraordinary evidence. Inconspicuous motes of rock and gas extraplanetary a very small stage in a vast cosmic arena courage of our questions shores of the cosmic ocean finite but unbounded and billions upon billions upon billions upon billions upon billions upon billions upon billions.';
$headers = 'From: webmaster@markobajovic.com' . "\r\n" . 'Reply-To: webmaster@markobajovic.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);

A little more advanced e-mailer using PHPMailer:

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'user@example.com';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted

$mail->From = 'from@example.com';
$mail->FromName = 'Mailer';
$mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
$mail->addAddress('ellen@example.com');               // Name is optional
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

I’ll add more over time, just gotta go through my files for more. Hope these help!

ender