Category: Tutorials

Tutorial: How to Create a Zip File with PHP / MySQL  

Posted at 6:44 am in PHP Functions,Programming,Tutorials

Recently I added a function to a CMS that I have been evolving to meet the needs of ereads.com. I needed to allow users to select items (in this case ebooks) from the system and then export files that are attached to the books. So lets get started!

What is a Zip File?

“Zip files (.zip or .zipx) are single files, sometimes called “archives”, that contain one or more compressed files. Zip files make it easy to keep related files together and make transporting, e-mailing, downloading and storing data and software faster and more efficient. The Zip format is the most popular compression format used in the Windows environment, and WinZip is the most popular compression utility. ” – winzip.com



What you need to know:
Arrays, MySQL, FTP file permissions

First:

First you need to set up the tables. This is a simplified way of how to do it:

Table Name: Books

id title author description filename
1 The great book TA baron Sr. blah blah blah greatbook.pdf
2 The greater book TA baron Jr. blah blah blah greaterbook.pdf
3 The greatest book TA baron III blah blah blah greatestbook.pdf

Table Name: Book_Cart

id bookid username
1 2 anthony
2 3 anthony

Lets assume:

- that you have all the zip files in a folder called “files”.
- that you already have a way for users to add books to the cart.
- that you have a the username of the person creating the zip stored in a session variable

Second:

You need to setup a folder for the zip file to be created. Make sure that the permissions are set to 777 on that folder. in this example we will pretend the zip folder is called “zips”.

Third:

Here is the zip function:

function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;

//close the zip -- done!
$zip->close();

//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}

You can place this code at the top of the folder or you can stick it inside your functions include file. Now we need to run some queries to add the requested files into a zip. In the following example the function above with be included as “zip_function.php”.

include "zip_function.php";
include "database_connect_file.php";

$username = $_SESSION['username'];
$locationFilename = "zips/Book_export.zip";

$get_all = "SELECT * FROM Book_Cart WHERE username='$username'";
$rstall = mysql_query($get_all);
$export_num = mysql_num_rows($rstall);
while ($r1 = mysql_fetch_assoc($rstall)) {
$bookid = $r1['bookid'];

$qry4 = "SELECT * FROM Books WHERE id LIKE '$bookid'";
$result4 = mysql_query($qry4);

while ($row4 = mysql_fetch_assoc($result4)) {
$filename = $row4['filename'];
$files[]= "files/$filename";
}
}

create_zip($files, $locationFilename, true);
echo '<a href="'.$locationFilename.'"> Click here to download PDFs </a><br><br>';

And that should do it. All the code I provided works on mediatemple.net webservers with PHP safe- mode turned off. I found that some other servers don’t allow the creation of zip files. However if the server is set up for it, this should work.

If you have any questions, post them in comments and I will do my best to answer them.

-AD

Written by Anthony Damasco on May 13th, 2010   8 comments  

Sponsor:

What should you charge for web development?  

Posted at 8:25 am in Business,Technology,Tutorials

Are you new to charging for your services? When is it okay to charge more? How can some developers get away with charging $150/hour? Let me try my best to answer some of these questions. I’ve been freelancing since 2002, while I am not an expert on this, I do have quite a bit of experience on this matter. Here is how I determine what to charge a client.

1. Determining your hourly rate

Here is a good way to figure it out.

Find some job listings as a web developer on monster.com or careerbuilder.com. Something that you actually qualify for. Get a few listings together of jobs that you would be a fit for. Look at how much each position makes a year. Find a good average out of those numbers. Once you have that number try this formula:

Your Skill Set Salary / 52 weeks / 40 hours a week  = Starting Hourly
Since you do more than just development for a client (you handle the business side as well) then we add %25 on top.
Starting Hourly + (Starting hourly * 0.25) = Your suggested rate

Example: If your salary fit is 60,000 a year then the formula would look like this:
60,000 / 52 /40 =  $28.84
25% of 28.84 = $7.21
$28.84 + 7.21 = 36.05suggested hourly rate

Make sure that you are honest with this part so that you can remain competitive against other freelancers of the same skill level.

2. Taxes!

Yes the first thing I think about when I charge for service is how much does Uncle Sam get. Well if you don’t know, get ready for this: Nearly half (roughly 40%). They do this because freelancers can write off a lot of different things against how much they owe in taxes.

My strategy is to put half of whatever I make as a freelancer in a savings account. At the end of the year (or quarter depending on when you pay) you can use the money in your savings account combined with a list of write offs. Take these to your accountant and have them work their magic. If you have a lot of write offs you should end up keeping a chunk of what you have saved for taxes. That can be considered your personal freelance tax return and you can keep that money for yourself.

Now with the “half your money goes to taxes” mentality when you would have charged $30 per hour you now see that as making 15 an hour after taxes.

3. Don’t Guess, You May Lose Money

In the beginning of my freelance career I would often set a price for a website. For example in 2003 my rate was $600 a website. That included design. This is how those projects went down most of the time.

Project will span 2-3 weeks:
a. 2 hours of phone calls with client
b. 5 hours of design
c. 3 hours of back and forth emails about the design options
d. 8 hours of HTML / CSS development
e. 6 hours of changes

So that’s:
600 / 24(hours) / 2(taxes) = $12.50 per hour.
My goal was $30.00 an hour.

By guessing, I ended up working very hard and using a skill set that I went to school for. I would have earned the same as a clerk. ( no offense to any clerks out there )

4. How to Charge, the correct way.

Here is how I charge my clients.

First, I find out as much as I can about the project:

Features - List out all the features you will need to program/install through out the entire website.
Database - Find out of the client can supply any data-entry or spreadsheets full of data that the project might need.
Design -  How long am I going to spend designing? How many rounds of revisions will be allowed?
Programming - Try your best to estimate how long it would take to program each feature one at a time and list it out.
Responsibility - What is the client responsible for delivering to you. If they are late will it hold up the project. If they have a lot of content that they still have yet to create, it’s sometimes good to charge extra to keep the project alive. Set deadlines for the client to deliver content. If the client misses it’s deadline it should add days to your deadline.
Deadline - Is the client going to set a tight deadline? Is the deadline open ended?
Additional talent – Is the project to big for one person? Are you going to have to hire additional help? Get estimates from other developers prior to giving client a cost.
Misc Costs- Hosting costs, domain names, turnkey software.

So here is my formula after I figure all the above out.

(Design hours * Hourly rate)
(Database hours * Hourly rate) (leaving room for possible data entry)
+ (Programming hours * Hourly rate)
——————————————-
Total Labor Cost
+ Taxes (Total labor * 0.35)
——————————————-
Total and Taxes
Additional talent
+ Misc Costs
——————————————-
Client Estimate



Example: Let’s see what I should have charged for the website project in 2003:

(5 * 30) 150
(5 * 30) 150
+ (14 * 30) 420
——————————————-
720
+ Taxes (720 * 0.35) 252
——————————————-
972
Additional talent ($0)
+ Misc Costs ($103 for hosting
——————————————-
$1075



By using this formula I found out that I should have charged $1075 instead of the $600 used in my last example.

5. Conclusion

There are many ways to figure this out, however my formulas have worked well for me. As long as you are honest with the hours you are working, you will remain competitive and fair. If anyone would like to share their ideas or opinions, post them in the comments section.

-AD

Written by Anthony Damasco on April 20th, 2010   4 comments  

PHP Function: remove special characters from post data  

Posted at 6:33 am in PHP Functions,Programming,Tutorials

Since I began programming 6 years ago I always had trouble with collecting data from forms. Users tend to copy and paste data into them, capturing special characters in the process. The special chars then end up in the mysql data as some random garbage, then it appears on the website as weird symbols.

A while back I asked a programmer friend of mine if he had a function that would help out with this. He did! I’ve been using it with the last 9 applications that I built, and it works every time.

Here is the function code:

if (!function_exists('cleanText')) {

function cleanText($str){

$str = str_replace("Ñ" ,"&#209;", $str);
//$str =  preg_replace('/Ñ/g',"|&#209;|", $str);

//echo "Text BEGIN ".$str."  --- ".bin2hex ("Ñ")."\n<BR>";     // d1

/*
for($i = 0 ; $i < strlen($str) ; $i++){
echo "".$str{$i}."  - ". bin2hex ( $str{$i})."<BR>";
}
*/

$str = str_replace("ñ" ,"&#241;", $str);
$str = str_replace("ñ" ,"&#241;", $str);
$str = str_replace("Á","&#193;", $str);
$str = str_replace("á","&#225;", $str);
$str = str_replace("É","&#201;", $str);
$str = str_replace("é","&#233;", $str);

$str = str_replace("ú","&#250;", $str);

$str = str_replace("ù","&#249;", $str);
$str = str_replace("Í","&#205;", $str);
$str = str_replace("í","&#237;", $str);
$str = str_replace("Ó","&#211;", $str);
$str = str_replace("ó","&#243;", $str);
$str = str_replace("“","&#8220;", $str);

$str = str_replace("”","&#8221;", $str);

$str = str_replace("‘","&#8216;", $str);
$str = str_replace("’","&#8217;", $str);
$str = str_replace("—","&#8212;", $str);

$str = str_replace("–","&#8211;", $str);
$str = str_replace("™","&trade;", $str);
$str = str_replace("ü","&#252;", $str);
$str = str_replace("Ü","&#220;", $str);
$str = str_replace("Ê","&#202;", $str);
$str = str_replace("ê","&#238;", $str);
$str = str_replace("Ç","&#199;", $str);
$str = str_replace("ç","&#231;", $str);
$str = str_replace("È","&#200;", $str);
$str = str_replace("è","&#232;", $str);
$str = str_replace("•","&#149;" , $str);

return $str;

}
}

?>

Stick this in code in a page called “functions.php” and include it at the top of the page.  It uses str_replace to replace special characters. You can add and remove characters easily by coping $str = str_replace(“•”,”&#149;” , $str); and just replacing the character and the code when necessary.

Here’s a snip of it in action

HMTL Form:

<form method="post" action="clean_data.php">
<input type="text" name="textfield">
<input name="submit" type="submit" />
</form>
clean_data.php:
<?php

include "includes/functions.php";

// Get post Data from form
$textfield = $_POST["textfield"];

// Clean Data
$textfield= cleanText($textfield);

echo $textfield;

?>

And that’s all there is to it. If you have any questions, post them in the comments of this post.

-AD

List of Special Characters

Written by Anthony Damasco on March 11th, 2010   3 comments  

Intro to PHP: 01 “the echo”  

Posted at 4:20 pm in Programming,Technology,Tutorials

If your just getting into PHP you first need to know how it works. PHP actually creates HTML on the server side before the user loads the page. PHP is in charge of checking for arguments, getting data from databases and sending emails. PHP is also capable of much more if modules are installed on the server.

Getting your feet wet:

What you need to know:

  • HTML
  • FTP
  • An understanding of how web servers work.

PHP lets us do things that HTML does not. Let’s go through some basics.

<?php

echo “some stuff!”;

?>

To tell the webserver that you are using PHP you need to start with a <?php. You follow it with your code, then close it with ?>. Using echo tells PHP that we want to spit something into the HTML. You can echo anything. Javascripts, style sheets, anchor tags, and anything else that is valid in HTML.

what makes this important is the arguments that you use in PHP.

<?php

if ($this_variable==”HAPPY”) {

echo ‘<link rel=”stylesheet” type=”text/css” href=”css/SUPER_HAPPY_STYLE.css”>’;

}

else {

echo ‘<link rel=”stylesheet” type=”text/css” href=”css/SUPER_SADFACE_STYLE.css”>’;

}

?>

What the argument above is doing is checking a variable, and if it’s set to “Happy” then it will tell the page to use the happy style sheet, if its not, set it to the sad style sheet. This little snip of code could be used to let your visitors change the websites theme. I’ll cover variables next time!

-AD

More on Echo

Print vs Echo

Written by Anthony Damasco on March 9th, 2010   4 comments  


Facebook
Follow damasconet on Twitter