How to turn on error reporting in PHP
If you are on a server that does not show you your PHP script's errors (you are getting a blank white page), paste this code at the top of your script:
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');
ini_set('display_startup_errors', 'On');
10 Steps to Success in PHP Consulting
I found the following article while reading Slashdot a few years ago. It has disappeared from the web. I do not know who the author is, but it is such a good article that I will post it here.
Read on to learn:
- Ten things PHP programmers should be doing
- How to filter customers
- Some other insightful/funny things about PHP
> I am a freelance programmer in Spain where most of my clients are small
> businesses.
Small business really benefits
from PHP because of the low cost in implementing any situation, when
you have a good programmer/DBA.
> In general they are totally clueless about good programming
> practices vs. bad ones, so indeed the strength of the projects and
> reputation are what weigh the most.
Tech for
the tech, simplicity for all else. It's quite possible to simply
explain good programming practices to anyone. You know, programming is
only about interpretation, and how we explain ourselves is what makes
it possible for people to understand. How we explain ourselves is what
makes it possible for the whole system to understand, and respond
better to changes we implement.
For me, good programming is about:
1.
KISS : the simple solution is always best. Break
everything down into the smallest possible unit, or lowest common
denominator. Ahh math. If something is used twice, it's on its own --
if it's used once, it can be rolled into the code.
2.
Tight : the tighter the system, the more normalized the
code is. A class that is very complicated and solves a bunch of
problems at once is *less* effective than 50 functions that can each
perform a specific task. I'm not at all against OOP, but I have found
that in PHP, breaking down each action into a function is a real time
saver -- and a systems resources saver.
3.
Base64 is your friend. All your text should be saved as
gz_deflate first, and then base64 encoded. Stuff them all into blob
fields, or medium blobs if you have some megs going in. This literally
removes any problems with quotes, and it protects the admins from
database scripts that can seriously damage the database if executed
during phpMyAdmin sessions.
4.
Purify : write a few neat purification functions and use them on incoming data. Don't let garbage in.
Don't accept HTML from your users. Accept UBB, and parse it so you can write your own XHTML.
5.
Register your expected variables and
crash on unexpected vars.
Not only does this keep your system neat as can be, it also prevents
people from hacking in because they can't send bogus vars to break your
scripts. It makes cross-site-scripting (
XSS
)
very difficult when used with a good set of purifying scripts. You can
also track requests for bogus vars to ban users who request them. A
simple foreach call to the $_REQUEST var will help check and verify
each $key ie: foreach($_REQUEST as $key=>$val){// do your tests}
6.
Log every pageview : create a table for logging each
page viewed. This will protect you from bad users, but it will also
protect you from your customers (or at least your bad willed customers,
if you haven't weeded them out yet). If you are hired to do a job and
your user account is the *only* one with *any* activity -- then you
have evidence to support the fact that you did not have proper guidance
making the system if there is ever a lawsuit or refusal of payment. As
an added bonus, tracking each pageview will also give you the heads up
when a boss is looking at a particular section of the site, and perhaps
tell you why. If they are going into parts of the system out of
curiosity -- it will show in the logs -- but if they are trying to look
at parts that aren't maybe ready yet, you will know immediately and you
can let them know that such-and-such system is still being worked on.
Tracking page views also helps debugging greatly.
7.
Code as you go : don't take entire systems offline
unless you absolutely have to. If you can set up a development area, it
will speed up your efforts in building a php system. If you can't do
this for some reason, it's a good sign that the customer is very
disorganized and maybe that could be an indication that you need to
find another customer. If you find yourself in the position where you
have to code as you go but you have to do it in a realtime environment
where the public will be viewing parts of your site -- use the isset
function and an if statement like so:
if(isset($_REQUEST['test56'])){
// execute function calls and some code if you like
}
Now you can just add a little thing on the URL and it will show your test:
google.com/?test56=1
8.
Break down your table structures into the same parts : my tables all have certain structures:
- record id : primary key, int, autoincrement
- date : varchar 64 (unix timestamp using the time() function) 64 bytes to prevent the UNIX date bug, down the road.
- status : tinyint default 0, set to 1 if the record is active, 2 if it's deleted, 0 if it's pending
- title: varchar 128 : purify this to apply ENT_QUOTES
- abstract: blob : gzdeflated, base64 data using my custom function pak()
- body: mediumblob : same as abstract
9.
Never be afraid of a total rewrite : part of the
evolving code is shedding skin and to do it, you have to always rethink
the way you do things. Being afraid of a total rewrite is always bad,
even if it's going to cost money. The costs of bad code and system
practices are always much heavier than the cost of regular maintenance
-- and code evolution is maintenance. Code is organic.
10.
Be selective : Use smart features of PHP and ignore
stupid ones. PHP has a lot of features, and many of them are useful,
but many of them have no business being in your code. Be critical of
what you are putting in.
- If you are using the print language construct, then use it everywhere instead of echo. If you are using echo, use it everywhere.
- Only use double quotes when you absolutely have to. Use singe apostrophes around text.
- Use the call by reference feature (ie: function
thisfn(&$this){print $this;}) because you can change the vars
content on a global scale if you want, but also you save a lot of
memory passing large chunks of data because only the resource id goes
into the function and not a whole copy of the data. It's just smarter.
- Never call a function like this: thisfn(&$this); because PHP
used to support this, but it's deprecated now. Put your callbyref &
in the function definition, not when you call it.
- Use the GD2 library whenever you can instead of the old GD functions. Big resource saver.
- Destroy all images after they are used. unset() big vars.
Be selective also means,
choose your customers wisely. In a long-term job, you can't choose your customers.
But for little contracts here and there, you certainly can choose who you work for.
A bad customer can cost you bigtime with reputation, time and money.
They can make it impossible to find future work, or they can drain you
emotionally or physically. If you have to work with a difficult
customer, that's okay, but you must protect yourself. Finding a bad
customer is like finding a mine when you are going berry picking. Watch
out. If you are in a tight spot and you have to pick up a bad customer,
please handle them with care or they will explode in your face.
Each person you deal with is going to be one of these to some
extent, and how you handle them is going to change the outcome of the
business relationship.
Answer these questions about each potential customer, or even your managers or coworkers:
1. Are you stupid?
2. Are you evil natured?
3. Are you disorganized?
4. Are you unsuccessful?
5. Do you have no budget?
6. Are you a stinking liar? Weasel?
7. Are you a know it all?
8. Are you a control freak?
9. Do you have mental problems?
10. Are you superstitious?
1.
Stupid people will cause your project to fail. By this,
I don't mean computer-smarts. This is general intelligence and you
can't have too much of it. It's okay to have a really smart person who
is computer-illiterate; they generally aren't a problem because they
can understand someone who is reasoning with them. A really stupid
person will do the same thing even when it's not working and that's why
you want to be really careful of stupid people. Repeating something
over and over that is not working will kill a project.
A good way to tell if someone is stupid or not is to tell them a
little story about yourself and see if they understand you. Frequent
spelling mistakes are not necessarily a good way to tell if someone is
stupid. Some stupid people are meticulous at covering it up -- I mean,
it's their livelihood so they have to be cautious. Overcautious people
might be stupid. Tell them a joke that makes no sense -- if they laugh,
they might be stupid. If they laugh and say that makes no sense, they
are good hearted. If they look at you like you're on mars, then they
are smart but possibly bad natured.
2.
Evil people will screw you over and love it -- it's part of their plan and you can't change their nature.
The biggest mistake people make is thinking they can outwit or change
an evil person. It's impossible, and as futile as arguing on the
internet.
To find out if someone is evil, you will have to talk to other
people around them. Examine their policies. Examine how they deal with
difficulties. Look past marketing propaganda and get to the roots. Evil
people will stop you from getting to the truth about anything.
Chances are, if you hear someone say something mean spirited, they
are either evil or disgruntled, and dealing with either will render the
same result.
Evil people are always thinking about being compensated and they
will sue you if they can, even if they don't deserve it. They might
leave you holding the bag on some bad business deal. Usually the best
way to see if someone is evil is to notice how other people react to
them. There are degrees of evil, but any amount of it will cause you
some serious problems. Obviously in an email-only business relationship
this kind of customer filtering is tough. But it's not impossible. Evil
people are often disguised as zealous do-gooders, but sometimes they
come equipped with Satanic garb and scythes.
3.
Disorganized people will not pay you on time. By far
the worst of all offenders, the disorganized customer is a time killer.
Your budget for $1k will dwindle in the first week and you'll have
nothing to show for it. You'll be promised something but a week later
the customer will say they forgot. Disorganized people actually do
forget things -- all the time. And this is why you keep a verbose log
record when you are forced to deal with these people. The sad truth is
-- only bankers and programmers are organized. Okay librarians too. But
that's pretty much about it. Everyone else is a shade of
disorganized.
The way to handle disorganized people is to have a verbose set of terms
and conditions and refuse to do any work for them until they sign on
the dotted line. Even then, it may be smart to have them work with you
on retainer only.
Do not enter an escrow agreement with a disorganized customer.
You'll never see the money and neither will they, so it's lose/lose.
Prepaid in full is the way to go, so you can be sure to live up to your
part of the bargain. A disorganized customer may offer you half now and
half on completion -- don't take it. That's a sure fire way to give
them 50% off when they refuse to pay you for your work. If the
disorganized customer has any evil in them, and many do, they will use
the final payment as a carrot on a stick and force you to chase it.
A good way to spot someone who is disorganized is in the way they
write. Email is perfect for this. Notice their word selection -- if
they only use really small words it could be because they are too lazy
to show any flair in language. Notice their spelling and grammar too.
Lazy and disorganized people are pretty much the same to a programmer.
If you find a customer who is disorganized and rich, prepare all
your paperwork in advance and keep everything simple. Rich,
disorganized people always pay their bills, eventually, and they
actually make good customers, because they are too afraid of losing
everything to a lawsuit.
Poor, disorganized customers make lousy customers.
4.
Losers have bad karma that will rub off on you. You can tell if someone is unsuccessful in a
New York minute,
if you look them in the eye and read them. If they don't look like a
fierce competitor or a very happy person, they might be a loser. People
who are too happy are deluded optimists and that can make your project
fail. Winners are competitive people, and they always have a strategy
to win. Winners have a way with people and a way with projects that
make projects win. Losers just hope everything will work out and they
sit back and watch it fail, doing nothing to make it win. Having a
customer who is a loser is a really bad thing for any programmer
because you can't possibly control what is going to happen to you or
your systems if you work for these types of people. You could find
yourself sued due to the incompetence of an unsuccessful customer.
Spell out your terms and conditions, just in case. Get it in writing.
You can't always tell if someone is a loser until after you've
worked with them for a while. Have an exit clause in case you need out.
Winners are not afraid of exit clauses because they aren't used to
people wanting to be rid of them.
Your reputation will become tarnished if you work for losers. Scott
Adams says that if you head up a project that fails, you can be seen as
having experience, but in my estimation this somehow does not apply to
programmers, due to fears of computer-illiterate bosses. Any failures
in a programmer's career stay with them as utter nuisances. Avoid
failure at all cost in this game. Always write postmortems on your
projects that succeed or fail, just in case you need to be reminded of
how to do it again, or how not to do it again.
5.
Customers without a budget might be losers, might be disorganized, might have no money, might be afraid of programmers, might... etc.
This is a nice question to ask in the first two minutes. If you don't
get a solid answer, tell them that you need to know this answer before
you agree to proceed. They might try and tell you that you are trying
to weasel them out of their money, but you should then insist that they
perform a code audit on your work using an independent third party, if
it's in the budget. Most programmers wouldn't want this, but I have
never felt it was a bad thing because my code is solid and I like
hearing ways to improve it.
There is no excuse for a customer not to reveal how much they want
to spend on a project. Tell them it affects the scope of your proposal
and if they can't inform you of a budget, you can't offer a proposal.
This protects you, but the time it takes to get the budget figure might
help you identify someone who is one of the other types of bad
customers.
6.
Stinking weasels (liars) will tell you anything to get
you to work for them for free. There is no budget, even if they say you
will earn $100k/yr, they are lying to you. They might tell you they
will call you and "forget". You will be treated very poorly by a weasel
customer, because that's how they treat everyone. You can spot a weasel
right away if they are promising anything and fail to deliver on said
promise. Have strict rules of conduct when approaching weasels, because
without it, you are defenseless. If you run into an alpha-weasel, none
of your defenses will hold, so you must adopt a strategy of utter
avoidance.
To learn more about how to deal with Weasels, read Scott Adam's
The Way of the Weasel
.
7.
Know-it-all customers will always question your methods and struggle to squeeze the very last dime out of you.
They might pay you on time, but only after they have audited you
themselves, and made all sorts of insane requests. Avoid these types of
people if you can. If you can't, the only way to defend against them is
to document everything and be religious about doing so. Have indexes
and page numbers memorized for impromptu phone meetings, so you can
refer to them quickly. The speed at which you refer to documentation is
the only litmus test to the know-it-all, not the actual degree of fact.
The faster you can shoot down their nonsense, the less of a footing
they will get over you and your project. Do not let these people become
entrenched on your projects. If you have to work with them, give them
large volumes of work to do and keep them out of meetings. If you have
to be in a meeting with a know-it-all, just remain quiet and wait until
they are finished speaking before you jump in. They count the number of
times someone tries to interject, and multiply it by the total minutes
of the meeting to arrive at the length of time they will speak, so the
less you interject, the sooner you will get your turn to remind others
of standards compliance or whatever else you want to discuss.
The funny thing about know-it-alls is that no matter what they say,
the only thing that matters is what is in writing. Divert them to the
phone instead of email because then you can't be held accountable for
the free internal non-SSL credit card module they promised the
customer, and that you agreed to in writing. Your terms and conditions
will help you around this type of person.
8.
Control freaks are like know-it-alls, but they actually know things.
The problem with control freaks is that you can't make any progress
without them micromanaging you back to square one. They want every
communication routed through them. They want five-hundred pages of
documentation for one page of code. They live in fear. You don't need
to avoid control freaks, you just have to relinquish total control to
them, and hold them accountable for it. You have to document everything
better when you are around them. If you have a control freak customer,
never agree to module pricing or you will be working until retirement
to satisfy them. Get paid daily at a specified rate, regardless of how
many hours you work. Specify that the maximum number of hours is 8 and
if they exceed it, you get paid double for the day. Specify a maximum
number of double-time days per month, that can only be circumvented by
a large lump sum.
If a control freak does not agree with your terms in writing, do
not work for them. Hold out for a fair deal and if you can't get one,
give up and look elsewhere.
Most often, they are just looking for competent people, so if you
know your stuff, they will agree to whatever you need for said
contract.
9.
There is a high frequency of mentally disturbed people in the world, and many of them became managers.
The stress of working all the way up the corporate ladder is enough to
cripple the mind of anyone with less than a 120 IQ. Most people have
100 IQ and most geniuses are not managers, they are philosophers or
scientists who are smart enough to know how to stay out of that racket.
You can't really win with someone who is crazy, so you have to weed
them out. The easiest way to figure out if your potential customer is
nuts is at negotiation time. When you are given a list of required
deliverables, next to a projected budget, use your head. If the two add
up, your customer is sane. If they are so far off, tell them and ask
them why. If you ask a crazy person why something looks crazy or really
far off target, they will have a crazy reaction that is easily
detectable.
Crazy people think they can bend time, space and matter to their
own will. To some extent that's what programmers have to do anyway, but
for the most part, but if there is inadequate compensation for this
magic -- it's a sign.
Don't be fooled by thinking things will go as expected. If they
won't compensate for overruns, incidentals or expenses, back away
carefully humming a happy tune -- then run! Fast!
10.
Superstitious people do not deal in fact. They work
within the realm of their own belief constructs, which is rooted in
strange omens and voodoo. While these people may be as sane as anyone
else, the problem that programmers face when dealing with superstitious
people is that they are very hard to please, and they may have bizarre
requests that make no sense. To deal with someone who is superstitious,
walk under a ladder and step on a crack, carry a black cat and use the
number 13 frequently. They will avoid
you.
> Quite often I get jobs that involve fixing broken PHP applications (or
> rebuilding from scratch -- often cheaper!). The people that built these
> apps are pretty much amateurs. It shows in the (non) functionality of
> the program and in the coding style itself.
I
love that. "Please fix this so it will do X" and you're like... "But it
never did that before." and the boss is like... "But it has to do it
now" and you're like..."But that will involve a total rewrite!" and the
boss is like ... "It had better not because we spent $50k on that
system!" and you want to say... "You got screwed." but instead you say,
"I'll see what I can do."
ROTFLMAO!!!
> New prospective clients who don't know me are often worried about my
> credentials: is he another hack that will take my money for another
> piece of garbage? I guess this is where the certification comes in -
> they probably won't know much about THAT either, but it sounds good and
> looks good on a business card. If they look into it, they will find
> that it indeed says a lot for the person who has it.
The
only real problem I have with any kind of certification is that is is
stale the minute you get it. New advancements in PHP development and
standards happen every day. Zend doesn't necessarily keep up with this.
Knowing how to code good systems is more about getting your hands in
the code than understanding the latest buzz words, IMHO.
What PHP really needs is something like w3.org's standards
compliance parser. Wouldn't it be great if you could stuff your PHP
modules in a page that verified them as compliant? Oh that would save
the noobs a million hours, and it would give good programmers a way to
show their work is not crap. What would it take to do this, I wonder?
I have no first hand experience with Zend's certs, so I won't trash
them. But I do know that MS certs are heavy on buzz words and light on
true understanding of the changing world of programming. Whenever MS
changes, it's a total upheaval. PHP changes every day, because people
are learning new ways to make the systems run faster and tighter --
plus it's open source so there are more minds working on the entire
nexus. MS is and always has been overcomplicated, and because they are
entrenched in a closed source way of doing things, this is not likely
to change.
Maybe the Zend certs change every day, but I suspect they do not, maybe each year? Does anyone here know?
The problem with most of MS systems is that they are too
complicated. The best systems are simple, minimalist pieces that
perform to standards.
However, managers like people who have lots of fancy papers that
prove they know what they are doing. The actual reliance on this sort
of thing is actually a dark horse, IMHO. We have to sniff for changes
in the way people are doing things and that can never be certified. :-)
There is no certainty, only change. So certification to me is kind
of a symbol of a lack of understanding on the part of those certifying
and those doing the certifications. Now that is perplexing!
> Then of course there's the IT firms that occasionally hire me to do
> jobs for them, and they WILL know the value of it.
Some
are really good. Others are scrambling to keep up. If you have found an
IT firm who is forward thinking and sniffing for changes, then hang on
to them and always work with their guidance. Listen to them.
But if you find that some firms don't really care about the quality
of your work or maybe they can't possibly evaluate you properly, I
would look elsewhere. If they don't care about the quality of your
work, it will show. Ask them for a proper code audit, and a sample
evaluation form up front. If they don't have one or they don't want to
show you one, back away. That spells trouble for everyone because
eventually they will have programmers doing crappy work, without anyone
evaluating correctly -- and that rubs off on anyone working there
because bad work seeps in and good work gets pushed aside.
> I don't look at it as a means of furthering Zend's business or the MS
> paradigm (you're probably right about that), but as a way of furthering
> my own business as a programmer.
You have a
good point here. Look at the big picture, too. If you are certified by
Zend, and you put that on your resume, what happens when some stale
programmers start providing bad code to projects? If you are Zend
certified and they are Zend certified -- that means their reputation is
linked with yours.
I think in this business, reputation is more personal. What do you think?
15.10.2007. 12:13
PHP tutorial: Round to the nearest nickel, dime or quarter
Here are examples on how to round up to the nearest nickel, dime, or quarter using PHP. I will also show you how to round down to the nearest nickel, dime or quarter in PHP. In PHP, the round function will always round up. The floor function will always round down. Because we are talking about money here, I will be using the PHP function number_format to make sure that all the zeros are in place.
Here is how to round up or down to the nearest nickel (5 cents):
$round_up_to_nearest_nickel=number_format(round($number*20)/20,2);
$round_down_to_nearest_nickel=number_format(floor($number*20)/20,2);
Here is how to round up or down to the nearest dime (10 cents):
$round_up_to_nearest_dime=number_format(round($number*10)/10,2);
$round_down_to_nearest_dime=number_format(floor($number*10)/10,2);
Here is how to round up or down to the nearest quarter (25 cents):
$round_up_to_nearest_quarter=number_format(round($number*4)/4,2);
$round_down_to_nearest_quarter=number_format(floor($number*4)/4,2);