I figured out how to do this. Theres a PHP function called proc_open which lets you run a process and pipe data to and from it. Heres what I did:
$descriptors = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w"),
3 => array("pipe", "r")
);
$cwd = './'
$process = proc_open('/bin/sh', $descriptors, $pipes, $cwd) ;
if (is_resource($process)) {
fwrite($pipes[0], 'sudo command') ;
fclose($pipes[0]) ;
fwrite($pipes[2], 'ENTER SUDO PASSWORD HERE') ;
fclose($pipes[2]) ;
// print pipe output
//echo stream_get_contents($pipes[1]) ;
// close pipe
fclose($pipes[1]) ;
proc_close($process) ;
}
I realized I didn't need to change user, but you could just as easily pipe in "su -l user -p" to $pipe[0]. I'm not entirely sure how the script works, I piped the password into $pipe[2] but I don't know if I could have used $pipe[0] instead or what.
Also another possible way to run sudo commands with PHP would be to get PHP to run an expect script, but it seems to be a pain in the ass, I couldn't get it to work myself.