Monday, 23 February 2015

PHP: Generate a salt

<?php /**  * This function generates a password salt as a string of x (default = 15) characters  * in the a-zA-Z0-9!@#$%&*? range.  * @param $max integer The number of characters in the string  * @return string  *  */ function generateSalt($max = 15) {         $characterList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*?";         $i = 0;         $salt = "";         while ($i < $max) {    ...

PHP: Generate an alpha-numeric password salt

<?php /**  * This function generates an alpha-numeric password salt (with a default of 32 characters)  * @param $max integer The number of characters in the string  *  */ function generateSalt($max = 32) { $baseStr = time() . rand(0, 1000000) . rand(0, 1000000); $md5Hash = md5($baseStr); if($max < 32){ $md5Hash = substr($md5Hash, 0, $max); } return $md5Hash; } //Usage: /* echo "Salt with 32 characters:\n"; echo generateSalt() . "\n"; echo "Salt with 5 characters:\n"; echo generateSalt(5) . "\n"; */ ?> ...

Javascript: Client-side clock, based on computed time differential between browser and server.

<?php /*** Clock -- beginning of server-side support code ***/ /* Prevent this page from being cached (though some browsers still    cache the page anyway, which is why we use cookies). This is    only important if the cookie is deleted while the page is still    cached (and for ancient browsers that don't know about Cache-Control).    If that's not an issue, you may be able to get away with    "Cache-Control: private" instead. */      header("Pragma: no-cache"); /* Grab the...

PHP: Common mistakes when creating secure PHP websites

Do you remember the last website which was hacked by some kids? What was your first thought, maybe “Phew, that’s not mine”? A hacked website is terrible and the clean-up is a lot of work for the site owner. As a website owner you need to be sure that your site is always secure. It’s important for your business and of course for your site listing in Google. Remember these tips when creating secure PHP websites: MySQL queries and SQL injection attacks If your web page accepts user input a SQL injection might happen if the data isn’t validated...

PHP: Capture the requested URI and Clean up global variables

<?php $requestURI = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']'; echo $requestURI; ?> This snippet is more of an example of how to convert strings to lowercase characters, and then clean them up for use in scripts, etc <?php $_POST["name"] = strtolower(stripslashes(trim(htmlspecialchars($_POST["name"])))); $_POST["message"] = strtolower(stripslashes(trim(htmlspecialchars($_POST["message"])))); ?>...

PHP: Detect browser language

If your website is multilingual, it can be useful to detect the browser language to use this language as the default. The code below will return the language used by the client’s browser. function get_client_language($availableLanguages, $default='en'){  if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {   $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);   foreach ($langs as $value){    $choice=substr($value,0,2);    if(in_array($choice, $availableLanguages)){     return $choice;  ...

PHP: WORDPRESS - Auto convert URL into clickable hyperlink

In wordpress, if you want to auto convert all URLs in your string into clickable hyperlinks, you can actually do it using the built-in function make_clickable(). If you need to do that outside of wordpress, you can refer to the function’s source code at wp-includes/formatting.php:<?phpfunction _make_url_clickable_cb($matches) { $ret = ''; $url = $matches[2]; if ( empty($url) ) return $matches[0]; // removed trailing [.,;:] from URL if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) { $ret = substr($url, -1); $url = substr($url,...

PHP: Find All Links on a Page

Using the DOM, you can easily grab all links from any webpage. Here’s a working example: <?php $html = file_get_contents('http://www.example.com'); $dom = new DOMDocument(); @$dom->loadHTML($html); // grab all the on the page $xpath = new DOMXPath($dom); $hrefs = $xpath->evaluate("/html/body//a"); for ($i = 0; $i < $hrefs->length; $i++) {        $href = $hrefs->item($i);        $url = $href->getAttribute('href');        echo $url.'<br />';...

PHP: Extract keywords from a webpage

The title said it all: A great code snippet to easily extract meta keywords from any webpage. <?php $meta = get_meta_tags('https://thiscode4u.blogspot.com/'); $keywords = $meta['keywords']; // Split keywords $keywords = explode(',', $keywords ); // Trim them $keywords = array_map( 'trim', $keywords ); // Remove empty values $keywords = array_filter( $keywords ); print_r( $keywords ); ?>...

Unzip files with PHP

The following function takes two parameters: The .zip file to unzip, and the destination directory. <?phpfunction unzip_file($file, $destination){  // create object  $zip = new ZipArchive() ;  // open archive  if ($zip->open($file) !== TRUE) {  die ('Could not open archive');  }  // extract contents to destination directory  $zip->extractTo($destination);  // close archive $zip->close();  echo 'Archive extracted to directory';  }?>...

PHP: Generate CSV file from a PHP array

Here is a simple but efficient function to generate a .csv file from a PHP array. The function accept 3 parameters: the data, the csv delimeter (default is a comma) and the csv enclosure (default is a double quote). <?phpfunction generateCsv($data, $delimiter = ',', $enclosure = '"') {  $handle = fopen('php://temp', 'r+');  foreach ($data as $line) {  fputcsv($handle, $line, $delimiter, $enclosure);  }  rewind($handle);  while (!feof($handle)) {  $contents .= fread($handle, 8192);  }  fclose($handle);  return...

PHP: Sanitize database inputs

In order to keep your database safe, you have to be very careful about the input you’re going to save. Here is a super handy function which sanitize inputs to make sure you’re not inserting malicious code into your database. function cleanInput($input) {     $search = array(     '@<script[^>]*?>.*?</script>@si',   // Strip out javascript     '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags     '@<style[^>]*?>.*?</style>@siU', ...

PHP: Some important PHP Snippets

PHP have lots of built-in functions, and most developers know many of them. But a few functions are not very well known, but are super useful. In this article, I have compiled little known but really cool PHP functions. highlight_string() When displaying PHP code on a website, the highlight_string() function can be really helpful: It outputs or returns a syntax highlighted version of the given PHP code using the colors defined in the built-in syntax highlighter for PHP. Usage: <?php highlight_string('<?php phpinfo(); ?>'); ?> str_word_count() This...

Add (th, st, nd, rd, th) to the end of a number

Another useful snippet which will automatically add st, nd, rd or th after a number. <?php function make_ranked($rank) {  $last = substr( $rank, -1 );  $seclast = substr( $rank, -2, -1 );  if( $last > 3 || $last == 0 ) $ext = 'th';  else if( $last == 3 ) $ext = 'rd';  else if( $last == 2 ) $ext = 'nd';  else $ext = 'st';   if( $last == 1 && $seclast == 1) $ext = 'th';  if( $last == 2 && $seclast == 1) $ext = 'th';  if( $last == 3 && $seclast == 1) $ext...

Maintenance mode with PHP

When updating your site, it is generally a good thing to temporarily redirect your users to a “Maintenance” page so they will not see any critical info such as error messages. This is generally done using an .htaccess file, but it can be done easily with PHP: <?php function maintenance($mode = FALSE){     if($mode){         if(basename($_SERVER['SCRIPT_FILENAME']) != 'maintenance.php'){             header("Location: http://example.com/maintenance.php");        ...

Calculate execution time

For debugging purposes, it is a good thing to be able to calculate the execution time of a script. This is exactly what this piece of code can do. <?php //Create a variable for start time $time_start = microtime(true); // Place your PHP/HTML/JavaScript/CSS/Etc. Here //Create a variable for end time $time_end = microtime(true); //Subtract the two times to get seconds $time = $time_end - $time_start; echo 'Script took '.$time.' seconds to execute'; ?> ...

PHP: Automatic password creation

Although I personally prefer leaving users to choose their password themselves, a client recently asked me to generate passwords automatically when a new account is created. The following function is flexible: You can choose the desired length and strength for the password. <?php function generatePassword($length=9, $strength=0) {  $vowels = 'aeuy';  $consonants = 'bdghjmnpqrstvz';  if ($strength >= 1) {   $consonants .= 'BDGHJLMNPQRSTVWXZ';  }  if ($strength >= 2) {   $vowels .= "AEUY";  }  if...

PHP: Highlight specific words in a phrase

Sometimes, for example, when displaying search results, it is a great idea to highlight specific words. This is exactly what the following function can do: <?php function highlight($sString, $aWords) {  if (!is_array ($aWords) || empty ($aWords) || !is_string ($sString)) {   return false;  }  $sWords = implode ('|', $aWords);   return preg_replace ('@\b('.$sWords.')\b@si', '<strong style="background-color:yellow">$1</strong>', $sString); } ?>...

Email PHP errors instead of displaying it

By default, most servers are set to display an error message when an error occured in one of your script. For security reasons, you may want to get an email with the error, instead of displaying it to the public. <?php // Our custom error handler function nettuts_error_handler($number, $message, $file, $line, $vars){ $email = " <p>An error ($number) occurred on line <strong>$line</strong> and in the <strong>file: $file.</strong> <p> $message </p>"; $email .= "<pre>" . print_r($vars,...

Whois query using PHP

If you need to get the whois information for a specific domain, why not using PHP to do it? The following function take a domain name as a parameter, and then display the whois info related to the domain. <?php function whois_query($domain) { // fix the domain name: $domain = strtolower(trim($domain)); $domain = preg_replace('/^http:\/\//i', '', $domain); $domain = preg_replace('/^www\./i', '', $domain); $domain = explode('/', $domain); $domain = trim($domain[0]); // split the TLD from domain name $_domain...

Compress data using gzcompress()

When working with strings, it is not rare that some are very long. Using the gzcompress() function, strings can be compressed. To uncompressed it, simply call the gzuncompress() function as demonstrated below <?php $string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ut elit id mi ultricies adipiscing. Nulla facilisi. Praesent pulvinar, sapien vel feugiat vestibulum, nulla dui pretium orci, non ultricies elit lacus quis ante. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam pretium ullamcorper...

PHP: Get info about your memory usage

In order to optimize your scripts, you may definitely want to know how many amount of RAM they use on your server. This snippet will check memory and then print initial, final and peak usages.<?php echo "Initial: ".memory_get_usage()." bytes \n"; /* prints Initial: 361400 bytes */ // let's use up some memory for ($i = 0; $i < 100000; $i++) {  $array []= md5($i); } // let's remove half of the array for ($i = 0; $i < 100000; $i++) {  unset($array[$i]); } echo "Final: ".memory_get_usage()." bytes \n"; /* prints Final: 885912...

PHP: Display source code of any webpage

Want to be able to display the source code of any webpage, with line numbering? Here is a simple code snippet to do it. Just modify the url on line 2 at your convenience. Or even better, make a pretty function according to your needs. <?php // display source code $lines = file('http://google.com/'); foreach ($lines as $line_num => $line) { // loop thru each line and prepend line numbers echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . " \n"; } ?>...

Thursday, 19 February 2015

PHP select box multiple selections

<form action="<?=$_SERVER['PHP_SELF']?>" method="post"> <select name="test[]" multiple="multiple">  <option value="one">one</option>  <option value="two">two</option>  <option value="three">three</option>  <option value="four">four</option>  <option value="five">five</option>  </select>  <input type="submit" value="Send" />  </form> <?php  $test=$_POST['test'];  if ($test){    ...

Monday, 2 February 2015

PHP Basics

PHP is a scripting language that can be embedded in HTML. Tags and SyntaxPHP commands are embedded into HTML by one of several ways. The preferred method is include the code using the special tags <?php PHP_code_goes_here ?>. A second way is to include the code within a <script language="php"?> - </script> block. Each PHP statement should end with a semicolon. Many statements can be contained in a single block and a single statement can span several blocks: <?phpif ($condition) {   ?>   <b>This...