Monday, October 3, 2011

How to Force download multiple files in a zip archive using PHP

In this post, I’ll show you how can you download the multiples files in a zip archive using PHP. I’ve made a function in PHP where you’ve to pass the parameters the array of files to be zipped, the second parameter is file name as which zip archive file has to be downloaded and finally the path of files where files to be zipped are located.(assuming that they are all in same folder)

PHP function to download mutiple files in a zip archive

//function to zip and force download the files using PHP
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
//create the object
$zip = new ZipArchive();
//create the file and throw the error if unsuccessful
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}

//add each files of $file_name array to archive
foreach($file_names as $files)
{
$zip->addFile($file_path.$files,$files);
}
$zip->close();

//then send the headers to foce download the zip file
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
exit;
}


In the above PHP function, first of all the object of ZipArchive class. Remember that this library is bundled in PHP after the version of PHP 5.2 only.If you’re using the PHP version older than that one then you’ve to get it from PECL extension.

After that, we’ve tried to create the zip arhive with the open() function using the ZIPARCHIVE::CREATE flag.After successfully creating the archive, each files whose names are passed as array are added to zip file using addFile() function of ZipArchive() class.Then, this zip archive is closed using close() function of same class.

And, finally different headers are passed through PHP to force download the newly created zip file.
Example of Using Above PHP function

$file_names=array('test.php','test1.txt');
$archive_file_name='zipped.zip';
$file_path=dirname(__FILE__).'/';
zipFilesAndDownload($file_names,$archive_file_name,$file_path);

The above PHP function call is straighforward and after calling that function you’ll get the zip archive containing mutiple files passed as array in the first parameter of the function.

How to Change textbox value from dropdown list using Ajax and PHP

Yesterday Tarquin macey asked me how can we change the value of the textbox based using Ajax and PHP based on the changing value of the dropdown list.Today, I’ve come up with a solution from him.In this post, you’ll see how to get the currency code of a country from PHP using Ajax and this currency code will replace the value of textbox each time the dropdown list changes.

View Live Demo
Writing Code for changing textbox value from dropdown list using Ajax and PHP

After looking at the above demo, let’s start writing code for the changing the currency code value in the textbox form Ajax using PHP when you changes the country from the dropdown list.

HTML Code




As you can in the above code, there are two main components one dropdown list whose name is country and contains the list country in it.The JavaScript function getCurrencyCode() is called when user change value in the list. Note down the name and id of textbox which will have the currency code fetched from Ajax.

JavaScript Code for changing textbox value without refreshing the page

function getCurrencyCode(strURL)
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
// only if http status is "OK"
if (req.status == 200)
{
document.getElementById('cur_code').value=req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}

In the first line of the above code, the XMLHTTPRequest object is created using getXMLHTTP() function. To look at the the structure of this function, take a look at this old post change the value of dropdown list using Ajax and PHP . After checking the appropriate value of readystate(4 means completed) and status(200 means ok) property of XMLHTTPRequest object, the value of textbox is replaced with the returned value from PHP using Ajax . The response ,which is can be accessed via req.responseText property, is written to textbox via the value property of textbox.

PHP code for changing the value of textbox using Ajax and PHP



As you can see the above PHP code, it is fairly simple which just print the currency code value according to the name of country. The value which is in the echo statement is going to returned from PHP via Ajax.

how to Solve Floating point number precision lost problem in PHP

The problem of precision lost in floating point number in PHP haunted me for about 10 minutes yesterday but I quickly figured out the problem and solved it as I was aware of this problem. But, I would like to post here it here so that many others PHP programmers, who are not aware with this kind of problem ,get solution easily and don’t get stuck with it.

Calculation problem floating Point number in PHP

First of all, let me show you a small piece of example of the PHP code which I was working on.

$no_of_time=(0.60-0.55)*100;
var_dump($no_of_time); //displays float(5)
for($i=1;$i<=$no_of_time;$i++)
{
echo $i;
}

In the above code, the line var_dump($no_of_time); displays float(5). Ok, this is a expected result. But what about the loop, which runs just for 4 time. The above loop runs just for four time although var_dump () outputs that it is 5. Yes, it is 5 but with lost precision and that why never ever trust on the regular arithematic calculation with the floating point numbers in PHP. It always gives the wrong result because of the problem of lost precision. You can also see this warning in the PHP’s website.
Solving the problem of floating point precision in PHP

To solve this problem in floating point number, you need the function which calculates and support the calculation of floating point number of any precision. And, I recommend you to use BC Math functions, the binary calculator, of PHP for calculations of floating point number to prevent yourself from the problem of precision lost. But note down that, these functions always returns calculated output as string.Now, let’s try to solve the problem of above code rewrite it using bcsub and bcmul functions of PHP.

$no_of_time=bcmul(bcsub(0.60,0.55,2),100);
var_dump($no_of_time); //display string(1) "5"
for($i=1;$i<=$no_of_time;$i++)
{
echo $i;
}

Now the above, loop runs 5 times without any problem.

How did I reduce CPU overhead problem caused by MySql

From last day, We were having problem with a project which was shut down in the middle due to heavy traffic. As a technical manager, I was the person who to take charge over the project bring it down to the track. After doing few benchmark test, I came to know that the MySql access from a PHP file was creating the overhead to the CPU of the server.
Problem of CPU Overhead with MySql

Let me explain the problem clearly first,

We’re working on a website which was similar to http://www.swoopo.co.uk/ and as you can see clearly in that website the most recent data should be fetched form MySql database in each second. in the PHP page, which was being called from Ajax every second, had around 5 SQL queries to retrieve data from server.

First of all, I optimized that page reducing the 5 queries into single query by using left outer joins among 3 tables. And then, I did benchmark test by using Apache benchmark tool(ab) 50 request with concurrency of 50 with the following command.

ab -n 50 -c 50 http://xyz.com/ajax_page.php

And then in another SSH shell prompt, I run the top command to view the CPU usages parallelly.

I was still horrified that the CPU usages by mysql after 50 concurrent user was going out of control(100%) despite of optimized query. But many joins have been used in that single query and lots of data were there in those tables so the database overhead was high even though it was a single query.
How did I reduced the CPU overload drastically caused by MySql?

Now, the first challenge was to reduce the database access. It was clear that it was caused by concurrent database overhead in the PHP page which was being called in every second. Here is the simple steps what I did to reduce the database overhead.

1. I created another PHP file in which I’ve transferred the mysql query causing CPU overhead and called it from Cronjob.
2. Created a temporary table for storing the output given by PHP page called from CronJob.
3. Then, I scheduled the CronJob in every second, don’t tell me that CronJob can’t be run less than a minute, take a look at this post before saying this.And from each call, the output data was stored in the temporary table.
4. And, finally from the Ajax the a new PHP page was called which was only accessing the data from temporary table with single row.

I did the same benchmarking again to the newly made page(which is accessing data only from temporary table) and saw that CPU usages after the this process reduced drastically.

Saturday, October 1, 2011

"SYSBIZ TECHNOLOGIES" Recruits FRESHERS : BE/BTech : Trainee Programmer

Sysbiz Technologies is a subsidiary of BPI Technologies Inc., USA. a diversified offshore Business Solutions and IT Services provider. Our competencies lie in setting up dedicated offshore software development teams for product development, Application Maintenance and Testing, for Life sciences, Financial Services, Retail, Distribution, Manufacturing, Tele-communication and High Tech Industries. Our enterprise solutions are running in corporations around the world.
Our team is committed to quality and is made up of highly skilled professionals encompassing a broad range of technology disciplines. Using our proven Project Management and mature development methodology we help emerging software leaders bring superior products to market.
Our Technology services range from complete design and development of custom software applications to maintenance of existing applications by leveraging innovative technologies, techniques and assets.
Our Application development (AD) services are designed to address the business needs of our clients .We provide best-of-breed custom solutions enabling clients to achieve competitive advantage and significant cost savings.
We provide consulting, deliver expertise, advanced technologies and accelerators in solution design, development and integration.

Trainee Programmer/fresher

Job Description :
* Define, design, develop, and debug various components and features.
Work on requirements, functional specifications, and design specifications.
Work on interface definitions, code implementation and code debugging for generic code and/or port-specific code.
* Triage, troubleshoot, and resolve any problems found in integrating,
building, and testing of these components and features.
* Work on the corresponding functional unit tests, the associated test infrastructures, and related development environment scripts.

Desired Profile :
* Self-motivated individual contributor and good team player.
* Bachelor or higher degree in Computer Science or related disciplines.
* Good understanding of oops concept.
* Strong skills in design, development, debugging, and problem solving.
* Experience in Unix/Linux and/or Windows operating systems.

Contact Details :

Name: Sindhuja Ashok

Address:
Sysbiz Technologies Pvt Ltd
270,Lloyds Road Royapettah
Chennai, Tamilnadu, India 600014

Email : hr(at)sysbiz.net

Reference : TRN010/DEV011

"AVRIO INFOTECH" Recruits FRESHERS : BE/BTech/BCA Freshers

Avrio Infotech Private Limited

B.E Freshers

Job Description :

Job Description:
Candidate should have basic knowledge in .Net

Should have minimum 50% marks in academics.

Local Chennai candidates only need to apply

Desired Profile:
Must be able to effectively work with a team
Self motivated with competitive spirit
Self-starter with good interpersonal and communication skills
Strong problem analysis, problem-solving, analytical skills required

Maximum Experience: 0 - 1 years

Location: Chennai.

Education:
B.Tech/B.E. - Computers; BCA - Computers

"SANKAR SEALINGS" Recruitment : Junior Engineer - Hardware

Sankar Sealings Systems Pvt.Ltd

Sankar is one of the leading Automobile gasket manufacturers in the country and developing critical sealing solutions to the prestigious vehicle and engine manufacturers in the country. Sankar has JV with market leader in Japan and collaboration with German manufacturer for sealing materials. Sankar has one of the most advanced Gasket Research and development centre with state of art testing facilities which include engine testing facilites etc.

Junior Engineer - Hardware

Industry Type: Auto/Auto Ancillary
Role: System Admin
Functional Area: Systems, EDP, MIS

Job Description :
Take care of all desktop support operations, maintain troubleshoot and resolve all desktop related issues.
Installation of Hardware, software etc.

Contact Details :

Name: Smitha Sr Officer, HR

Address:
Sankar Sealings Systems PvtLtd
No 36, Ambattur Vanagaram Road Ayanambakkam
Chennai ,Tamilnadu, India 600001

Email : mhr(at)sankar.com

"MILLMORE TECH" Recruits FRESHERS : BE/BTech/MCA/MSc : Software Test Engineer

Right Source Consultancy

One of our leading company at Chennai

Company Name: Millmore Technology

Wanted Software Test Engineer

Job Description :

Qualification: BE/ MCA/ M.Sc (CS/IT)

Mandatory : Finished Software testing course, with Good communication skills.

Experience : 0-1 year

Post your resume to: aruna(at)millmoretech.com

Contact Details :
Name: K.Aruna
Right Source Consultancy

Email : rightsource1(at)rightsourcechennai.com

"SILICON HOUSE" Recruitment : Fresh Engineers /MSC Graduates

SiliconHouse.Net pvt Ltd.

siliconhouse.net private limited is a leading multinational software company since 1998.Its an ICANN(USA) accredited registrar .siliconhouse is an ISO9001-2000 Company serving clients across 90+ countries and provide excellent support n service.

MNC software -Female Fresh Engineers /MSC Graduates apply

Experience: 0 - 2 Years
Compensation: Rupees 2,00,000
fresh female graduates will be provided highest salary according to their qualifications

Job Description :
Software Multinational requires female fresh engineers to work as a network engineer n provide technical support for webhosting and domains. B.E(CSE/IT /ECE/EEE/E&I/CIVIL/BIO) n other non IT graduates are preferred. excellent salary will be provided.

Desired Profile :
2010/2011-Female fresh engineering graduates from the branch of CSE/IT/ECE, EEE, E&I, CIVIL, BIO n other non IT branches are most preferred and will be given first preference. Must have good communication skills must willing to relocate to adyar, Chennai.

Contact Details :

Name: Hr manager
SiliconHouse.Net pvt Ltd

Email : hr(at)siliconhouse.co.in

VLC for Android Devices

Bangalore: VLC is most widely utilized media player for Linux, Windows and Mac computer across the globe and now it's time for android mobile operating system to make full use of it.

The player was supposed to launch in early 2011 but due to some technical difficulties, the app got delayed.

The developer of VLC said, there are two builds available of VLC for Android, known as NEON and NONEON. The difference is in the processor type. Because VLC for Android makes use of the NDK (Native Development Kit), it is compiling native-level binaries that will only work on the processor class for which they were designed. This means that the same build will not work across all devices.


This VLC player is compatible with devices running version 2.1 and above.

Continuous Monitoring Can Help Avoid Cyber Attacks

BANGALORE: The only realistic way to combat modern cyber fraud methods is continuous monitoring, with comprehensive oversight of user activity, infrastructure events and banking transactions, a senior official at Hewlett Packard's security solutions subsidiary Arcsight said.

Although cyber-war and cyber-espionage have been in the headlines in recent years, cyber-crime directed at financial institutions and their clients continues to wreak the real havoc on the Internet, Arcsight Regional Director Loke Yeow Wong said.

"Financial fraud cases won't astonish casual observers the same way news of Stuxnet malware infiltrating computer systems to send uranium-enrichment centrifuges spinning out of control does, but financially motivated cyber-crime affects far more people, while enriching immoral people around the world," he said.

The current approach to fraud monitoring has three primary blind spots, he said.

Most of the services pushed by financial firms online have opened avenues for fraudsters to exploit vulnerabilities across banking transaction types, Wong said.

Moreover, financial institutions rarely correlate data between their information security and fraud teams, creating another substantial blind spot, he said.

In addition, he noted that fraud and information security teams alike typically do not perform sophisticated monitoring of privileged accounts.

At present, most banks deal with fraud through dedicated teams for different financial products, such as electronic (ACH) transfers, web banking and wire transfers.

"This specialised model worked well for a long time, as fraud methods were largely specific to one type of transaction," he said.

However, financial services firms should now work toward a comprehensive view of enterprise risk, including both fraud and information security monitoring, he said.

Indian Navy Installs Anti-Piracy Device

MUMBAI: With piracy in the Gulf of Aden and off the Somali reaching alarming proportions, the Indian Navy, which has been in action against the brigands for the last three years, has begun installing a device on its warships that literally scares the hell out of hostile elements.

The Long Range Acoustic Device (LRAD), as it is called, shouts, threatens and warns in a variety of languages.

The device has been seen on the destroyer INS Mysore and on INS Satpura, the Navy's second indegenously built stealth frigate that was commissioned recently.

Sources told India Strategic defence magazine (www.indiastrategic.in) that the system is being installed on most of the naval ships as it can automatically translate warnings into several languages, depending upon the choice of the captain and the region his vessel is sailing in.

LRAD is a non-lethal system but, if required, can injure the targeted personnel with literally ear-splitting, very high decibel tones and noise beams of up to 150 dBSPL. In some cases however, people near the system too can suffer permanent hearing disability.

The Indian Navy has acquired the system from a US firm, which holds its patent.

The Indian Navy has a policy not to inflict violent attacks on the pirates unless they fire or attack an Indian ship. Accordingly, said the sources, it was considered prudent to install the LRAD not only because it can cause intense pain without killing but also because it can translate warnings automatically into 10 or more languages.

The system is a regular feature on most US and western naval ships as well as those of China and the Gulf countries operating in the Gulf of Aden area.

US ships do not allow unknown vessels to come near them, and if they do not respond to warnings over radio, the LRAD is used to warn them three km away with directed sound and voice beams. Hostile vessels, of course, are engaged immediately either through patrol boats or helicopters.

LRAD was, in fact, developed after the terror attack on the USS Cole in Yemen in 2000 when a hostile vessel rammed into the warship, damaging it and killing many naval personnnel.

According to the manufacturer, the system is portable, comes in many sizes and requirements, and can be installed on any platform, from police vehicles to strategic buildings and ships.

Police forces in the US and many countries use it for crowd control.

IT Companies Jittery on Sluggish U.S. Growth

NEW DELHI: Major IT and BPO companies in the country are jittery amid fears of another economic slump in the U.S. and a debt crisis in Europe, according to industry body Assocham.

About 55 percent respondents said that while the sector is unfazed from S&P's downgrade of the U.S. credit rating and that the slowdown is temporary, it would surely hamper the hiring activity across the sector.

"Downgrade of U.S. debt rating and debt crisis in Euro zone will impact recruitments in the Indian IT sector and hiring is expected to go down by about 30 percent during the course of next few months," Assocham Secretary General D S Rawat said.

The downgrade by credit ratings agency Standard & Poor's in August had triggered concerns that the $ 60 billion software services industry - which gets more than 60 percent revenues from the US market would be hit.

IT industry body Nasscom, along with top players, had however, exuded confidence that the sector will "sail through" the crisis.

Assocham interacted with about 140 representatives, directors, CEOs, CFOs, Chairmen and MDs of companies offering IT/ITes and BPO, BTO, KPO services in various domains like pharmaceuticals, Banking, Financial Services and Insurance, auto, FMCG and manufacturing.

The study was carried out across Ahmedabad, Bangalore, Chandigarh, Chennai, National Capital Region (Gurgaon and Noida), Hyderabad and Pune.

"The U.S. and Europe account for over 80 percent of India's $ 60 billion IT industry and macro-economic uncertainty in these parts of the world are bound to make the market gloomy," Rawat said.

About 25 percent of respondents said the current round of global economic crisis won't have much of an impact on India, considering the strong domestic demand of goods and services together with their exposure to other avenues like Asia-Pacific and other parts of the world.

Nearly 20 percent of the respondents said Indian firms may report sluggish business during the course of next few months due to the slowdown.

Besides, the industry is already reeling under high interest costs, high inflation and the stock market is also in a sombre mood, the study added.

Apart from slowdown in foreign direct investment (FDI), growth in exports and domestic private consumption might also slump, Rawat said.

Hazare Turns Blogger; Joins Facebook, Twitter

Mumbai: Anti-corruption crusader Anna Hazare seems set to take the virtual world by storm. He Thursday became a blogger and even joined social networking sites Facebook and Twitter.

The blog, with posts in English, Hindi and Marathi, is titled "Anna Hazare Says" and can be accessed on: https://annahazaresays.wordpress.com.
Hazare Turns Blogger; Joins Facebook, Twitter


In his inaugural post, Hazare wrote: "It is after a long time that I am directly communicating with you. Henceforth, it is from this blog that I will be constantly in touch with you."

"We started a movement demanding that Janlokpal Bill be passed in India and slowly the crusade spearheaded into a full-fledged non-violent revolution spilling on to the Ramlila grounds," he added.

The activist said he found the support of the people and his young friends as overwhelming as they came forward from every corner of the country and their cries awakened India from its deep slumber.

"Their cries not only shook the very roots of our country but people from world over who had fallen prey to injustice, corruption took active part in the movement.

"The entire movement was infectious. This was the beginning of a revolution. It was the beginning of India's second struggle for independence," Hazare said.

The 74-year old leader pointed out that parliament gave an assurance that it would put forward some of the demands from the Jan Lokpal Bill and get them approved.

"But assurance doesn't necessarily mean law. A bigger fight awaits us," Hazare urged.

The activist warned that the movement still "has a long way to go and very soon it will acquire a non-violent, but intense flavour of a nation-wide revolution".

"To enable a one-to-one conversation with you I will soon embark on my journey throughout India. I will address problems faced by people at every step of life... Interactive communication on this blog will start very soon. You can share your queries, problems thoughts and emotions with me," Hazare appealed.

He also wrote on his blog that he has joined Facebook and Twitter.