How to redirect to www without editing .htaccess file?
It's always going to be better to do this with .htaccess, or in other web server config, but if you need to do it in php, put this at the top of settings.php:

if ($_SERVER['HTTP_HOST'] == 'example.com') {
  header('Location:http://www.example.com' . $_SERVER['REQUEST_URI']);
  exit();
}