When you read the content of any specified directory with PHP functions such as scandir() or readdir(), they will return both files and directories. How does one get just the child directories of a given directory in PHP? The obvious solution is the is_dir() function that checks if a filename is a directory:

$all = scandir('.'); // . stands for the current directory, you can use any path string here
$dirs = array();
foreach ($all as $each) {
	if (is_dir($each)) {
		$dirs[] = $each;
	}
}
print_r($dirs);

Which will return:

Array
(
    [0] => .
    [1] => ..
    [2] => dir1
    [3] => dir2
    [4] => dir3
)

Clearly, the problem of this approach is that it also returns ‘.’ and ‘..’.

A better approach is the glob() function that searches the current directory by a certain pattern. You can use it in conjunction with the array_filter() function to select all the directories:

$dirs = array_filter(glob('*'), 'is_dir'); // is_dir function is used against each item of the array returned by glob('*')
print_r($dirs);

Which will give out results:

Array
(
    [0] => dir1
    [1] => dir2
    [2] => dir3
)

A neater way to get the same results with glob() function is this:

$dirs = glob('*', GLOB_ONLYDIR);
print_r($dirs);

The GLOB_ONLYDIR flag commands the function to return only directory entries that match the pattern ‘*’.

{ Comments on this entry are closed }

If you have mysqli extension installed with PHP and you use it to perform database operations, after you have tried to connect to MySQL by:

$conn = new mysqli('localhost', 'db_user', 'db_pwd', 'db_name');

You can then check if the connection is successful by:

if ($conn -> connect_errno) {
  // failure
} else {
  // success
}

That’s because connect_errno contains the error number of the last query. If there’s no error, it’s 0 by default. If an error occurred in the last query, it’s a natural number greater than zero. There you go with the conditional check of whether the PHP database connection is successful.

However if you are using the legacy mysql extension to connect to MySQL databases:

$conn = mysql_connect('localhost', 'db_user', 'db_pwd');

It’s even simpler. The returned value of mysql_connect() function will be FALSE should the connection fail. Therefore, you can check if the connection is successful by:

if ($conn = mysql_connect('localhost', 'db_user', 'db_pwd')) {
  // success
} else {
  // failure
}

{ Comments on this entry are closed }

MySQL: Check if a table exists

by Yang Yang on July 30, 2010

When I was creating an installation script, I needed to check if a table exists to make sure the installation had not been performed yet. How did I do that?

I use this simple query to get whether a table exists in the specified database:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'db_name'
AND table_name = 'table_name'

Just fill in the ‘db_name’ as well as ‘table_name’. If this query returns 1 row, the table db_name.table_name does exist, otherwise it does not.

{ Comments on this entry are closed }

My online income report – June, 2010

by Yang Yang on July 23, 2010

Edit: Forgot all the website advertising revenues other than AdSense. Added it.

So I thought I should start writing things that are more personal and interesting. I ended up with this crazy idea – posting about my online income. People always want to know how much people make online, and more importantly, how they have made the money online.

Listed below are my primary sources of income from last month, June, 2010.

  1. Google AdSense – $740.91
  2. Sales of my own products – $960.75
  3. Amazon Associate Program – $54.67
  4. Other affiliate / partner programs – $932.44
  5. Website advertising revenues other than AdSense (such as the buy sell ads on Kavoir.com) – Roughly $250

And the total amount of earnings I have made online from last month is about $2938. It’s not bad considering I spend like only 3 hours a day and 5 days a week working from home on my PC to get all this. The above earnings didn’t include my freelance projects which I used to rely on heavily for the primary source of income. I don’t quite like them because it’s not passive so I’m giving up on them. Unless it’s a very interesting project that I feel compelled to work on, I’d not do it for less than 5 figures.

If you would like to know how you can do this yourself, making 4 figures monthly, feel free to comment below and let me know. I will help as much as I can. Otherwise, what can you suggest as an interesting topic for Kavoir.com?

{ Comments on this entry are closed }

This is a pretty odd question to ask in the first place if you have been using JavaScript for a while. JavaScript files are called from HTML web pages who need them to manipulate the HTML elements so that the users have extraordinary interactive experience. You can’t include a JavaScript file inside another JavaScript file like you can with PHP files, but you can only include JS files from HTML files.

If you need something that’s in a JavaScript file such as a predefined function, just include the file before wherever you are using the function and it should be fine. For example, you are calling A.js from a HTML file:

<body>
<script type="text/javascript" src="A.js"></script>
</body>

There is a rather sophisticated function in B.js that A.js relies on. You are wondering how to include B.js in A.js so A.js works properly. No you can’t. The answer is not to include B.js in A.js but include B.js in the HTML file before it includes A.js.

<body>
<script type="text/javascript" src="B.js"></script>
<script type="text/javascript" src="A.js"></script>
</body>

Now all the code in A.js should work fine. This is because all HTML code are read, parsed and executed in basic sequence from top to bottom. It’s the same with JavaScript code. When you need something from another JavaScript file and want to use it on the web page, just include it in the HTML web page. You can’t include a JavaScript file in a JavaScript file.

{ Comments on this entry are closed }

JavaScript: How to set focus to form elements?

by Yang Yang on July 22, 2010

Normally, when users click on any label tag with the cursor, the corresponding input field will be focused ready for input or selection. Therefore, you can always achieve the focus effect by this native function of HTML’s. Otherwise, you’d need a small dime of JavaScript to set focus to any form element on the fly upon a certain event:

// FormName is the name value of the form.
// FieldName is the name value of the field
// to be focused.
document.FormName.FieldName.focus();

Or by element ID:

// FieldId is the id value of the field
// element to be focused.
document.getElementById('FieldId').focus();

There you go, the tiny focus() function is what we all need.

{ Comments on this entry are closed }

To get the URL address of the current page with JavaScript, simply return the value of window.location.href:

document.write(window.location.href);

Which is the same with:

document.write(location.href);

There’s much more you can do with the JavaScript Location Object such as redirecting to another URL.

{ Comments on this entry are closed }

If the website is run on a Linux server, everything that can be run from the web (i.e., from the browser address bar) can be run from the Linux console. That is if you have the SSH access which most hosts provide. Connect to your hosting server via SSH by putty and you will have the ultimate control over your box. For example, you can execute a PHP script called routine.php via SSH by:

/usr/bin/php5 routine.php #routine.php is in the current working directory

Depending on your distro and PHP installation options, the command line interpreter (in this case, /usr/bin/php5) may vary in location.

You can add this line to a crontab job and it the PHP script routine.php will be executed by your designated intervals or at any certain time, automatically.

Other than calling PHP scripts from Linux console via SSH, you can also call to execute PHP code in another script file from the current PHP file. For instance, in A.php:

exec('/usr/bin/php5 B.php');

As it obviously suggests, this line will run the Linux command ‘/usr/bin/php5 B.php’ and you can put stuff in B.php that will be taken care of when this line in A.php is executed.

There are a variety of different PHP functions that perform essentially the same task, running system commands: exec, shell_exec, system and passthru.

{ Comments on this entry are closed }

Sometimes you need to temporarily halt the code execution of your PHP script for certain seconds and then automatically resume it. For example, some mail delivery servers have the restriction that you have to wait a certain interval such as 12 seconds before sending another email.

You can tell your PHP script to stop for 12 seconds before continuing down with the rest of the code by sleep() function:

sleep(12); // freeze PHP execution for 12 seconds before going ahead

That’s it. When it is executed to this line, PHP will freeze for 12 seconds, doing nothing, and then go on with the line immediately after this line.

{ Comments on this entry are closed }

I made a sale months ago when someone purchased a few website scripts for over $1,500. A few days after the transaction he fired a chargeback dispute. I thought, well ok, I’m puked. I almost gave in. But then I thought I couldn’t let him win this easily.

So I provided everything I can with regards to the dispute case in the PayPal resolution center, including transaction logs, email communications and several screenshots of proof that he had received the digital goods. A few days later, the funds are transferred away anyway. I lost.

This morning, however, PayPal sent me an email, over 100 days later:

Hello Kavoir,

We are pleased to inform you that we have successfully disputed chargeback
case #PP-xxx-xxx-xxx-xxx.  The buyer’s card issuer has decided in your
favor and within seven days you will receive reimbursement for $xxxx.xx USD.

This is truly a surprise and a good one. You can imagine the look I had when I read the message. To make sure, I logged into my PayPal account and saw the funds right reimbursed.

How awesome is that.

{ Comments on this entry are closed }