There are two kinds of backfires; intake backfires and exhaust backfires.
Intake backfires happen when the timing mechanism fails and cam timing becomes retarded (eg; timing belt or chain skips a tooth, dowel/key on cam sprocket breaks and sprocket moves relative to cam, etc). This causes the intake valve to close late enough that combustion starts before it's fully seated. It can also be caused by a cracked or bent intake valve, or ignition timing that has been advanced too far. On DOHC engines, sometimes the timing belt can skip a tooth on only one cam, which can lead to all kinds of weird behavior.
Exhaust backfires are typically caused by an overly rich air-fuel mix and/or ignition timing that's been retarded too far. Also, in multi-cylinder engines, if one cylinder is misfiring badly it can cause backfires (since that cylinder is basically pumping unburned fuel into the exhaust).