通过php脚本选择OpenVPN配置文件

I am using openvpn on my own dedicated cloud server (ubuntu). Therefor I created an interface by doing all steps written in this tutorial. Everything works when I am using the terminal as described in the tutorial. Also when I am trying to connect to the interface via curl curl_setopt($ch, CURLOPT_INTERFACE, "tun0"); it works fine. But therefor I have to execute the following statement in the terminal before I run the php script:

openvpn "path/to/my/file.ovpn"

When I want to change the IP address I have to execute the statement above again but with another file.ovpn.

But I want to change the file.ovpn in my php script like:

exec('sudo openvpn path/to/my/file.ovpn');

But this isn't working. I always get the error curl error: Could not resolve host: tun0. So what am I doing wrong? Is this even possible?

For now the configuration files are living in the root folder. So may be it is an authorization / access issue?

most likely, sudo fails, it tries to ask for a password and you're not giving it any, OR the user that PHP runs as is not in the sudo file and it errors out. in which case, shame on you for ignoring stderr and not noticing it.

in any case, if php runs as the user "www-data", add this to /etc/sudoers

www-data ALL=(ALL) NOPASSWD: /usr/bin/openvpn path/to/my/file.ovpn

just replace www-data with whatever user php runs as (in linux, most commonly, its a user called www-data), and /usr/bin/openvpn with wherever your openvpn binary is located and warning, this allows the user to run the exact command /usr/bin/openvpn path/to/my/file.ovpn as root without a password. which i believe would solve your problem here.