Claudio Goodridge, Carlos Perez and Alquis Alvarado all scored for Panama, which finished in third place in Group B and assured itself of knockout round berth on the basis of having a better goal difference than the Czech Republic and more goals than Australia.
Goodridge equalized in the sixth minute after Ahmad Esmeilpour gave Iran the lead less than 2½ minutes earlier, but Afshin Kazemi and Mohammad Taheri put the Asian side ahead 3-1 by halftime.
Perez pulled Panama within a goal in the 35th by converting a penalty after a handball, but Taheri restored the two-goal advantage with under three minutes remaining. Alvarado again got Panama within a goal with 39 seconds remaining, however Iranian keeper Mostafa Nazari made a late save to preserve the victory.
"We didn't even dream about this, advancing to the next round in a World Cup in our first time of being here," Panama coach Agustin Campuzano said. "The chance of qualifying was a pressure my players did not expect to face, and that is why we were not up to our usual level."