Cart

    Sorry, we could not find any results for your search querry.

    Rest-API tutorials: PHP examples

    • Are you already familiar with our API and do you want to get started with the PHP library right away? Then see our Github page to get started. 
       
    • In the 'examples' folder in the PHP library you'll find additional examples for using the PHP library of our API.

    In this tutorial, we show how to use the PHP library of the TransIP REST API using several simple examples. Before proceeding with this article, ensure that you have read the following guides:

    The following PHP examples are covered in this tutorial:


    Retrieving an overview of your VPSs

     

    In this example, we show you how to retrieve an overview of all VPSs in your TransIP account. This creates an Array that contains the following information:

    • name
    • description
    • product name
    • operatingSystem
    • diskSize
    • memorySize
    • cpus
    • status
    • ipAddress
    • macAddress
    • currentSnapshots
    • maxSnapshots
    • isLocked
    • isBlocked
    • isCustomerLocked
    • availabilityZone
    • tags

     

    Create a file containing the code below, for example,  /var/www/html/example.com/vps/GetVpss.php

    <?php
        /**
         * This is an example on how to retrieve and list all VPSs in your TransIP account.
         */
        require_once (__DIR__ . '/../Authenticate.php');
        // Get all VPSs in your account
        $vpss = $api->vps()->getAll();
        $vpss = print_r($vpss, true);

    Do you want to retrieve the specifications of a specific VPS? Then use getByName($vpsName) instead of getAll.


    Stopping a VPS

     

    With the stop action, you put the VPS in 'stopped' status. This function is equivalent to turning off a computer with the physical 'off / on' button. This is not a graceful stop of your VPS and it is important to save your work first.

    If the VPS is in a power cycle (reset), this API call will fail because stopping the VPS is part of the power cycle process.

    Replace 'example-vps' with the name (not the description) of your VPS.

    <?php
        /**
         * Use this API call in order to stop your VPS
         */
        require_once(__DIR__ . '/../Authenticate.php');
        $vpsName = 'example-vps';
        $api->vps()->stop($vpsName);

    Starting a VPS

     

    This API call starts a VPS that is switched off. This function is the same as turning on a computer with the physical 'off / on' button.

    If the VPS is in a power cycle (reset), this API call will fail because starting the VPS is part of the power cycle process.

    <?php
        /**
         * Use this API call in order to start your VPS
         */
        require_once(__DIR__ . '/../Authenticate.php');
        $vpsName = 'example-vps';
        $api->vps()->start($vpsName);

    Resetting a VPS

     

    This function immediately restarts your VPS and is equivalent to resetting a computer with the physical 'reset' button. This is not a graceful reset of your VPS and it is important to first save your work.

    <?php
        /**
         * Use this API call in order to restart your VPS with a reset command
         */
        require_once(__DIR__ . '/../Authenticate.php');
        $vpsName = 'example-vps';
        $api->vps()->reset($vpsName);

    Retrieving available VPS products

     

    With the products API call, you display an overview of all available VPS products that can be ordered via the API. When new products are released, they will be included in the output.

    <?php
        /**
         * This is an example on how to retrieve all available VPS products. 
         */
        require_once(__DIR__ . '/Authenticate.php');
        // Get all available products
        $products = $api->products()->getAll();
        $products = print_r($products, true);
        

    Showing available operating systems

     

    With the vpsOperatingSystems API-call, you display an overview of all available operating systems. When new products are released, they will be included in the output.

    In this example, we assume that you place the file with the code below in the same folder as 'Authenticate.php'.

    <?php
        /**
         * This is an example on how to retrieve all available VPS products. 
         */
        require_once(__DIR__ . '/../Authenticate.php');
        // Get all available products
        $OperatingSystems = $api->vpsOperatingSystems()->getAll();
        $products = print_r($OperatingSystems, true);
        
    OperatingSystems 

    Ordering a VPS

     

    You can order a VPS with the vps->order API-call. After ordering, the VPS is delivered and deployed automatically.

    • You can optionally specify add-ons in an array that are then automatically ordered as well.
    • If you do not specify an availability zone, your VPS will be delivered in Amsterdam.
    • When you enter a hostname, the first 32 characters of this are used as a 'description' of your VPS (i.e. the own name / description that you can give to a VPS in the control panel).
    • A hostname is required for cPanel.
    • Do you not want to add addons, but do you want to provide a hostname, availability zone, and / or description? Then, define addons as an empty array with: $addons = [];
    • You can provide an unattended installation script which will be run immediately after the order has been processed, see the note beneath the code below.

    When using this API call, an invoice will be generated in your TransIP account.

    <?php
        /**
         * Using this API call, you are able to order a new VPS. After the order process has been completed (payment will occur
         * at a later stage should direct debit be used) the VPS will automatically be provisioned and deployed. Values
         * associated to the newly delivered VPS will be returned in a new call respectively.
         */
        require_once(__DIR__ . '/../Authenticate.php');
        /**
         * Example 1: Order a VPS
         */
        $productName               = 'vps-bladevps-x1';
        $operatingSystemToInstall  = 'debian-9';
        // Order VPS
        $api->vps()->order(
             $productName,
             $operatingSystemToInstall
        );
        /**
         * Example 2: Order a VPS with an addon and choose your data center
         */
        $addons = ['vpsAddon-1-extra-ip-address'];
        $hostName = 'server.yoursite.com';
        $availabilityZone = 'ams0';
        $description = 'My server';
        // Order VPS
        $api->vps()->order(
            $productName,
            $operatingSystemToInstall,
            $addons,
            $hostName,
            $availabilityZone,
            $description,
        );

    If you'd like to use an unattended installation as part of ordering a VPS, then also provide the following variable in the second exaple:

    $base64InstallText = 'installscript';

    The order command would then look as follows:

    // Order VPS 
        $api->vps()->order( 
            $productName, 
            $operatingSystemToInstall,
            $addons,
            $hostName,
            $availabilityZone,
            $description,
            $base64InstallText 
        );

    The contents of the unattended installation script fall out of the scope of this tutorial, but you can consult Ubuntu, Debian or RedHat's documentation.

    Click below for an example of a minimal install for Ubuntu 18.04.

    Example

    $base64InstallText = base64_encode('
    ### Localization
    # Preseeding only locale sets language, country and locale.
    d-i debian-installer/locale string en_US
    # Keyboard selection.
    # Disable automatic (interactive) keymap detection.
    d-i console-setup/ask_detect boolean false
    d-i keyboard-configuration/xkb-keymap select us
    ### Network configuration
    # netcfg will choose an interface that has link if possible. This makes it
    # skip displaying a list if there is more than one interface.
    d-i netcfg/choose_interface select auto
    # Any hostname and domain names assigned from dhcp take precedence over
    # values set here. However, setting the values still prevents the questions
    # from being shown, even if values come from dhcp.
    d-i netcfg/get_hostname string example
    d-i netcfg/get_domain string supporttest.nl
    ### Mirror settings
    # If you select ftp, the mirror/country string does not need to be set.
    #d-i mirror/protocol string ftp
    d-i mirror/country string manual
    d-i mirror/http/hostname string mirror.transip.net
    d-i mirror/http/directory string /ubuntu/ubuntu
    d-i mirror/http/proxy string
    ### Account setup
    # Skip creation of a root account (normal user account will be able to
    # use sudo). The default is false; preseed this to true if you want to set
    # a root password.
    d-i passwd/root-login boolean true
    # Alternatively, to skip creation of a normal user account.
    #d-i passwd/make-user boolean false
    # Root password, either in clear text
    d-i passwd/root-password password yourpassword
    d-i passwd/root-password-again password yourpassword
    # or encrypted using a crypt(3)  hash.
    #d-i passwd/root-password-crypted password [crypt(3) hash]
    # To create a normal user account.
    d-i passwd/user-fullname string TransIP Demo
    d-i passwd/username string transip
    # Normal user password, either in clear text
    d-i passwd/user-password password yourpassword
    d-i passwd/user-password-again password yourpassword
    # or encrypted using a crypt(3) hash.
    #d-i passwd/user-password-crypted password [crypt(3) hash]
    # Create the first user with the specified UID instead of the default.
    #d-i passwd/user-uid string 1010
    # The installer will warn about weak passwords. If you are sure you know
    # what you are doing and want to override it, uncomment this.
    d-i user-setup/allow-password-weak boolean true
    # Set to true if you want to encrypt the first user home directory.
    d-i user-setup/encrypt-home boolean false
    ### Clock and time zone setup
    # Controls whether or not the hardware clock is set to UTC.
    d-i clock-setup/utc boolean true
    # You may set this to any valid setting for $TZ; see the contents of
    # /usr/share/zoneinfo/ for valid values.
    d-i time/zone string US/Eastern
    # Controls whether to use NTP to set the clock during the install
    d-i clock-setup/ntp boolean true
    # NTP server to use. The default is almost always fine here.
    #d-i clock-setup/ntp-server string ntp.example.com
    ### Partitioning
    ## Partitioning example
    # If the system has free space you can choose to only partition that space.
    # This is only honoured if partman-auto/method (below) is not set.
    # Alternatives: custom, some_device, some_device_crypto, some_device_lvm.
    #d-i partman-auto/init_automatically_partition select biggest_free
    # Alternatively, you may specify a disk to partition. If the system has only
    # one disk the installer will default to using that, but otherwise the device
    # name must be given in traditional, non-devfs format (so e.g. /dev/sda
    # and not e.g. /dev/discs/disc0/disc).
    # For example, to use the first SCSI/SATA hard disk:
    d-i partman-auto/disk string /dev/vda
    # In addition, you will need to specify the method to use.
    # The presently available methods are:
    # - regular: use the usual partition types for your architecture
    # - lvm:     use LVM to partition the disk
    # - crypto:  use LVM within an encrypted partition
    d-i partman-auto/method string lvm
    # If one of the disks that are going to be automatically partitioned
    # contains an old LVM configuration, the user will normally receive a
    # warning. This can be preseeded away...
    d-i partman-lvm/device_remove_lvm boolean true
    # The same applies to pre-existing software RAID array:
    d-i partman-md/device_remove_md boolean true
    # And the same goes for the confirmation to write the lvm partitions.
    d-i partman-lvm/confirm boolean true
    d-i partman-lvm/confirm_nooverwrite boolean true
    # For LVM partitioning, you can select how much of the volume group to use
    # for logical volumes.
    d-i partman-auto-lvm/guided_size string max
    # You can choose one of the three predefined partitioning recipes:
    # - atomic: all files in one partition
    d-i partman-auto/choose_recipe select atomic
    # This makes partman automatically partition without confirmation, provided
    # that you told it what to do using one of the methods above.
    d-i partman-partitioning/confirm_write_new_label boolean true
    d-i partman/choose_partition select finish
    d-i partman/confirm boolean true
    d-i partman/confirm_nooverwrite boolean true
    # This makes partman automatically partition without confirmation.
    d-i partman-md/confirm boolean true
    d-i partman-partitioning/confirm_write_new_label boolean true
    d-i partman/choose_partition select finish
    d-i partman/confirm boolean true
    d-i partman/confirm_nooverwrite boolean true
    ### Base system installation
    # Configure a path to the preconfigured base filesystem. This can be used to
    # specify a path for the installer to retrieve the filesystem image that will
    # be deployed to disk and used as a base system for the installation.
    #d-i live-installer/net-image string /install/filesystem.squashfs
    # The kernel image (meta) package to be installed; "none" can be used if no
    # kernel is to be installed.
    #d-i base-installer/kernel/image string linux-generic
    ### Apt setup
    # You can choose to install restricted and universe software, or to install
    # software from the backports repository.
    #d-i apt-setup/restricted boolean true
    #d-i apt-setup/universe boolean true
    #d-i apt-setup/backports boolean true
    # Uncomment this if you do not want to use a network mirror.
    #d-i apt-setup/use_mirror boolean false
    # Select which update services to use; define the mirrors to be used.
    # Values shown below are the normal defaults.
    #d-i apt-setup/services-select multiselect security
    #d-i apt-setup/security_host string security.ubuntu.com
    #d-i apt-setup/security_path string /ubuntu
    # Additional repositories, local[0-9] available
    #d-i apt-setup/local0/repository string \
    #       http://local.server/ubuntu stretch main
    #d-i apt-setup/local0/comment string local server
    # Enable deb-src lines
    #d-i apt-setup/local0/source boolean true
    # URL to the public key of the local repository; you must provide a key or
    # apt will complain about the unauthenticated repository and so the
    # sources.list line will be left commented out
    #d-i apt-setup/local0/key string http://local.server/key
    ### Package selection
    tasksel tasksel/first multiselect standard
    # Individual additional packages to install
    #d-i pkgsel/include string openssh-server build-essential
    # Whether to upgrade packages after debootstrap.
    # Allowed values: none, safe-upgrade, full-upgrade
    #d-i pkgsel/upgrade select none
    # Policy for applying updates. May be "none" (no automatic updates),
    # "unattended-upgrades" (install security updates automatically), or
    # "landscape" (manage system with Landscape).
    d-i pkgsel/update-policy select none
    ## Boot loader installation
    # Grub is the default boot loader (for x86).
    # This is fairly safe to set, it makes grub install automatically to the MBR
    # if no other operating system is detected on the machine.
    d-i grub-installer/only_debian boolean true
    # This one makes grub-installer install to the MBR if it also finds some other
    # OS, which is less safe as it might not be able to boot that other OS.
    d-i grub-installer/with_other_os boolean true
    ### Finishing up the installation
    # During installations from serial console, the regular virtual consoles
    # (VT1-VT6) are normally disabled in /etc/inittab. Uncomment the next
    # line to prevent this.
    #d-i finish-install/keep-consoles boolean true
    # Avoid that last message about the install being complete.
    d-i finish-install/reboot_in_progress note
    #### Advanced options
    ### Running custom commands during the installation
    ## i386 Preseed Example
    # d-i preseeding is inherently not secure. Nothing in the installer checks
    # for attempts at buffer overflows or other exploits of the values of a
    # preconfiguration file like this one. Only use preconfiguration files from
    # trusted locations! To drive that home, and because it is generally useful,
    # here is a way to run any shell command you like inside the installer,
    # automatically.
    # This first command is run as early as possible, just after
    # preseeding is read.
    #d-i preseed/early_command string anna-install some-udeb
    # This command is run immediately before the partitioner starts. It may be
    # useful to apply dynamic partitioner preseeding that depends on the state
    # of the disks (which may not be visible when preseed/early_command runs).
    #d-i partman/early_command \
    #       string debconf-set partman-auto/disk "$(list-devices disk | head -n1)"
    # This command is run just before the install finishes, but when there is
    # still a usable /target directory. You can chroot to /target and use it
    # directly, or use the apt-install and in-target commands to easily install
    # packages and run commands in the target system.
    #d-i preseed/late_command string apt-install zsh; in-target chsh -s /bin/zsh
    ');

    Attach existing Big Storage to your VPS

     

    You can attach a Big Storage using the 'update' function from the BigStorage Repository. Please note that your Big Storage can be attached to a maximum of one VPS and a maximum of ten Big Storages can be attached to a single VPS.

    <?php
        /**
         * This is an example on how to attach a Big Storage to a VPS.
         */
        require_once(__DIR__ . '/../Authenticate.php');
        // Name of your Big Storage and VPS to which it will be attached
        $bigStorageName = 'testtransip-bigstorage40';
        $bigStorageVpsName = 'testtransip-vps28';
        // Attach Big Storage to your VPS
        $bigStorage = $api->bigStorages()->getByName($bigStorageName);
        $bigStorage->setVpsName($bigStorageVpsName);
        $api->bigStorages()->update($bigStorage);

    Retrieving a list of your domains

     

    In this example, we show you how to retrieve an overview of all domains in your TransIP account, regardless of whether they have been ordered via the API or the TransIP website. The output is an array that contains the following information:

    • name
    • authCode
    • isTransferLocked
    • registrationDate
    • renewalDate
    • isWhitelabel
    • cancellationDate
    • cancellationStatus
    • isDnsOnly
    • tags
    <?php
        /**
         * This is an example on how to retrieve and list all domains in your TransIP account.
         */
        require_once (__DIR__ . '/../Authenticate.php');
        // Get a list of all domains in your account
        $domains = $api->domains()->getAll();
        $domains = print_r($domains, true);

    Listing DNS records for a domain

     

    In the example below, we show you how to list all DNS records for a specific domain.

    <?php
        /**
         * This is an example on how to retrieve and list all DNS records for a domain in your TransIP account.
         */
        require_once (__DIR__ . '/../Authenticate.php');
        $domainName = 'example.com';
        // Get the DNS for your domain
        $domainDns = $api->domainDns()->getByDomainName($domainName);
        $domainDns = print_r($domainDns, true);

    Updating a single existing DNS record

     

    Updates the content of an existing DNS record. You can update the name (setName), TTL (setExpire), type (setType) and / or value (setContent). Accepted values for TTL and type are:

    • TTL: 60, 300, 3600, 86400
    • Type: A, AAAA, CNAME, MX, NS, TXT, SRV, SSHFP, TLSA, CAA

    You will receive an error message if the record does not yet exist.

    <?php
        /**
         * This is an example on how to update a single existing DNS entry for a specific domain
         */
        use Transip\Api\Library\Entity\Domain\DnsEntry;
        require_once (__DIR__ . '/../Authenticate.php');
        $domainName = 'example.com';
        // Create a DNS entry object
        $dnsEntry = new DnsEntry();
        $dnsEntry->setName('apidemo');
        $dnsEntry->setExpire('300');
        $dnsEntry->setType('TXT');
        $dnsEntry->setContent('transip demo');
        // Apply entry
        $api->domainDns()->updateEntry($domainName, $dnsEntry);

    Adding a single new DNS record

     

    Adds a new DNS record to a domain. You can update the name (setName), TTL (setExpire), type (setType) and / or value (setContent). Accepted values for TTL and type are:

    • TTL: 60, 300, 3600, 86400
    • Type: A, AAAA, CNAME, MX, NS, TXT, SRV, SSHFP, TLSA, CAA
    <?php
        /**
         * This is an example on how to add a single new DNS entry to a specific domain
         */
        use Transip\Api\Library\Entity\Domain\DnsEntry;
        require_once (__DIR__ . '/../Authenticate.php');
        $domainName = 'supporttest.nl';
        // Create a DNS entry object
        $dnsEntry = new DnsEntry();
        $dnsEntry->setName('apidemo2');
        $dnsEntry->setExpire('300');
        $dnsEntry->setType('TXT');
        $dnsEntry->setContent('transip demo');
        // Apply entry
        $api->domainDns()->updateEntry($domainName, $dnsEntry);

     

    This concludes our examples on how to use the PHP library of our REST API.

    Should you have any questions left regarding this article, do not hesitate to contact our support department. You can reach them via the ‘Contact Us’ button at the bottom of this page.

    Need help?

    Receive personal support from our supporters

    Contact us