Don't let your dwarves go into the magma, and don't let the magma flow over your dwarves. This will prevent them from being set on fire from contacting magma.
It's usually not practical to stop a fire after it starts. It's possible to put out the flames on a burning creature, but it takes a vast amount of water - they have to have 7-depth water occupy their square to do it reliably, and they won't willingly move into that depth, so you either need to drop water on them or drop them in water. Having a dwarf bath will sometimes extinguish flames, but not always. Since such a structure (a trough in your entry hallway, to the surface or caverns, that is filled with 2- or 3-depth water) is useful anyway for disease containment, building one may be helpful, however.
You can stop a fire from passing through an area through a couple of means. The quickest is usually to have your miners dig a channel ahead of the flames. Fire doesn't spread across z-levels, so a channel stops fire in its tracks. Another means is to build an unpaved road as a fire break; unpaved roads build pretty fast if they're small and remove vegetation from under them, and without any grass to burn the fire won't spread through them. This is a temporary solution, but usually lasts long enough to stop a wildfire.