Categories
SQL / MySQL Tips and Tutorials

MySQL: Incorrect key file error AND InnoDB: Error: unable to create temporary file; errno: 2

When I encounter the incorrect key file for table error, it’s almost certainly because the disk is full and MySQL can’t write to the tmpdir. The solution is simple, just move tmpdir to another partition with enough disk space.

Open my.ini and change tmpdir to another directory with enough disk space. Restart MySQL and that should do it.

However on Windows, such as for WAMP, you need to make sure you use slashes (/) rather than backslashes (\) in the path for tmpdir in my.ini, or it would be this error and mysqld would simply refuse to start:

InnoDB: Error: unable to create temporary file; errno: 2

Categories
Hosting Tips & Deals Manage Your Own Server SQL / MySQL Tips and Tutorials

Make phpMyAdmin Show Exact Number of Records for InnoDB Tables

By default, phpMyAdmin shows an estimated number of records for InnoDB tables that have more than 20,000 rows. It can vary by every fresh as much as 50% or even more. Makes it hard to get an exact number of records for the tables as we have to explicitly run an SQL query to do that:

SELECT COUNT(*) FROM table_name

While it would make it a bit slower for phpMyAdmin to open up the database tables list page because it has to count the exact total number of records of each table in the database by this query, it’s worth it for some of us as we want to know the exact number of rows the InnoDB table currently has. phpMyAdmin does it for MyISAM tables, and we want it to do the same with InnoDB tables.

So how can we make phpMyAdmin show exact number of records for InnoDB tables?

Simple. Just open the config.inc.php in your phpMyAdmin installation directory and add this line:

$cfg['MaxExactCount'] = 2000000;

This configuration parameter sets the threshold that phpMyAdmin executes COUNT(*) against the table.

In this case, if the total number of recrods in this InnoDB table is larger than 2,000,000, the Rows count will be estimated, starting with a wave sign, ~; on the other hand, if the total number of records in this InnoDB table is smaller than 2,000,000, phpMyAdmin will run COUNT(*) against the table so an exact Rows count is displayed.

You get the idea.

To make phpMyAdmin show exact number of rows on all InnoDB tables, simply make the parameter $cfg[‘MaxExactCount’] large enough.

Categories
Free PHP Classes & Library PHP Tips & Tutorials

Convert Object to Array in PHP

There are quite a few ways to do this and each of them has its strengths and weaknesses. Find out if one suits your needs by trying one of the approaches below.

Casting with (array)

$array = (array) $obj;

Problem is this doesn’t convert complex / multi-dimensional objects well.

get_object_vars()

$array = get_object_vars( $obj );

$array would then be an array of properties and values from $obj that are accessible in the current scope.

Custom function for complex objects

function objectToArray( $object )
    {
        if( !is_object( $object ) && !is_array( $object ) )
        {
            return $object;
        }
        if( is_object( $object ) )
        {
            $object = get_object_vars( $object );
        }
        return array_map( 'objectToArray', $object );
    }

$array = objectToArray( $obj );

This function is conjured by PHPRO.ORG.

JSON – json_encode(), json_decode()

$json  = json_encode($object);
$array = json_decode($json, true);

This is probably the coolest approach delivered by Andy.

Categories
PHP Tips & Tutorials Regular Expression Tips & Tutorials WordPress How To

PHP preg_match() First Letter of a WordPress Post for Drop Cap Styling

Drop Cap ExampleWhile CSS3 can target the first letter of text inside an element, it’s still not universally supported across major browsers AND it doesn’t work well for elements that have child elements inside. The bullet proof way to target the first letter of a WordPress post would be to capture the content of the post in WordPress theme and match it by regular expression functions in PHP, such as preg_match().

And here’s the code I’ve come up for this job:

ob_start();
the_content();
$content = ob_get_clean();
$content = preg_replace('@<p>\s*((?:<[^<>]+>\s*)*)([^<>\s])@'
, '<p>$1<span class="drop_cap">$2</span>'
, $content
, 1);

echo $content;

Obviously, this code should reside in single.php of your WordPress theme where the content of the posts is being output. Just replace any “the_content()” function in the post area with this snippet.

The key is the regular expressions:

@<p>\s*((?:<[^<>]+>\s*)*)([^<>\s])@

And:

<p>$1<span class="drop_cap">$2</span>

That finds the 1st non-whitespace, printable character (a letter, a numeral, etc.) of a post and adds a surrounding <span> tag with class “drop_cap” to it.

Now you will add some drop cap styles to style.css as class .drop_cap, and the first letter of your posts will have a nice drop cap style. See this blog Mosso Reviews for example.

Categories
PHP Tips & Tutorials

PHP Getting the last xx bytes of a large text file

Sometimes the text files are very large and you don’t want to load it in memory before searching through it because it’s inefficient. You just want to get the last few bytes of the file because the latest additions / updates are there.

This would help you:

$fp = fopen('somefile.txt', 'r');
fseek($fp, -50, SEEK_END); // It needs to be negative
$data = fgets($fp, 51);

Which gets the last 50 bytes of the file somefile.txt in $data. Thanks to niels for the solution.

Make sure the 2nd parameter for fgets() is 1 more than the absolute value of the 2nd parameter for fseek().

Categories
.htaccess Tutorials & Tips Free PHP Classes & Library Information Security PHP Tips & Tutorials

PHP Class for Handling .htpasswd and .htgroup (Member Login & User Management)

Apache is a marvelous web server that offers .htpasswd and .htgroup for controlling restricted access to your website. By help of .htaccess, they work as a member login & user management system that is so simple and easy to deploy. You can even define user groups / roles with it.

Basically,

  • .htpasswd defines pairs of username & password that are user accounts.
  • .htgroup defines groups / roles of user accounts that can be access-controlled as a whole.
  • .htaccess then applies .htpasswd and .htgroup to the current directory, and specifies which groups in .htgroup has access to the current directory.

For example, we have

/home/myuser/.htpasswd

user1:{SHA}kGPaD671VNU0OU5lqLiN/h6Q6ac=
user2:{SHA}npMqPEX3kPQTo+x/+ZckHDrIcQI=
user3:{SHA}q1Fh2LTUjjkncp11m0M9WUH5Zrw=

/home/myuser/.htgroup

admin: user2
editor: user1 user3
writer: user3

/home/myuser/public_html/example.com/member/.htaccess

AuthName "Members Area"
AuthType Basic
AuthUserFile /home/myuser/.htpasswd
AuthGroupFile /home/myuser/.htgroup
<Limit GET POST>
require group admin
require group writer
</Limit>

What they do is only let users in the admin and writer group, that is user2 and user3, to access example.com/member. When someone tries to access example.com/member, Apache would prompt him or her for user name and password, and he or she must be either user2 or user3 to access it – they must enter the correct password set out in .htpasswd for user2 or user3.

user1 isn’t allowed to access example.com/member even if the password is correct. You get the idea.

You can place .htaccess anywhere in your website, and it will control access to the directory it’s in by the defined rules (which groups / roles are allowed to access). Just make sure it is pointing to the right .htpasswd and .htgroup by AuthUserFile and AuthGroupFile.

And you can have multiple .htaccess in different directories of your website, using the same .htpasswd and .htgroup.

This is so simple yet so very handy in creating & managing different users and user roles (.htpasswd, .htgroup) and giving them permissions (.htaccess) in accessing different website assets.

PHP Class

Now that you are familiar with the basic authentication and native user management system in Apache, you can use this two simple PHP classes to automate tasks such as user creation, user deletion, adding user to group, and removing user from group.

class Htpasswd

class Htpasswd {
	
	private $file = '';
	private $salt = 'AynlJ2H.74VEfI^BZElc-Vb6G0ezE9a55-Wj';
	
	private function write($pairs = array()) {
		$str = '';
		foreach ($pairs as $username => $password) {
			$str .= "$username:{SHA}$password\n";
		}
		file_put_contents($this -> file, $str);
	}
	
	private function read() {
		$pairs = array();
		$fh = fopen($this -> file, 'r');
		while (!feof($fh)) {
			$pair_str = str_replace("\n", '', fgets($fh));
			$pair_array = explode(':{SHA}', $pair_str);
			if (count($pair_array) == 2) {
				$pairs[$pair_array[0]] = $pair_array[1];
			}
		}
		return $pairs;
	}
	
	private function getHash($clear_password = '') {
		if (!empty($clear_password)) {
			return base64_encode(sha1($clear_password, true));
		} else {
			return false;
		}
	}
	
	public function __construct($file) {
		if (file_exists($file)) {
			$this -> file = $file;
		} else {
			die($file." doesn't exist.");
			return false;
		}
	}

	public function getUsers() {
		return $this -> read();
	}
	
	public function addUser($username = '', $clear_password = '') {
		if (!empty($username) && !empty($clear_password)) {
			$all = $this -> read();
			if (!array_key_exists($username, $all)) {
				$all[$username] = $this -> getHash($clear_password);
				$this -> write($all);
			}
		} else {
			return false;
		}
	}
	
	public function deleteUser($username = '') {
		$all = $this -> read();
		if (array_key_exists($username, $all)) {
			unset($all[$username]);
			$this -> write($all);
		} else {
			return false;
		}
	}
	
	public function doesUserExist($username = '') {
		$all = $this -> read();
		if (array_key_exists($username, $all)) {
			return true;
		} else {
			return false;
		}
	}
	
	public function getClearPassword($username) {
		return strtolower(substr(sha1($username.$this -> salt), 4, 12));
	}
	
}

class Htgroup

class Htgroup {
	
	private $file = '';
	
	private function write($groups = array()) {
		$str = '';
		foreach ($groups as $group => $users) {
			$users_str = '';
			foreach ($users as $user) {
				if (!empty($users_str)) {
					$users_str .= ' ';
				}
				$users_str .= $user;
			}
			$str .= "$group: $users_str\n";
		}
		file_put_contents($this -> file, $str);
	}
	
	private function read() {
		$groups = array();
		$groups_str = file($this -> file, FILE_IGNORE_NEW_LINES);
		foreach ($groups_str as $group_str) {
			if (!empty($group_str)) {
				$group_str_array = explode(': ', $group_str);
				if (count($group_str_array) == 2) {
					$users_array = explode(' ', $group_str_array[1]);
					$groups[$group_str_array[0]] = $users_array;
				}
			}
		}
		return $groups;
	}
	
	public function __construct($file) {
		if (file_exists($file)) {
			$this -> file = $file;
		} else {
			die($file." doesn't exist.");
			return false;
		}
	}

	public function getGroups() {
		return $this -> read();
	}
	
	public function addUserToGroup($username = '', $group = '') {
		if (!empty($username) && !empty($group)) {
			$all = $this -> read();
			if (isset($all[$group])) {
				if (!in_array($username, $all[$group])) {
					$all[$group][] = $username;
				}
			} else {
				$all[$group][] = $username;
			}
			$this -> write($all);
		} else {
			return false;
		}
	}
	
	public function deleteUserFromGroup($username = '', $group = '') {
		$all = $this -> read();
		if (array_key_exists($group, $all)) {
			$user_index = array_search($username, $all[$group]);
			if ($user_index !== false) {
				unset($all[$group][$user_index]);
				if (count($all[$group]) == 0) {
					unset($all[$group]);
				}
				$this -> write($all);
			}
		} else {
			return false;
		}
	}

	public function getGroupsByUser($username = '') {
		$all = $this -> read();
		$user_groups = array();
		foreach ($all as $group => $users) {
			if (in_array($username, $users)) {
				$user_groups[] = $group;
			}
		}
		return $user_groups;
	}

}

Usage

First, you should use your own $salt. Change the value of $salt in the Htpasswd class to something else for your own application.

To instantiate the classes:

$passwdHandler = new Htpasswd('/home/myuser/.htpasswd');
$groupHandler = new Htgroup('/home/myuser/.htgroup');

To create and delete a user:

// Add a user with name 'user1' and password 'I prefer to use passphrase rather than password.' if it doesn't exist in .htpasswd.
$passwdHandler -> addUser('user1', 'I prefer to use passphrase rather than password.');
// Delete the user 'user1' if it exists in .htpasswd.
$passwdHandler -> deleteUser('user1');

To check if a particular user exists in .htpasswd:

// Check if user 'user1' exists in .htpasswd.
if ($passwdHandler -> doesUserExist('user1')) {
	// User 'user1' exists.
}

To get the clear text password for a particular user (Apache stores passwords in .htpasswd as encoded strings):

// Get the clear password for user 'user1'.
echo $passwdHandler -> getClearPassword('user1');

To add a user to a group:

// Add user 'user1' to group 'admin' in .htgroup. Group will be automatically created if it doesn't exist.
$groupHandler -> addUserToGroup('user1', 'admin');

To delete a user from a group (user still exists in .htpasswd, just not associated with the group any more):

// Delete user 'user1' from group 'admin' in .htgroup. Group will be automatically removed if it doesn't contain any users.
$groupHandler -> deleteUserFromGroup('user1', 'admin');

To get a list of groups a particular user is assigned to:

/* Get an array of groups that 'user1' is a member of. */
$user_groups = $groupHandler -> getGroupsByUser('user1');

Conclusion

This ain’t concluded. It’s just an END notice. Feel free to let me know your thoughts and how my classes work for you.

Categories
PHP Tips & Tutorials

PHP: Strip or Trim Extra Whitespaces Inside a String

There are raw strings that contain extraly unwanted whitespaces (tabs, spaces, new lines) that you want to get rid of so as to form a normalized string that has only a single spaces between words and sentences. For instance, you may want to transform this string:

Morning   is here,   sunshine
   is here.    Morning is    here.

Into this:

Morning is here, sunshine is here. Morning is here.

How to achieve this in PHP?

Just use this function:

function purge_inside_whitespaces($text) {
	while (preg_match('/\s{2}/', $text)) {
		$text = preg_replace('/\s{2}/', ' ', $text);
	}
	return $text;
}

Basically, it keeps scouring through the $text string passed to it and removes any continuous whitespaces and replace them with single spaces, until it can’t find any more continuous whitespaces.

Note you would need to apply trim() to get rid of any whitespaces in the beginning or at the end of the string, because if there are any there, a single space would still remain after applying purge_inside_whitespaces().

Categories
SQL / MySQL Tips and Tutorials

MySQL: LOAD DATA LOCAL INFILE only imports 1 or 2 rows?

It is common to import CSV files into MySQL database. You can do this with phpMyAdmin with small CSV files but with large ones, you would probably encounter the memory error and had to switch to MySQL command line “LOAD DATA LOCAL INFILE” to do the job.

It looks like something like this:

LOAD DATA LOCAL INFILE 'your.csv'
INTO TABLE `your_table`
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(field1, field2, field3)

And then you encounter another problem that it only imports the first 1 or 2 rows and then it stops. After some researching and trying, I was sure it’s something to do with the “LINES TERMINATED BY” directive. Depending on the platform that the CSV file is created on, the line delimiter may be

  1. \n
  2. \r\n
  3. \r

And you need to be correct on the line delimiter to properly parse the CSV file.

So the solution is to try them all one by one and see which one of them works. Chances are, one of them would make the whole command successfully import ALL rows.

Another simple approach is to deprive the whole command of the “LINES TERMINATED BY” directive and let MySQL do the call. It’ll probably detect things right but in my case, this doesn’t work but specifying ‘\r’.

Categories
PHP Tips & Tutorials

PHP: Check if A String Contain Only Uppercase / Capital Letters

Sometimes you would want to check if a string is an acronym or an abbreviation by testing if it only contains capitalized letters from A to Z and nothing else. There are 2 ways to accomplish this simple task in PHP.

ctype_upper()

Use the native ctype_upper() function and you will know if the provided string contains only uppercase letters:

if (ctype_upper($string)) {
	echo $string.' is all uppercase letters.';
} else {
	echo $string.' is not all uppercase letters.';
}

The Ctype functions would turn out to be very handy when you want to test a string against different character types – digits, alphabetic, alpha-numeric, lowercase letters, uppercase letter, and even punctuations, etc. See the full list here: http://www.php.net/manual/en/ref.ctype.php

strtoupper()

Use the strtoupper() function to transform the string into all uppercase characters that’s capitalized letters, and then compare the transformed string against the original one to see if they are identical. If they are, then you are pretty sure the original string was also a string consisting of ONLY capital letters.

if (strtoupper($string) == $string) {
	echo $string.' is all uppercase letters.';
}

Check if A String Consists of Only Lowercase Letters

The same goes true if you want to do the test other way around. Just use ctype_lower() and strtolower() instead.

Categories
Desktop Development Internet Tools

FFVCL – FFmpeg Delphi VCL for Video / Audio Apps Development

ffmpeg delphi vclThis post is dedicated to one of my friends, Coolie (not his real name but he preferred to be called that way among friends), a father and self-entrepreneur who created the outstanding Delphi VCL component for FFmpeg that makes it extremely easy to develop audio and video applications for Windows.

For those who are not Windows desktop developers, FFmpeg is the ONE video and audio applications library across all major platforms that is able to encode, decode, edit, convert and stream audio and video. It is widely adopted as the standard library for multi-media applications development. Chances are, what you currently have for media player in your operating system uses FFmpeg to do all the underlying work.

The problem with FFmpeg is that it’s only got a command line interface. You would definitely find it fascinating if you are a Linux guru, but not GUI users. Developers must create another layer of interface to accommodate end users, another layer of abstraction for FFmpeg, and that’s exactly where Coolie’s talent comes in, who heroically produced the Delphi VCL for FFmpeg and the ActiveX OCX Controls for FFmpeg. Problem solved for people who want to make video and audio applications in Windows but daunted by the command-line FFmpeg.

Simply ground-breaking work he has made, Coolie graduated from Tsinghua university, the China counterpart of MIT or Princeton – approximately 100,000 high school students each year compete for just 1 admission to Tsinghua. Think about that.

Feel free to bug him if you are interested in developing a multi-media application yourself – it’s not so hard as it may seem because many contemporary languages and platforms are made to be used by absolute programming beginners, such as VB.NET.