Before iOS 4 - jailbreak software changes could do this.
For iOS 4 and later, the lock function easily sets a portrait mode for all apps that run in both portrait and landscape.
You can lock the screen rotation on the iPhone 3GS and 4, running iOS 4, to portrait only by double pressing the Home button (bringing up the task switcher), swiping right to show the media controls and pressing the left most icon (looks like a refresh button), the rotation lock. When locked you will see a padlock in the icon and a new status bar icon of the same design.
Note: this does not affect applications which only run in landscape mode, such as most games.
Edit: Video of how to do this: http://www.youtube.com/watch?v=xYkUzYXtZT0