All-rounder Imad Wasim hit Afghanistan skipper Gulbadin Naib for a boundary through the covers to seal the win off the fourth ball of the last over, prompting chaotic scenes as fans poured onto the Headingley pitch.
Pakistan, chasing a modest 228-run target, were in grave danger at 156 for six in the 39th over.
But man-of-the-match Imad (49 not out) and Shadab Khan (11) put on 50 for the seventh wicket to revive their hopes.
The win lifts Pakistan into fourth place in the 10-team table, above hosts England after a poor start to the tournament.
If they win their final game against Bangladesh and England fail to win both of their last two matches, against India and New Zealand, Pakistan will qualify for the semi-finals.
"Thank you all the fans, they cheered every ball. It is a great win for us on not an easy pitch," said Pakistan captain Sarfaraz Ahmed.
"We all know that it is not easy to win our last four games," he said. "We go match by match. We will all be watching India v England tomorrow."
Pakistan Prime Minister Imran Khan, a World Cup-winning captain in his cricket days, tweeted his congratulations to the team for "keeping their nerve under pressure".