Posts Tagged PHP

Truncate last N lines of a file using PHP

For one of my project I needed to remove certain footer / tail-end lines from the large-file to make it clean as it was containing some summary of records within the file. Because if I do that it can be directly loaded into database by LOAD DATA command.

Usually one can read file into an array using PHP's file function but that's okay when size of file is in few hundred KB, if your file-size is running in to few MB to few hundred MB we need to find and use some efficient way to play with them. Because with large file reading as an array we can (and certainly will) run into memory outage issue.

To remove lines from the end of file you can use following snippet of code:

 
// Function to truncate last N lines from the file
function truncate_last_n_lines_of_file($file, $lines_to_remove, $chunk = 1024)
{
	// Open file in read+write mode
	$handle = @fopen($file, "a+");
	$lines_found = array();
 
	// Check if it's a valid file handle
	if($handle)
	{
		// size of file
		$max_length = $file_size = filesize($file);
		if(intval($file_size) == PHP_INT_MAX)
		{
			$max_length = PHP_INT_MAX;
		}
 
		// loop through file as long as we are not done with truncating required files
		for($length = 0; $length < $max_length; $length += $chunk)
		{
			if( ($max_length - $length) > $chunk)
			{
				$seek_size = $chunk;
			}
			else
			{
				$seek_size = $max_length - $length;
			}
 
			// read data in chunk
			fseek($handle, ($length + $seek_size) * -1, SEEK_END);
			$data = fread($handle, $seek_size) . $data;
 
			// Loop thorugh chunk to see if we are done with truncate
			for($i = $chunk; $i > 0; $i--)
			{
				if($data[$i-1] == "\n")
				{
					$lines_found[] = $i;
				}
				if(count($lines_found) == $lines_to_remove+1)
				{
					ftruncate($handle, ($max_length) - ($seek_size - $lines_found[$lines_to_remove]));
					return true;
				}
			}
			fclose($handle);
		}
		return false;
	}
}
 

Read the rest of this entry »

Tags: , , ,

Netbeans 7.0 RC1 Released


Netbeans IDE 7

Netbeans IDE 7 RC1 Released

Netbeans has been one of my favorite IDE for PHP, I have been using it in my day to day usage for most of my projects. I have been using Netbeans since 6.x. I know it's Java based IDE which needs powerful machine just like Eclipse. But some of the feature it offers are even not available in commercial competitors. One of the best feature is "Quick Search", the way it provides search through list of file is awesome. Something similar I have seen is in JetBrains PHPStorm but could not find it in Enterprise class Eclipse.

I have been following and using and following progress on Netbeans 7 since it's first beta release and I have noticed that it has improved lot as far as speed of IDE is concerned. Whenever your Netbeans 7 IDE freezes for fraction of second or two it immediately opens up a window to report an issue. With each beta (1, 2) and now RC1 speed improvement and especially intelligent auto-complete speed has improved drastically (compared to 6.x).

Here is the quick view of features supported by Netbeans 7 platform: Read the rest of this entry »

Tags: , , , ,

Reading MSSQL BLOG column data with PHP

I was working on a migration script to transfer data from legacy desktop software to Portal we have developed. While migrating attachments (stored as TIFF files) in BLOB (Binary Large Object) in Microsoft SQL Database Server using PHP it was not a cake-walk. When I observed every time it was creating a file of same size (4KB). I quickly understood that there is some limitation (of size) for reading records in PHP configuration.

I searched through PHP.INI file and found following settings:

; Valid range 0 - 2147483647.  Default = 4096.
;mssql.textlimit = 4096
 
; Valid range 0 - 2147483647.  Default = 4096.
;mssql.textsize = 4096

I removed ";" and made values as zero, thinking that it will let PHP read unlimited size of data but didn't work out. So changed it to max value specified as following and worked perfect: Read the rest of this entry »

Tags: , , , , ,

Posting or Uploading Files using cURL with PHP

cURL - groks those URLs

groks URLs

cURL is very important tool for PHP programmers, we tends to do so many thing with using this tool. Posting data, imitating a form post and lot more, it's usage is countless. Some time back I came across situation where we have to post files to a 3rd party faxing service. I knew there are many possibilities but I didn't wanted to get into sockets and file stream to get this done, just wanted to post FILE in addition to rest of the post data.

// URL on which we have to post data
$url = "http://localhost/tutorials/post_action.php";
// Any other field you might want to catch
$post_data['name'] = "khan";
// File you want to upload/post
$post_data['file'] = "@c:/logs.log";
 
// Initialize cURL
$ch = curl_init();
// Set URL on which you want to post the Form and/or data
curl_setopt($ch, CURLOPT_URL, $url);
// Data+Files to be posted
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// Pass TRUE or 1 if you want to wait for and catch the response against the request made
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// For Debug mode; shows up any error encountered during the operation
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Execute the request
$response = curl_exec($ch);
 
// Just for debug: to see response
echo $response;

Above Code is the bare minimum required to post/upload file using CURL. As used in above example, it's not mandatory to use array index as "file". You can use anything required depending upon the requirement.

Posting multiple files is also easy, with the same code you can add multiple file upload using following lines:

$post_data['alian_error_log'] = "@c:/alian_app_error.log";
$post_data['myapp_error_log'] = "@c:/myapp_error.log";

Here @ is the key character, prefixing local file path with @ does all the trick.

 Read the rest of this entry »

Tags: , , , , , ,

Setting up PHP, MySQL, Apache with most up-to-date WAMP Package

WAMP Packages

WAMP Packages

Availability of WAMP packages is not a new story, they are here since the beginning of last decade now. EasyPHP, Wamp, XAMPP and dozens of them. Find comparison of WAMP packages on Wikipedia here.

We are here not to discuss all of them, just top 3 to 5 which are active and we can use them reliably for development or optionally for production purpose or both.

Having WAMP stake up-to-date on production environment is important as we are using open-source technologies and there are few to hundreds of critical to non-critical bugs are being fixed with every new release of the software, and if it's development environment we would like to test new features when they're hot.!

Zend Server, Zend Server Cluster Manager and Zend Server Community Edition:

Zend Server (CE)

Zend Server (CE)

All 3 editions are highly reliable and ready for production usage. I have tried both Zend Server and ZS-Community Edition, Zend Server - Commercial version is pre-tweaked for performance on production environment and Community Edition do not have some of the goodies. But that does not stop you or me from using Zend Server - CE on production. Zend Server comes with beautiful web-panel to administer, control and configure server from the browser itself. We can change PHP and Apache parameters, check server status and even restart service from within browser itself, this feature makes it good choice for remote server administration.

Zend Server - CE is as good for development as it is for production. It comes as Apache and PHP package where MySQL is an optional download during the installation wizard.

The Uniform Server:

The Uniform Server

The Uniform Server

Uniform Server is comparatively new kid on the floor and highly configurable for both development and production use. It comes with system tray using which we can switch Apache and PHP configuration files from development to production or back and forth.

It comes in both VC6 and VC9 binaries for Windows and I must say it's most up-to-date WAMP package so far (I mean next or equal to Zend). Rest of all WAMP packages take week to months to bundle latest version of Apache, PHP or MySQL but I have observed Uniform Server very quick with that. This is main benefit if you are really looking for such option to use on production server.

Installation is simplest - extract and done. Comes with minimum, no big bucket (just 11-13MB in size).

Comes with some handy plug-ins for FTP, Resin, Tomcat etc. It has e-Accelerator packed with it is recommended for production use.

Read the rest of this entry »

Tags: , , , ,

CodeIgniter 2 is just here – about to release..!

CodeIgniter - An MVC framework for PHP

CodeIgniter - An MVC framework for PHP

I have been using CodeIgniter since some time and used in couple of my projects. It's a good and easy to use PHP MVC Framework, which takes you on the road very quickly and you start developing real time application with it. For any experienced PHP Programmer it's matter of few hours to start working with CI and get started-on with production.

It's got decent documentation (User Guide, Wiki and Community support forum). No configuration and no command-lines. Last release was way back in September'09 and I heard something about v1.8 sometime after that. But now it has been more than 1 year and recently while going through news section on CI website I read a post stating that new version of framework CI2 is about to be released.

I got excited and downloaded a copy from bitbucket. I was happy to see that CodeIgniter2 will be dropping PHP4 support step by step. There are lot of new changes/additions which you might be interested in if you're day-to-day CI user. Ellislab being professional company CI2 has been already used in their newer version of ExpressionEngine.

Here are some of the changes I have grabbed from CodeIgniter2 User Guide:

  • General changes
    • PHP 4 support is deprecated. Features new to 2.0.0 may not support PHP 4, and all legacy features will no longer support PHP 4 as of 2.1.0. (Good)
    • Scaffolding, having been deprecated for a number of versions, has been removed.
    • Plugins have been removed, in favor of Helpers. The CAPTCHA plugin has been converted to a Helper and documented. The JavaScript calendar plugin was removed due to the ready availability of great JavaScript calendars, particularly with jQuery.
    • Added new special Library type: Drivers.
    • Moved the application folder outside of the system folder. (I liked this)
    • Added routing overrides to the main index.php file, enabling the normal routing to be overridden on a per "index" file basis.
    • Added the ability to set config values (or override config values) directly from data set in the main index.php file. This allows a single application to be used with multiple front controllers, each having its own config values.
    • Added $config['directory_trigger'] to the config file so that a controller sub-directory can be specified when running _GET strings instead of URI segments.
    • Added ability to set "Package" paths - specific paths where the Loader and Config classes should try to look first for a requested file. This allows distribution of sub-applications with their own libraries, models, config files, etc. in a single "package" directory. See the Loader class documentation for more details.
    • In-development code is now hosted at BitBucket. (Go grab your copy)
    • Removed the deprecated Validation Class. Read the rest of this entry »

Tags: , , ,

The perfect regular expression for email validation

Okey..! You are looking for "The perfect regular expression for email validation......" aaah..! That's great. I have come across an article as author has done lot of analysis to find out the perfect regular-expression and benchmark it against hundreds of test-cases.

My favorite is James Watts and Francisco Jose Martin Moreno's following one which uses preg_match:

/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i
Email Regular-Expression - Test-Case Run

Email Regular-Expression - Test-Case Run

Checkout this archived article here and let us know hat's your favorite regular-expression for email-validation?

Tags: , ,

Paying the bills.!