libvirt-php: Examples
Description: libvirt, virtualization, virtualization API

# Examples

- Getting libvirt, hypervisor and libvirt-php version
- Connecting to libvirt daemon with debugging
- Getting list of domains

## Getting libvirt, hypervisor and libvirt-php version

If you just want to check whether the module is working fine you can try to ask libvirt for libvirt/hypervisor version and libvirt-php version. Libvirt-php version is also available in phpinfo() output when a module is loaded. In your PHP script you can do it using following syntax:

    <?php
         print_r ( libvirt_version() );
    ?>

The output will be having information about major, minor and release versions of the hypervisor (if connected and applicable) and libvirt available and also there will be version number of libvirt-php connector in form of major.minor.release.

## Connecting to libvirt daemon with debugging

For connecting to libvirt daemon the libvirt_connect() API function has been introduced. This function accepts 2 arguments:

- Hypevisor URI: string
- Readonly: boolean

Hypervisor URI could be also string null to make libvirt probe the hypervisor driver that is applicable to the host machine.

To turn on the debugging you need to call libvirt_logfile_set() API function to tell libvirt-php to enable logging to file. Logging is disabled by default.

    <?php
        $logfile = 'test.log';

        unlink($logfile);
        if (!libvirt_logfile_set($logfile))
             die('Cannot set the log file');

        $conn = libvirt_connect('null', false);
        unset($conn);

        $fp = fopen($logfile, 'r');
        $str = fread($fp, filesize($logfile));
        fclose($fp);

        echo $str;
    ?>

This will print the connection result as logged into the test.log file.

## Getting list of domains

If you want to get the list of domains you can use libvirt_list_domains() API function. This function returns an array of libvirt domain resources that could be used with the libvirt_domain_get_name() API function to get the list of domain names like:

    <?php
         $conn = libvirt_connect('null', false);
         $doms = libvirt_list_domains($conn);
         print_r($doms);
    ?>

This script will output all the domain names available on this connection (all of them are temporarily stored in $doms array).