Winkelwagen

    Sorry, we konden geen resultaten vinden voor jouw zoekopdracht.

    Rest-API tutorials: PHP voorbeelden

    • Ben je bekend met onze REST API en wil je direct aan de slag? Op deze Github-pagina vind je de PHP-library van onze REST API.
       
    • In de 'examples'-map in de PHP-library vind je nog meer voorbeelden terug voor het gebruik van de PHP-library.

    In deze handleiding laten wij in enkele eenvoudige voorbeelden zien hoe je de PHP-library van de TransIP REST API gebruikt. Zorg dat je voor je de voorbeelden in dit artikel doorloopt de volgende artikelen hebt gelezen:

    De volgende API-voorbeelden worden in dit artikel behandeld:

    Daarnaast hebben wij nog enkele voorbeelden van geavanceerdere toepassingen in PHP van de REST API. Wij zullen gaandeweg deze lijst uitbreiden:


    Een overzicht van je VPS'en ophalen

    In dit voorbeeld laten wij zien hoe je een overzicht ophaalt van alle VPS'en in je TransIP-account. Hiermee maak je een Array waarin de volgende informatie is opgenomen:

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

    Maak een bestand aan waar je de onderstaande code in opneemt, bijvoorbeeld /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);
    echo "<pre>{$vpss}</pre>";

    Wil je van een specifieke VPS de specificaties ophalen? Gebruik dan in plaats van getAll de functie getByName($vpsName).


    Een VPS stoppen

    Met de stop actie plaats je de VPS in een 'stopped' status. Deze functie is gelijk aan het uitzetten van een computer met de fysieke 'uit/aan'-knop. Dit is geen graceful stop van je VPS en het is belangrijk om eerst je werk op te slaan.

    Als de VPS zich in een power cycle (reset) bevindt zal deze API call falen omdat het stoppen van de VPS een onderdeel is van het power cycle proces.

    Vervang 'example-vps' door de naam (niet de description) van je VPS.

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

    Een VPS starten

    Deze API call start een VPS die uit staat. Deze functie is gelijk aan het aanzetten van een computer met de fysieke 'uit/aan'-knop.

    Als de VPS zich in een power cycle (reset) bevindt zal deze API call falen omdat het starten van de VPS een onderdeel is van het power cycle proces.

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

    Een VPS resetten

    Deze functie herstart je VPS onmiddellijk en is gelijk aan het resetten van een computer met de fysieke 'reset'-knop. Dit is geen graceful reset van je VPS en het is belangrijk om eerst je werk op te slaan.

    <?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);

    Beschikbare VPS-producten ophalen

    Met de products API-call toon je een overzicht van alle beschikbare VPS-producten die via de API besteld kunnen worden. Als er nieuwe producten uitgebracht worden, zullen die in de output opgenomen worden.

    <?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);
    echo "<pre>{$products}</pre>";

    Beschikbare besturingssystemen tonen

    Met de vpsOperatingSystems API-call toon je een overzicht van alle beschikbare besturingssystemen. Als er nieuwe producten uitgebracht worden, zullen die in de output opgenomen worden.

    In dit voorbeeld gaan wij ervan uit dat je het bestand met de onderstaande code in dezelfde map plaatst als '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);
    echo "<pre>{$OperatingSystems }</pre>";

    Een VPS bestellen

    Met de vps->order API-call kun je een VPS bestellen. Na het bestellen wordt de VPS automatisch geleverd en deployed.

    • Je kunt optioneel add-ons in een array opgeven die dan automatisch meegeleverd worden.
    • Specificeer je geen availability zone, dan word je VPS in Amsterdam geleverd.
    • Wanneer je een hostname opgeeft, worden de eerste 32 karakters hiervan gebruikt als 'description' van je VPS (i.e. de eigen naam/omschrijving die je aan een VPS kunt geven in het controlepaneel).
    • Bij cPanel is een hostname verplicht.
    • Wil je geen addons, maar wel een hostname, availability zone en/of description meegeven? Definieer addons dan als een leeg array met: $addons = [];
    • Het is mogelijk een script mee te geven voor een unattended installatie van de VPS na de bestelling. Zie de toelichting onder de code.

    Bij het gebruik van deze API call zal een factuur worden gegenereerd in je 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,
    );
    

    Wil je gebruik maken van een unattended installatie bij het bestellen, geef dan ook in het tweede voorbeeld de volgende variabele mee:

    $base64InstallText = 'installatiescript';

    Het bestelcommando zou er dan als volgt uitzien:

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

    De inhoud van een unattended installatiescript valt buiten de scope van deze handleiding, maar je kunt hiervoor gebruik maken van de documentatie van Ubuntu, Debian en RedHat (voor CentOS).

    Klik hier onder voor een voorbeeld van een minimal install voor Ubuntu 18.04.

    Voorbeeld
    $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
    ');

    Bestaande Big Storage aan je VPS koppelen

    Het koppelen van een Big Storage doe je met behulp van de 'update' functie uit de BigStorage Repository. Let wel dat je Big Storage aan maximaal één VPS gekoppeld kan worden en maximaal tien Big Storages aan één VPS gekoppeld kunnen zijn.

    <?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);
    

    Een lijst van je domeinen ophalen

    In dit voorbeeld laten wij zien hoe je een overzicht ophaalt van alle domeinen in je TransIP-account, ongeacht of ze via de API of de TransIP-website zijn besteld. De output is een array waarin de volgende informatie is opgenomen:

    • 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);
    echo "<pre>{$domains}</pre>";

    DNS-records van een domein opvragen

    In het voorbeeld hieronder laten wij zien hoe je van een specifiek domein alle DNS-records opvraagt.

    <?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);
    echo "<pre>$domainDns</pre>";

    Een enkel bestaand DNS-record updaten

    Update de inhoud van een bestaand DNS-record. Je kunt de naam (setName), TTL (setExpire), type (setType) en/of waarde (setContent) updaten. Geaccepteerde waardes voor TTL en type zijn:

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

    Je krijgt een foutmelding als het record nog niet bestaat.

    <?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);

    Een enkel DNS-record toevoegen

    Voegt een nieuw DNS-record toe aan een domein. Je kunt de naam (setName), TTL (setExpire), type (setType) en/of waarde (setContent) updaten. Geaccepteerde waardes voor TTL en type zijn:

    • 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()->addDnsEntryToDomain($domainName, $dnsEntry);

     

    Mocht je aan de hand van deze handleiding nog vragen hebben, aarzel dan niet om onze supportafdeling te benaderen. Je kunt hen bereiken via de knop 'Neem contact op' onderaan deze pagina.

    Kom je er niet uit?

    Ontvang persoonlijke hulp van onze supporters

    Neem contact op