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.

Disable SSH Login For FTP User

Overview

The below guide will show you have to create an FTP account for vsftpd and also block ssh access making a ssh account a ftp only account. This will also disable telnet access to the ssh account.

Disable SSH Login For FTP User

Secure Lock

Create The Ftp User

The ssh login account will be used as the ftp login account. So first step is to create the ssh user. Since this will be the FTP username choose name you wish to use are your ftp username. someusername is the username I am using as an example for this tutorial. We will disable ssh access later on.

Enable FTP Login Using SSH Account

In order to allow local ssh users to be able to ftp in, you need to set local_enable=YES in your vsftpd.conf file. That will allows any users on the system, to gain access to the server through FTP.

adduser someusername

Disable SSH Login For FTP User

Open up your passwd file which is usually located under /etc/passwd. Now change the default shell which would be similar to /bin/bash to your ftp only shell which I will create as /etc/ftponly. I created the file under /etc/ftponly however you can place the file anywhere you see fit.

someusername:x:1017:1017:,,,:/home/someusername:/etc/ftponly

Create the ftponly shell file

Now create the ftponly file of /etc/ftponly and type in a scary message to deter trespassers. Save the file in the location you specified in the passwd file located at /etc/passwd.

#!/bin/sh
echo "Welcome to my FTP Webserver. Please note that all activity is tracked for security purposes!"
exit

Ensure the file can be executed

chmod a+x /etc/ftponly

Step 5 – Add ftponly as a valid shell

Add our file /etc/ftponly to the list of valid shells. Simply add the following line to the end of your shells file which is located at /etc/shells. Your shells file will look something like this:

# /etc/shells: valid login shells
/bin/csh
/bin/sh
/usr/bin/es
/usr/bin/ksh
/bin/ksh
/usr/bin/rc
/usr/bin/tcsh
/bin/tcsh
/usr/bin/esh
/bin/bash
/bin/rbash
/usr/bin/screen
/etc/ftponly

All Done!

Now when people try to ssh or telnet into the server, they will see the message “Welcome to my FTP Webserver. Please note that all activity is tracked for security purposes!” and they won’t be able to gain any further access however they will still be able to login using FTP.

Warning Note!

If the shells file /etc/shells file doesn’t exist, you will need to add in the other shells similar to above since you will be overriding the default shells. If you fail to do so, you could prevent any further ssh access.

2D Sprite Animation Tutorial

What are sprite animations?

A sprite animation is basically a large image which contains a whole bunch of smaller images. Think of it as a film strip where each frame is the next piece of animation in the sequence. The idea of sprites is that you only need to load one image and it will contain all the smaller images needed to create the animation. You simply position the background position of the sprite and it will appear to animate the sprite. For more information on sprites, check out the css button sprite tutorial.

End Result Demonstration


Above is the finished example of a flame sprite and it is what this tutorial will show you. As you can see it appears as an animation, however we simply move the background position of the larger image to create the illusion of movement.

Why should you use sprites?

Before images and css items can be displayed on your webpage, your browser must request the item such as javascript files, images, css files, etc. Each request takes time and your browser must wait for a response and then download the file for it to be displayed. So in short, the less items means less time to request and download items, meaning less time to load a page. So using sprites will increase the speed at which your website loads.

Flame Ball Sprite

2D Sprite Animation Tutorial

Above is the large flame sprite image I am using to create the sprite animation for this tutorial. We use javascript to move the background position of the sprite image. In the below example, we do this every 100ms. To achieve smooth animation, we would need to achieve 25 frames per second, however this would increase the size of the sprite image, so we will do it a time frames per second.

Now for the code to get this all working

CSS Code

<style type="text/css">

#flameanimation {
	/* our flame sprite png */
	background: url(http://www.example.com/images/flamesprite.png);
	width: 512px;
	height: 512px;
}

</style>

Javascript Code

Here is a quick javascript function to move the background position of the sprite animation to the next frame. We start at frame 1 and for each frame of animation we move 512px to the left since each frame is 512px wide by 512px high. Moving the background image positions every frame creates the illusion of movement, just as a movie is made up of 25 or 29 frames in a second.

<script type='text/javascript'>

$(document).ready(function(){
	// call the next() function every 100 ms.
	setInterval(next, 100);
});

// first frame of animation
var frame = 1;

// move the sprite animation to the next frame
//	i.e. move background position to the next image in the sequence
function next()
{
	// Set the position of the sprite image 512px more to the left on each frame.
	var left = 512 * frame;
	// top stays 0 since all the images have Y positioned at 0
	var top = 0;
	document.getElementById('flameanimation').style.backgroundPosition = '-'+left+'px -'+top+'px'; 

	frame++;
}

</script>

HTML Code

Next we create the div tag where the sprite animation will be applied to.

<div id="flameanimation" title="Sprite Animation"></div>

Now as the javascript next() function runs, it will move the background image to the left which will create the illusion of animation.

flame sprite image obtained from http://forum.unity3d.com/threads/60284-Free-2d-sprite-animations.

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
}

How To Abort A Previous Ajax Request In jQuery

Overview

When using ajax to request a page or data, there will be occasions where you will need to cancel the ajax call. I found this useful after building a search as you type feature and I would abort the previous search and request a new ajax search each time they typed a new letter. Since their old word has changed to a new meaning, completing the old request is meaningless since the new word is an entirely different category. For example the typed fee and then they type `d` making the word feed. So I would abort a previous ajax request in jquery and issue a new ajax search on feed.

Additional uses for aborting an ajax request in jquery

Another reason may be that the page you are calling enters an infinite loop and stops the call from returning. Maybe you need to cancel a previous request before making a new request to prevent duplicate requests from being sent.

How To Abort A Previous Ajax Request In jQuery

Luckily jQuery has made this almost too easy as you can see by my example below.

/* our handler to the ajax request */
var xhr = null;

function goAjax()
{
	/* if there is a previous ajax request, then we abort it and then set xhr to null */
	if( xhr != null ) {
		xhr.abort();
		xhr = null;
	}

	/* and now we can safely make another ajax request since the previous one is aborted */
	xhr = $.ajax({
		type: "POST",
		url: "/some/url",
		data: "variables=whatever&var2=something",
		success: function(msg) {
			/* handle the ajax response */
		}
	});
}

Now you can call the goAjax() function as often as you like and it will cancel the previous ajax request if it hasn’t been completed before making a new request preventing duplicate requests from stacking up.

<a href='javascript:goAjax();'>Click me as much as you like</a>

And that is all there is to it. Simple and straightforward.