Archive for category 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: , , ,

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: , , ,

Smarty 3.0 is almost here..!

Smarty PHP Template Engine

Smarty PHP Template Engine

There could be some or lot of us in PHP World who might have not heard about Smarty..! Yes, Smarty is the PHP Template Engine since ages. Why Ages......? some of you might ask.. but it is there since long... really long, even before we started hearing about these PHP Frameworks.

I have been using Smarty in some of my projects and as part of my daily usage component I have been following up on the Smarty Website. If you are like me you might have noticed that it has been more than one year (8 beta and 3 rc releases) that Smarty 3.0 is almost there and still there is no final release.

May be it's indication or beginning of the announcement of death of Only Template Engine PHP Frameworks or something else. Somehow community does not seems to be active or founders or whatever. Now a days many MVC frameworks are choice of developers and they either have in-built template-engine or no-template-engine or plug-in-support for template engines.

No matter what Smarty 3.0 claims to be loaded with following features: Read the rest of this entry »

Tags: ,

Upgrading to PHP 5.3..! – are you sure?

If you are planning to upgrade to PHP 5.3 from PHP 5.2.x then you must think twice before you really do it. There are few things you should take care of. Recently last week I tried upgrading one of the web-server to PHP 5.3 from PHP 5.2.9 and it was not a good idea which I came to know later on.

It is not only about deprecated functions which are creating Warnings or Notices but TCPDF library for generating PDF has created some wired problems due to which I have to roll back to the older version, as it was one of the crucial functionality of the application. It was not a planned version upgrade but it was a server migration and on the fly I tried upgrading PHP version also.

There are many functions and some of php.ini parameters which are deprecated, for complete list please refer http://www.php.net/manual/de/migration53.deprecated.php.

You can’t pass parameter while overriding “magic methods”; so if you ever had your __toString() method overridden with __toString($device = ‘SCREEN’) then it won’t work with PHP5.3. Other than that date_default_timezone() or similar timezone setup function also had some problems.

// This won't work with PHP5.3 and will work with 5.x
public function __tostring($device = "SCREEN")
{ ... }
 
// This will work with PHP5.3 and 5.x
public function __tostring()
{ ... }

So crux is if your applications are not ready for PHP5.3 it is not wise decision to upgrade and if you have to upgrade we should make sure to test whole application and all functionalities as with large development teams sometimes you never know who has used what all the time.

Paying the bills.!