How to configure PHP CLI on linux ubuntu to run as www-data?

Run a command as another user once:

sudo -u www-data php script.php

This should work if you are root.

As for always running php as www-data, there are several possiblities. You could create a simple wrapper shellscript. If /usr/bin/php is only a soft-link to /usr/bin/php5 or similar, that makes it simpler. Just replace the soft-link (NOT the file php5) with a script like this:

#!/bin/sh

sudo -u www-data php5 $*

return $?

That's not tested though. Also be aware that this will ALWAYS try to run php5 as user www-data, even if the user may not be root and may not have permission to do so. And it may also not be what you really want. Some installed services may run into problems when trying to execute php.

A (possibly better) solution to only apply that to root may be to leave the soft-link /usr/bin/php alone and place the script in /root/bin instead. Then add that folder to PATH via .bashrc, .profile or similar. If you have /etc/skel/.profile, that may point out how that is done:

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

Once this is in your .bashrc, .profile or similar, every new shell you open will allow you to directly execute any executables (+x) in $HOME/bin (/root/bin for root).

Hint: You may want to name the wrapper script something like phpwww so you explicitly specify php script.php or phpwww script.php to decide if you want regular or sudo'ed php.

Another solution is a simple alias. Place this in your .bashrc, .profile or similar:

alias phpwww='sudo -u www-data php'