Both of these countries developed their oil resources in the 1960s and 70s, the same as other middle eastern states such as Saudi Arabia and Kuwait.
Iraq has very large reserves of oil underground, estimated by some to be 6 - 8% of the world's total, and 95% of their foreign trade. By selling it to oil thirsty countries like the United States, China, and Japan, Iraq has brought in hundreds of billions of dollars. When the United States invaded Iraq in 2003, some argued that its reconstruction could be paid for with oil revenues, although that turned out to be wildly optimistic.
Iran also has oil, although less than its neighbor Iraq. In the years before 1979 when the Shah of Iran ran the country and was very friendly to the United States, oil revenue poured into the country. The Shah used much of it to enrich himself and to pay his military and police, which was not enough to stop a revolution. Since then, Iran has been able to survive economically in part because of oil revenues.