I have this parameters to download a XML file:
wget --http-user=user --http-password=pass http://www.example.com/file.xml
How I have to use
lots of methods available in php to read a file like exec, file_get_contents, curl and fopen but it depend on your requirement and file permission
Visit this file_get_contents vs cUrl
Basically file_get_contents for for you
$data = file_get_contents($file_url);
wget
wget is a linux command, not a PHP command, so to run this you woud need to use exec, which is a PHP command for executing shell commands.
exec("wget --http-user=[user] --http-password=[pass] http://www.example.com/file.xml");
This can be useful if you are downloading a large file - and would like to monitor the progress, however when working with pages in which you are just interested in the content, there are simple functions for doing just that.
The exec
function is enabled by default, but may be disabled in some situations. The configuration options for this reside in your php.ini
, to enable, remove exec
from the disabled_functions
config string.
alternative
Using file_get_contents we can retrieve the contents of the specified URL/URI. When you just need to read the file into a variable, this would be the perfect function to use as a replacement for curl - follow the URI syntax when building your URL.
// standard url
$content = file_get_contents("http://www.example.com/file.xml");
// or with basic auth
$content = file_get_contents("http://user:pass@www.example.com/file.xml");
As noted by Sean the Bean
- you may also need to change allow_url_fopen to true
in your php.ini to allow the use of a URL in this method, however, this should be true by default.
If you want to then store that file locally, there is a function file_put_contents to write that into a file, combined with the previous, this could emulate a file download:
file_put_contents("local_file.xml", $content);
Shellwrap is great tool for using the command-line in PHP!
Your example can be done quite easy and readable:
use MrRio\ShellWrap as sh;
$xml = (string)sh::curl(['u' => 'user:pass'], 'http://example.com/file.xml');
To run wget command in PHP you have to do following steps :
1) Allow apache server to use wget command by adding it in sudoers list.
2) Check "exec" function enabled or exist in your PHP config.
3) Run "exec" command as root user i.e. sudo user
Below code sample as per ubuntu machine
#Add apache in sudoers list to use wget command
~$ sudo nano /etc/sudoers
#add below line in the sudoers file
www-data ALL=(ALL) NOPASSWD: /usr/bin/wget
##Now in PHP file run wget command as
exec("/usr/bin/sudo wget -P PATH_WHERE_WANT_TO_PLACE_FILE URL_OF_FILE");