At least 19 people were killed and 22 wounded when militants stormed Afghanistan's biggest university in an attack that ended only after hours of fighting with security forces, officials said.

The Taliban said they were not involved in the incident at Kabul University, but several education centres have been attacked over the years by extremist groups such as the so-called Islamic State.

A police spokesman said most of those killed were students.

A spokesman for the ministry of higher education said the attack started when government officials were arriving for the opening of an Iranian book fair organised at the campus.

Gunmen stormed the facility, sending hundreds fleeing and scrambling over walls of the campus as they tried to escape the firing, witnesses said.

Afghan security forces later surrounded the area, cordoning off all roads that led to the university, witnesses and an AFP correspondent reported. 

Policemen stand guard at an entrance gate of the Kabul University in Afghanistan

Students spoke of chaos and confusion.

"We were studying inside our classrooms when suddenly we heard a burst of gunfire inside the university," said Fraidoon Ahmadi, 23, adding that he and several other students were besieged for more than two hours before being rescued

"We were very scared and we thought it could be the last day of our lives... boys and girls were shouting, praying and crying for help."

About 800 students were in the social sciences faculty where he was studying. 

Last week at least 24 people, mostly students, were killed in a suicide attack on an educational centre in western Kabul that was claimed by IS.

In 2018 a suicide bomber killed dozens of people, many of them teenagers, in front of Kabul University in an attack also claimed by IS.

Sixteen people were killed when militants stormed the American University of Afghanistan in Kabul in 2016.