A Brooklyn student sneaked a loaded gun into school in his backpack yesterday and then accidentally shot himself in the thigh when the weapon went off in an English class, police said.

Howling in pain, the 15-year-old boy then tried to hide the .45-caliber pistol by handing his bag to a pal, who attempted to run away with it in the pandemonium that followed, according to officials and students.

The wounded teen is a special-ed student at New Utrecht HS who transferred to the Bensonhurst school – considered one of the safest in the city – three days ago, officials said.

The teen, whose name was withheld because he is a minor, was rushed to Lutheran Hospital with a leg injury caused by the bullet, which flew through his leg to his foot.

His pal, Danny Rhames, 17, was caught with the gun and was charged with weapons possession, cops said.

Department of Education spokesman Keith Kalb said both students had recently transferred from Jim Thorpe HS in Brooklyn and are special-ed students who were enrolled under an “inclusion program” that mixes them into regular classes.

Rhames had been at New Utrecht for at least two months.

Kalb said both students will be suspended.

Students in the noon class said the gun suddenly fired while their teacher was facing the blackboard and giving them an assignment to write entries in their personal journals.

They said the teen had been holding the pack on his lap and that Rhames had been looking inside it.

“The teacher had her back to the class, and all of a sudden there was a big boom,” said student Ashley Feller, 14.

“It sounded like something exploded in the science lab. It was really loud, then we saw all this blood coming down his leg. He screamed, ‘Call 911,’ the teacher called security, and we had to leave the classroom.”

There are no metal detectors at the school of some 3,000, and students are not frisked before they enter.

Guidance counselors met with the 30 students who had been in the classroom, and their parents were notified.

Additional safety agents will be deployed to the school today, including an NYPD School Safety Division mobile command unit, officials said.