How to delete non-empty directory with PHP?

2 04 2011

You can easily delete any empty directory with build-in function rmdir(), but it can’t delete any directory which contains some file within it. For that, you need to first delete the files inside the directory. The below function exactly does the same, it recursively delete any internal files/directories. Take a look at the code-

function deleteDirectory($directory)
{
	if(!$dh=opendir($directory))
	{
		return false;
	}
	
	while($file=readdir($dh))
	{
		if($file == "." || $file == "..")
		{
			continue;
		}
		
		if(is_dir($directory."/".$file))
		{
			deleteDirectory($directory."/".$file);
		}
		
		if(is_file($directory."/".$file))
		{
			unlink($directory."/".$file);
		}
	}
	
	closedir($dh);
	
	rmdir($directory);
}
Advertisements




Getting directory size with PHP

2 04 2011

This script will show you how easily you can get the directory size with php. The function is used recursively to get the inside directories. It will return directory size in byte. Here is the code –

function getDirectorySize($directory)
{
	$dirSize=0;
	
	if(!$dh=opendir($directory))
	{
		return false;
	}
	
	while($file = readdir($dh))
	{
		if($file == "." || $file == "..")
		{
			continue;
		}
		
		if(is_file($directory."/".$file))
		{
			$dirSize += filesize($directory."/".$file);
		}
		
		if(is_dir($directory."/".$file))
		{
			$dirSize += getDirectorySize($directory."/".$file);
		}
	}
	
	closedir($dh);
	
	return $dirSize;
}




How to add new file extension to parse php code?

28 03 2011

For some reason if you need to enable a new file extension rather than .php to parse your php code, then this article will help you. But before you proceed, i would like to warn you an issue. If you enable other file extensions like .html to parse php code, every time an html file is requested, it is passed to php for parsing. It may have an issue with performance. However, if you need to enable more extensions to parse php code, then continue reading.

The process is very simple, all you need is to add the specified extension in your apache configuration file, which is httpd.conf . So you need to locate the file. Open the file and find the line –

AddType application/x-httpd-php .php

If its not there, add the line and then add your desired extension after .php separated by space –
AddType application/x-httpd-php .php .html

Finally restart apache server. This way you can add other extensions. What it does is, it binds a MIME type to a particular extension.





Fix problem installing reCaptcha with table layout

12 03 2011

In my earlier post, i showed you how you can easily install reCaptcha in your php scripts. In this post i would like to mention a quick fix to those of you who have experienced an unusual error while trying to install it. If you have ever tried to install the reCaptcha in a form containing html table and put the form inside the table, then i have faced this situation, where every successful submission of form will tell you reCaptcha was incorrect like that “The reCAPTCHA was incorrect, try it again.”.

The fix is simple, just place the table inside the form and it will work.





Use reCAPTCHA in your PHP Scripts

26 11 2010

With reCAPTCHA, you can easily provide captcha on you php powered sites. Simply follow the steps –

1. First you need to download reCAPTCHA PHP library, there you will find a php file named recaptchalib.php, which we will include later in our scripts.

2. Then sign up for API keys for your site. If you are planning to use the same key over all sub-domains, then you can enable the ‘global key’ option while signing up. You will be given a public key and a private key. Public key is for use in html/javascript code, that is served to end users. And private key is used in processing part, for communicating between your server and reCAPTCHA server.

3. Now time to show the captcha image in your site, just put the code block below inside the form tag where you wish captcha image to display –

require_once('recaptchalib.php');
$publickey = "your_public_key"; // you got this from the signup page
echo recaptcha_get_html($publickey);

4. And finally you need to verify the user input against the captcha image displayed, the following code block is responsible for that –

<?php
  require_once('recaptchalib.php');
  $privatekey = "your_private_key";
  $resp = recaptcha_check_answer ($privatekey,
                $_SERVER["REMOTE_ADDR"],
                $_POST["recaptcha_challenge_field"],
                $_POST["recaptcha_response_field"]);

  if (!$resp->is_valid) {
    // What happens when the CAPTCHA was entered incorrectly
    die ("The reCAPTCHA was incorrect, try it again.");
  } else {
    // Your code here to handle a successful verification
  }
?>

Thats all, it will surely save you from few hours of coding if were doing all this from scratch.





send email with attachment using gmail’s smtp server with PHP

25 11 2010

In the previous post we have send email using gmail’s smtp server. This post will actually extend that post to send emails with attachments. First make sure you have following pear packages installed : Mail, NET_SMTP and Mail_Mime. Lets have a look at the code-

<?php
require_once "Mail.php";
require_once "Mail/mime.php";

$from      = "username@gmail.com";
$to        = "someone@gmail.com";
$subject   = "Test Message!";
$bodyTxt   = "Its working!";

$config=array(
    'host'      => 'ssl://smtp.googlemail.com',
    'port'      => 465,
    'auth'      => true,
    'username'  => 'gmailUsername',
    'password'  => 'gmailPass'
);

$filepath="sample.txt";
$fileContentType="text/plain";

$mime = new Mail_Mime("\r\n");
$mime->setTXTBody($bodyTxt);
$mime->addAttachment($filepath,$fileContentType);

$headerInfo=array(
    'From'      => $from,
    'To'        => $to,
    'Subject'   => $subject
);

$body = $mime->get();
$headers = $mime->headers($headerInfo);

$smtp = Mail::factory('smtp',$config);

$mail = $smtp->send($to, $headers, $body);

if(!(PEAR::isError($mail)))
{
    echo "Mail sent successfully!";
}

else
{
    echo $mail->getMessage();
}
?>




send email using gmail’s smtp server with PHP

25 11 2010

In this post i will show you how to send email using gmail’s smtp server. You need to install two pear packages, Mail and NET_SMTP. Code is quite self explanatory.

<?php
require_once "Mail.php";

$from    = "username@gmail.com";
$to      = "someone08@gmail.com";
$subject = "Test Message!";
$body    = "Its working!";

$config=array(
    'host'      => 'ssl://smtp.googlemail.com',
    'port'      => 465,
    'auth'      => true,
    'username'  => 'gmailUserName',
    'password'  => 'gmailPass'
);

$headers=array(
    'From'      => $from,
    'To'        => $to,
    'Subject'   => $subject
);

$smtp = Mail::factory('smtp',$config);

$mail = $smtp->send($to, $headers, $body);

if(!(PEAR::isError($mail)))
{
    echo "Mail sent successfully!";
}

else
{
    echo $mail->getMessage();
}
?>