In an incredible climax to Group B, Spain set up a last-16 tie against Russia after a 2-2 draw with Morocco was enough to secure top spot.
Portugal let their position as group leaders slip in the closing minutes of their match when an injury-time penalty earned Iran a 1-1 draw against the European champions.
That was after Cristiano Ronaldo missed a penalty, with Portugal having gone ahead through Ricardo Quaresma's wonderful curled finish in the first half.
Portugal will now face Uruguay in their last-16 tie.