PHP

PHP

Regex Reverse Match And Replace All But Specified Characters

Overview

We can use regular expressions to specify a list characters we want to either strip out of a string or replace them with other characters however this article is aimed more on how to do a regex reverse match and replace (also knows as a negative replace) where we specify the characters we DO NOT want to be stripped out which can be very useful for sanitising and cleaning out strings and prevent MySQL injections or cross-site scripting attacks. In other words we replace everything but the string specified.

Sounds simple enough yet I found it ever so difficult on how to perform this which is why I am posting it here to save others the time.

Regex Reverse Match

The below examples use the regular expression pattern /[^a-zA-Z0-9\s]/ which basically is just specifying a list of characters (being upper and lower case letters, numbers and spaces). But the big difference is the ^ (caret symbol) is inside the square brackets which tells the regular expression that it is a negative search. ie, match and strip all but the ones listed.

Remember… if we wanted to remove the list of characters specified by the expression’s pattern, then we simply exclude the ^ which mean the resulting pattern to include a list of characters would look like so: /[a-zA-Z0-9]/.

Secondly the second parameter is and empty string which will tell the function to replace the string with nothing.

Note! that if the ^ (caret) was outside the square brackets it would then specify matches at the beginning of a sentence. Just as a $ (dollar symbol) at the end of the sentence would specify matches at the end of the sentence. In this case, the ^ (caret) is inside which denotes an exclusion of characters.

PHP Reverse Replace

<?php

/* our string we will be working on */
$str = "A string - with, awful characters$@!.";
/* use php's preg_replace to execute the regular expression and echo the result */
echo preg_replace( '/[^a-zA-Z0-9\s]/', '', $str );
/* the output from the above will be "A string with awful characters" */

?>

Javascript Reverse Replace

<script type="text/javascript">

/* our string we will be working on */
var str = 'A string - with, awful characters$@!.';
/* use  javascript's replace() function to execute the regular expression and then store the result */
var str = str.replace(/[^a-zA-Z0-9\s]/g,'');
/* the variable `str` from the above will be "A string with awful characters" - all nasty characters are removed */

</script>

Validate IP Address PHP And Javascript Examples

Overview

Below is a similar post to my other post on validate email addresses example except in this post we will validate an IP address instead of an email address. I have also provided simple and straight forward code snippets for Javascript and PHP. It uses a regular expression to test if the string passed to is a check the IP address is valid.

Validate IP Address

Validate IP Address

Validate IP Address PHP And Javascript Examples

The two types of IP Address Validation we will cover are:

I have included both PHP and Javascript Email Validation Examples. It works perfectly for me and hope it will save you hours of time trying to find it out for yourself. Please let me know in the comments if you have any issues.

Validate IP Address In PHP With preg_match()

<?php

/* The IP to test (this IP is valid) */
$str = "100.150.200.250";
/* use php's preg_match to execute the regular expression and store the result - which is either `0` for no match or `1` for a match */
$bValidIP = preg_match( '/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/', $str );

?>

Validate IP Address In Javascript With test()

<script type="text/javascript">

/* The IP to test (this IP is valid) */
var str = "100.150.200.250";
/* The regular expression pattern */
var pattern = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/g;
/* use  javascript's test() function to execute the regular expression and then store the result - which is either true or false */
var bValidIP = pattern.test(str);

</script>

Conclusion

Not much explaining I can do. Essentially there are two methods to validate IP address. First is validate IP in PHP and the second is how to validate IP address in javascript.

PHP Implode Array Key Value – Array Keys To String

Overview

In this tutorial, I will show how you can quickly and easily convert array keys, into a string. The method I use will convert array key values into an array without using foreach() function.

The idea of this code snippet will allow you to convert this:

<?php

$array = (
    'John' => 'John is a common name',
    'Mark' => 'Mark is eating a sandwich',
    'Sarah' => 'Sarah does not like Mondays',
);

Into this:

<?php

$names = 'John, Mark, Sarah';

PHP Implode Array Key Value – Array Keys To String

In PHP there is a great function for converting a PHP Array into a string (and visa versa) using the function implode(). These functions work well on the values of the array, however we are trying to convert he array keys. Luckily in PHP there is a function called array_keys() which will return a list of array keys from the array. Combining these two functions, we can easily convert the keys of an array into a string. Using php implode array key value will easily convert your array’s keys into a string.

Note that as this function converts the array keys into a string rather than the array values. As such, the array passed to the calling function should be an associative array.

The PHP Function

Here is the function used to convert the array keys into a string. If you want to learn how the function works, then view the explanation here.

<?php

// our simple yet effective implode array key function
function implodeArrayKeys($array) {
	return implode(", ",array_keys($array));
}

?>

How the above function works

This is the long winded version of this function explaining how the above implode array keys function works. You should use the above function as the function below is more for information purposes.

<?php

function implodeArrayKeys($array)
{
	// first we get the array keys using array_keys() PHP function
	$keys = array_keys($vars);

	// now join the keys into a string and separate using a comma
	$string = implode(", ",$keys);

	// and return the result
	return $string;
}

?>

And voila, it’s as easy as that.

Convert String To Array And Array To String PHP

Overview

Arrays are used very often in PHP and at times you will need to convert a string into an array as well as converting an array into a string. PHP has two functions to achieve this and I will give an example of each one.

Simple use cases are splitting a string of names into an array containing all the names. Also converting an array of names, into a string which can be displayed to the user.

Convert String To Array And Array To String PHP

I will show you two ways to convert a string into an array, and a method to convert an array into a string.

  • explode()convert string to an array using a single delimiter
  • preg_split()convert string to an array using regex (more flexible and powerful)
  • implode()convert array to a string

explode()

Convert string to array using explode().

Converts a string into an array. String is split by each delimiter specified by the first parameter passed to the function. If you need to split a string into an array split by a single delimiter, then this method is ideal. If you need to use many delimiters or to split the string using a regex delimiter, then see preg_split() example below.

<?php

/* our string we are going to split (explode()) into an array */
$str = "Split:This:Into:An:Array:Please";
/* $arr will now be an array with the value of array("Split","This","Into","An","Array","Please"); */
$arr = explode(":",$str);

?>

preg_split()

Convert string to array using preg_split().

If you need to split a string into an array using regex, then take a look at the example below. It gives you the ability to convert a string into an array, however it also brings the power and flexibility of regex.

Using preg_split() allows you to split up a string at multiple delimiters. Take the string Tim, Sarah,Albert and Sue. In this case, we need to split the string up by “,” as well as ” and “.

<?php

/* our string we are going to split (preg_split()) into an array */
$str = "Tim, Sarah,Albert and Sue";

/* $arr will now be an array with the value of array("Tim", "Sarah", "Albert", "Sue"); */
$names = preg_split('/(,{1}[\s]?|\sand\s)+/', $str);

?>

implode()

Convert array to string using implode().

Convert an array into a string. Each Element of the array is glued together by the delimiter specified by the first parameter. For example, this is useful if you have an array of names that you want to convert to string to be displayed on a webpage.

<?php

/* our array we are going to glue together (implode()) into a string */
$arr = array("Glue","This","Into","A","String","Please");
/* $str will now be a string with the value "Glue This Into A String Please" */
$str = implode(" ",$arr); /* Note we glued it together with a space */

?>

And that is all there is to it.

Conclusion

While explode offers simple ways to convert string to an array, it lacks the power of preg_split() which allows you to specify the delimiter as a regex. However preg_split has more of an performance overhead as it has to process the regex.

PHP Array Push Pop Shift and Unshift

Overview

Many if not all PHP developers will come across arrays in their day to day programming. Arrays allow you to store ‘rows’ or ‘blocks’ of information. PHP comes with plenty functions that can be used to create, manage and simplify the use of arrays. I will focus on four functions that allow you to add and remove elements from an array. I will also show you how to access the first and last elements of an array using these functions.

PHP Array Functions

PHP Array Push Pop Shift and Unshift

For each of the four functions, I will give a short overview of what each one is used for as well as alternative functions that can be used to achieve the same result. Remember that each of the four functions will reset the internal pointer for the array when used causing your ‘foreach’ function to start at the beginning of the array.

PHP Push Array – array_push()

Add one or more elements onto the end of array. Returns the number of elements in the new array.

Standard method using array_push();

// create our array with 1 element
$arr = array("one");
// $count will be 3 and $arr will now be array("one","two","three");
$count = array_push($arr,"two","three");

Alternate method using $arr[]

tip! Using this method can be faster than using array_push since there is no overhead of calling an actual function.

// create our array with 1 element
$arr = array("one");
// $arr will now be array("one","two");
$arr[] = "two";
// $arr will now be array("one","two","three");
$arr[] = "three";
// $count will be 3
$count = count($arr);

Alternate method using array_merge();

// create our array with 1 element
$arr = array("one");
// alternate method using array_merge()
$arr = array_merge($arr,array("two","three")); // $arr will now be array("one","two","three");
$count = count($arr); // $count will be 3

PHP Pop Array – array_pop()

Removes and returns the value of the last element of an array. Returns NULL if array is empty or not set.

Standard method using array_pop();

// create our array with 3 elements
$arr = array("one","two","three");
// $value will be "three" and array's value will now be array("one","two");
$value = array_pop($arr);

Alternate method using array_slice();

// create our array with 3 elements
$arr = array("one","two","three");
// alternative method using array_slice()
$value = $arr[count($arr)-1]; // $value will no be "three"
$arr = array_slice($arr, 0, -1);   // $arr will now be array("one","two");

PHP Shift Array – array_shift()

Removes and returns the value of the first element of an array. Returns NULL if array is empty or not set.

Standard method using array_shift();

// create our array with 3 elements
$arr = array("one","two","three");
// $value will be "one" and array's value will now be array("two","three");
$value = array_shift($arr);

Alternate method using array_slice();

// create our array with 3 elements
$arr = array("one","two","three");
$value = $arr[0]; // $value will now be "one"
$arr = array_slice($arr, 1); // array's value will now be array("two","three");

PHP Unshift Array – array_unshift()

Add one or more elements to the beginning of an array. Returns the number of elements in the new array.

Standard method using array_unshift();

// create our array with 3 elements
$arr = array("three","four","five");
// $count will now be 5 and array will hold one - five
$count = array_unshift($arr,"one","two");

Alternate method using array_slice();

// create our array with 3 elements
$arr = array("three","four","five");
// $count will now be 5 and array will hold one - five
$arr = array_merge(array("one","two"),$arr);
$count = count($arr);

PHP stdin Command Line Input From User

Overview

In C++ it is called cin, and in perl it is $variable = <STDIN> however what is the equivalent of cin and STDIN for PHP?

In PHP is is similar to perl in that we use php’s I/O stream called stdin. The syntax looks something like this:

php://stdin

Reading User Input From Command Line

To read a user’s input from the command line we use stdin which as I mentioned before, is an I/O stream. Since stdin is an input stream, it can only be opened as read-only. There are two other I/O streams which are stdout and stderr and as they are output stream, they can only be opened in write mode. Opening stdin and reading from it won’t be that difficult and hopefully the example below will show how useful and easy it can be to capture a users input from the command line or other information from stdin and display it back to the user.

PHP stdin Command Line Input From User

The below script will capture a user’s name and then display it to the user.

<?php

// show them a message to enter their name
echo "Tell us your name: " . PHP_EOL;

// the script will wait here until the user has entered something and hit ENTER
$name = read_stdin();

// This will display the thank you message including their name they entered.
echo "Thank you $name. Welcome to my site" . PHP_EOL;

// our function to read from the command line
function read_stdin()
{
	$fr=fopen("php://stdin","r");	// open our file pointer to read from stdin
	$input = fgets($fr,128);	// read a maximum of 128 characters
	$input = rtrim($input);		// trim any trailing spaces.
	fclose ($fr);			// close the file handle
	return $input;			// return the text entered
}

?>

Final Note

Reading from the command line can be useful for creating php scripts that run from the command line. It can be used to capture the user’s decisions such as specifying the install location or setting up config preferences for a new website.

PHP Increase Memory Limit Using Htaccess, Apache Or PHP

Overview

Most of us have come across this error: “Fatal error: Allowed memory size of xxxxxx bytes exhausted (tried to allocate yyy bytes) in ….” in the php error log files.

In php, running out of memory in usually a sign that your php script is not too well written or has a bug or two in it. It could also be caused by script that have to process large amounts of data at once. Sometime even well designed php scripts still require more memory than usual especially if it is handling large amounts of data or when trying to read large files into memory.

PHP Increase Memory Limit Using Htaccess, Apache Or PHP Script

Luckily in php, increasing the memory limit is an easy task to do and can be done in a number of ways. Below I will show you how to increase (or even decrease) the memory limit using either htaccess, apache and even inside the php script itself.

Setting PHP Memory Limit inside PHP Script

Inside your php script that requires the increase in memory, you can add the following line which increases the memory limit just for that page. So putting this at the top of the script can help you handle larger amounts of data.

<?php

// note that memory_limit is case sensitive!
ini_set('memory_limit','64M');

// rest of your code follows

Setting PHP Memory Limit in .htaccess

Setting a memory limit in .htaccess is also straight forward. Add a line into your .htaccess file. Note that this will affect any php files within that folder and subfolders. You won’t need to restart apache when updating the htaccess. Be careful as any typo’s in the htaccess file will prevent the website from loading correctly.

php_value memory_limit 64M

Setting PHP Memory Limit in php.ini config file

If you want to set the memory limit within PHP itself, then edit the php.ini file which is usually found under /etc/php/apache2/php.ini under Debian and find the line shown below and change it to whatever you need. This will affect all php scripts running under your server so be careful with this value.
Note: you will have to restart apache for this change to take effect

memory_limit = 64M

Setting PHP Memory Limit in Apache

Inside apache, find the virtual host that needs the increase in memory limit and add the line as shown below in italics.
Note: you will have to restart apache for this change to take effect

<VirtualHost *:80>

# apache settings for virtual host

php_value memory_limit 64M

# other settings etc. follow as usual.

</VirtualHost>

Conclusion

Needing more memory for a php script can be frustrating, luckily you are able to increase the php memory limit for your website or just a specific subfolder of your site. It is easy to increase the limit using either htaccess, apache or within the php script.

Override The Default PHP Execution Timeout Limit

Overview

In many programming language there is always a chance that your code will enter an infinite loop and get stuck for a long time. There is also a chance that a script may be processing large and complex dataset which causes it consume large amounts of server resources for a long time. Which affects other programs or websites that are running on the same server. In most cases this would be useful, however sometimes you will need to allow the script to complete even if it takes a long time and consumes a chunk of a server’s resources.

If this is the case, you can override the default PHP execution limit, which is generally around 30 seconds and set it to a much higher (or lower) timeout limit. You can even remove the time limit although this isn’t generally recommended. As you will see, PHP has introduced a PHP Execution Timeout which basically limits the amount of time a PHP script is allowed run until it is cancelled by the PHP server.

Override The Default PHP Execution Timeout Limit

I will show you a number of ways to extend the maximum execution time of a PHP script.

 

Setting the PHP execution limit in php.ini

Edit your php.ini file which is usually under ‘/etc/php5/apache2/php.ini’ in Debian Linux and scroll to the line which has the max_execution_time option. Want to remote the time limit? Setting the limit to 0 (zero) will remove the PHP execution timeout and possibly cause the PHP script to run forever.

max_execution_time = 600

 

Setting the PHP execution timeout using set_time_limit()

You can override the PHP execution time directly in a PHP script by using the set_time_limit() function. Setting the limit to 0 (zero) will remove the PHP execution timeout and possibly cause the PHP script to run forever.

<?php

// set the PHP timelimit to 10 minutes
set_time_limit(600);

// rest of your code will be able to run for the next 10 minutes before timing out

?>

 

Changing the PHP execution time using ini_set()

Just as above, you can also override the PHP timeout limit in a PHP script by using the PHP ini_set() function. Setting the limit to 0 (zero) will remove the PHP execution timeout and possibly cause the PHP script to run forever.

<?php

// set the PHP timelimit to 10 minutes
ini_set('max_execution_time',600);

// rest of your code will be able to run for the next 10 minutes before timing out

?>

 

Override PHP execution time in .htaccess file

Overriding the default PHP execution timeout can also be done inside an .htaccess file by using the php_value directive and using it to set the value of max_execution_time. Setting the limit to 0 (zero) will remove the PHP execution timeout and possibly cause the PHP script to run forever.

# set timeout to 10 minutes
php_value max_execution_time 600

Final Words

Increasing the timeout limit can be very useful but should be used with caution. Removing the time limit can be done by setting the limit to 0, but again, use with caution. Timeout limits are there for a reason and should only be used when other options are not available or viable.

PHP Ping Script To Check Remote Server Or Website

Overview

Ever needed a quick php code snippet to perform a ping to check if a remote server or website is up? Then see the code below which contains two variations of a ping function that will show you how to ping from php using a PHP Ping Script. The first version uses exec() and the second version uses fsockopen().

PHP Ping Website

The advantage of the second function is that it can connect to a specified port which allows you to also check if a port or service is available on your server. Great if you want to check if your Website is still running on port 80 or if your MySQL service is still responding.

PHP Ping Script To Check Remote Server Or Website

A PHP Ping Script can be very useful to check if your website or server is up before attempting to connect to it resulting in you having to wait for ages while the program or script to eventually timeout.

Our first version using PHP exec() to ping the server.

First example is a simple example that will send a standard ping.

<?php

/* our simple php ping function */
function ping($host)
{
	exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($host)), $res, $rval);
	return $rval === 0;
}

/* check if the host is up
	$host can also be an ip address */
$host = 'www.example.com';
$up = ping($host);

/* optionally display either a red or green image to signify the server status */
echo '<img src="'.($up ? 'on' : 'off').'.jpg" alt="'.($up ? 'up' : 'down').'" />';

?>

Our alternate PHP Ping Script using fsockopen().

Our second example is by far more useful as it accepts a port as the parameter. This allows us to check specific services on the server. Using port 80 in most cases will test the website, or 3306 will try connect to a mysql server.

<?php

function ping($host,$port=80,$timeout=6)
{
	$fsock = fsockopen($host, $port, $errno, $errstr, $timeout);
	if ( ! $fsock )
	{
		return FALSE;
	}
	else
	{
		return TRUE;
	}
}

?>

Useful Example of Using PHP Ping Script

We can use this ping function to allow us to provide our users with a better message rather than seeing our site is down.

<?php

$host = 'www.example.com';
$up = ping($host);

// if site is up, send them to the site.
if( $up ) {
	header('Location: http://'.$host);
}
// otherwise, take them to another one of our sites and show them a descriptive message
else {
	header('Location: http://www.anothersite.com/some_message');
}

?>

Now if the site is up, they will get sent to your site. Otherwise they will be sent to www.anothersite.com and shown a message.

Pass a PHP Array to Javascript as JSON using AJAX and json_encode

Overview

You will mostly likely (or already have) reached a point where you have a PHP array and you need to be able to access that array from inside a Javascript function. You may wonder if it is possible to pass an array from PHP to Javascript. Fortunately I have created a tutorial on how this can be achieved. Below I will show you how to Pass a PHP Array to Javascript as JSON using AJAX. There are two parts to accomplish this task.

Creating The PHP Array

Firstly you need a PHP script which has the PHP array you want to pass back to Javascript. You encode the array into a JSON string using the PHP function `json_encode()`. We then echo the string into the PHP file to make it accessible to the AJAX function calling this script.

Call The PHP Script That Contains The PHP Array

Secondly we create an HTML which will contain the AJAX function to call the PHP script. We will use the jQuery `$.getJSON` function which converts the output from the PHP function ‘json_encode()’ into a JSON object. Once we have the JSON object, we can loop through it and use it as we require. We don’t really need to convert the JSON array to javascript array since we use jQuery’s ‘$.each()’ function to loop through the JSON array that is returned.

Pass a PHP Array to Javascript as JSON using AJAX

Below is the code that is to be placed into the PHP script. This file will be called by the jQuery `$.getJSON` function.

<?php

/* set out document type to text/javascript instead of text/html */
header("Content-type: text/javascript");

/* our multidimentional php array to pass back to javascript via ajax */
$arr = array(
	array(
		"first_name" => "Darian",
		"last_name" => "Brown",
		"age" => "28",
		"email" => "darianbr@example.com"
	),
	array(
		"first_name" => "John",
		"last_name" => "Doe",
		"age" => "47",
		"email" => "john_doe@example.com"
	)
);

/* encode the array as json. this will output [{"first_name":"Darian","last_name":"Brown","age":"28","email":"darianbr@example.com"},{"first_name":"John","last_name":"Doe","age":"47","email":"john_doe@example.com"}] */
echo json_encode($arr);

?>

Javascript / HTML Code Snippet

Place this code into a file with the extension `.html`. The below code will call the above PHP script using AJAX and the jQuery function `$.getJSON`. The PHP script will have the PHP array encoded as a json string. Once the `$.getJSON` function returns, the Javascript function will have access to the PHP array that has been converted into a JSON object.

<html>
<head>
	<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>

	<!-- this UL will be populated with the data from the php array -->
	<ul></ul>

	<script type='text/javascript'>
	$(document).ready(function(){
		/* call the php that has the php array which is json_encoded */
		$.getJSON('json_encoded_array.php', function(data) {
			/* data will hold the php array as a javascript object */
			$.each(data, function(key, val) {
				$('ul').append('<li id="' + key + '">' + val.first_name + ' ' + val.last_name + ' ' + val.email + ' ' + val.age + '</li>');
			});
		});

	});
	</script>

</body>
</html>

 

Passing variables to PHP using JSON and AJAX

If you would like to pass some variables to PHP you can change the parameters as shown above. In my example below, I pass the variables name and age and then the PHP function could use these to search a database or file for that person and then return that specific information as a JSON array.

$.getJSON('json_encoded_array.php', {name:'Darian Brown',age:40}, function(data) {
	// ... handle response as above
}