How to Send a vCard using PHP and SMS

March 13, 2023
Written by
Reviewed by

How to Send a vCard using PHP and SMS

If you need to share a contact's details with a friend, the last thing that you want to do is to copy their details manually, one by one, from your contacts app into an SMS. And your friend's not going to enjoy copying them, one-by-one, from the SMS into a new contact on their phone either.

The same goes for sharing contacts from PHP applications. Copying details from a website into an SMS and sending it is very tedious.

Gladly, no one needs to, as contacts can be exchanged using vCards!

If you're not familiar with them, vCards are, effectively, an electronic form of a business card. They can contain all of the contact details (or properties) that you'd likely expect to see, such as first and last names, nicknames, photos, anniversaries, roles – and so much more.

In this tutorial, I'm going to show you how to create one with PHP and then send it to a contact in a Twilio-powered SMS.

Prerequisites

To follow along with this tutorial, you will need the following:

Create the project directory structure

The first thing to do is to create the project's directory structure. So, where you store your projects, run the following commands to create the project directory and change in to it.

mkdir -p twilio-vcard-sms/public/assets
cd twilio-vcard-sms

If you're using Microsoft Windows, run the following commands instead.

mkdir twilio-vcard-sms/public/assets
cd twilio-vcard-sms

The project directory contains a directory named public, where the sole PHP file will be created. In that directory, is another directory called assets. This directory is where the vCard will be written to, when created.

Install the required dependencies

Now, you need to install the 3 required dependencies; these are:

  • sabre/vobject: This package simplifies creating vCard files.
  • Twilio's PHP Helper Library: This package simplifies interacting with Twilio's APIs, making it pretty trivial to send an SMS.
  • PHP dotenv: This package helps us keep environment variables and other secure credentials out of code, yet still be simple enough to work with.

To install them, run the following command.

composer require sabre/vobject \
    twilio/sdk \
    vlucas/phpdotenv

Set the required environment variables

Now, you have to set several environment variables. These are:

  • Your Twilio Account SID and Auth Token: required to make authenticated requests to Twilio's APIs.
  • Your Twilio phone number: so that the correct account can send the SMS.
  • The ngrok Forwarding URL: This is the public-facing URL of the PHP application. It needs to be publicly available so Twilio can retrieve the generated vCard.
  • Your phone number: So that the application knows which phone number to send the SMS to.

These will be stored in a new file, in the top-level project directory, named .env. Create the file with your preferred text editor or IDE and then paste the configuration, below, into the file.

TWILIO_NUMBER="XXXXXXXXXX"
TWILIO_ACCOUNT_SID="XXXXXXXXXX"
TWILIO_AUTH_TOKEN="XXXXXXXXXX"
NGROK_URL="XXXXXXXXXX"
YOUR_NUMBER="XXXXXXXXXX"

Paste your phone number in place of the placeholder for YOUR_NUMBER.

Twilio Console Account Info panel

Then, open the Twilio Console in your preferred browser, and from the dashboard's Account Info panel, copy your Account SID, Auth Token, and Twilio phone number and paste them into .env in place of the placeholders for TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_NUMBER respectively.

The NGROK_URL placeholder will be replaced toward the end of the tutorial.

Write the PHP code

Now, it's time to write the code. In public, create a new file named index.php. Then, paste the code below into it.

<?php

declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();
$dotenv->required([
    'TWILIO_ACCOUNT_SID',
    'TWILIO_AUTH_TOKEN',
    'TWILIO_NUMBER',
    'TWILIO_NUMBER',
    'YOUR_NUMBER',
]);

use Sabre\VObject\Component\VCard;
use Twilio\Rest\Client;

echo "Creating VCard...\n";
$vcard = new VCard([
    'FN'  => 'Twilio Number',
    'ORG' => 'Twilio',
    'TEL' => $_ENV['TWILIO_NUMBER'],
    'TITLE' => 'Twilio',
    'URL' => 'https://twilio.com/docs',
    'BDAY' => new DateTimeImmutable('2008/03/18'),
]);

// Uncomment the line below, if your contacts app cannot import 
// the vCard created by the default code.
// $vcard = $vcard->convert(VCard::VCARD30);

$vcardFilePath = __DIR__ . '/assets/twilio.vcf';

$result = file_put_contents($vcardFilePath, $vcard->serialize());

if (! $result) {
    echo "Could not create VCard successfully.\n";
    exit();
}
echo "VCard created successfully.\n";
echo "File is available at: {$vcardFilePath}.\n\n";

echo "Sending VCard via SMS...\n";

$twilio = new Client(
    $_ENV["TWILIO_ACCOUNT_SID"],
    $_ENV["TWILIO_AUTH_TOKEN"]
);

$message = $twilio
    ->messages
    ->create(
        sprintf("%s", $_ENV['YOUR_NUMBER']),
        [
            "from" => "{$_ENV['TWILIO_NUMBER']}",
            "body" => "Here is my contact VCard",
            "mediaUrl" => "{$_ENV['NGROK_URL']}/assets/twilio.vcf",
        ]
    );

if ($message->errorCode === null) {
    echo "VCard was successfully sent via SMS to: {$_ENV['YOUR_NUMBER']}.\n";
    echo "Message SID is: {$message->sid}.";
}

The code starts off by loading the environment variables defined in .env into PHP's $_ENV and $_SERVER superglobals. The call to $dotenv->required() ensures that the environment variables listed in the array passed to the call are defined and have a value.

After that, a new VCard object ($vcard) is initialised. The vCard specification lists quite a number of properties, but the code only sets five:

  • FN: The contact's full name
  • ORG: The name of the organisation that the contact works for
  • TEL: The contact's telephone number
  • TITLE: The contact's title or identifier
  • URL: A URL
  • BDAY: The contact's birthday

Then, using PHP's file_put_contents() function, a vCard file is created from $vcard in public/assets, named twilio.vcf. Then, a Twilio Client object ($twilio) is initialised with your Twilio Account SID and Auth Token. After that, the call to $twilio->messages->create() sends an SMS to the number stored in $_ENV['TWILIO_NUMBER']. During this process, Twilio will retrieve the vCard file from the PHP application and attach it to the message.

It's worth bearing a few things in mind when attaching files to SMS messages.

  • When Twilio retrieves attachments, they must have an accepted content type header. PHP's built-in web server, which we'll use to run the application, will send the header automatically with the value text/x-vcard; charset=UTF-8.
  • Because of carrier-imposed size limitations, Twilio recommends that attachments are 600 kb or smaller
  • You can send up to 10 attachments with an SMS, as long as the total size of the message body text and all attachments is less than 5 MB

On points 2 and 3, it's likely that most vCards will never approach that size. However, if you start adding sounds and photos, they might.

If you're curious about what the vCard file looks like, open it in your text editor or IDE, where you should see something similar to the following.

BEGIN:VCARD
VERSION:4.0
PRODID:-//Sabre//Sabre VObject 4.5.3//EN
UID:sabre-vobject-f57681da-78c2-4ac9-874b-26d379b6af3f
FN:Twilio Number
ORG:Twilio
TEL:+12111111131
TITLE:Twilio
URL;VALUE=URI:https://twilio.com/docs
BDAY:20080318T000000Z
END:VCARD

Test the application

With the code written, it's time to test that the application works. To do that, first start the application, by running the command below.

php -S 0.0.0.0:8080 -t public/

Then, start ngrok running to provide a publicly facing URL to the application, by running the following command.

ngrok http 8080

From the terminal output, copy the Forwarding URL and paste it into .env in place of the placeholder for NGROK_URL.

Then, run the command below, after replacing the placeholder with the ngrok Forwarding URL.

curl <NGROK_URL>

You should see the following output in the terminal.

Creating VCard...
VCard created successfully.
File is available at: twilio-vcard-sms/public/assets/twilio.vcf.

Sending VCard via SMS...
VCard was successfully sent via SMS to: +12111111131.
Message SID is: MM30f8f2c264d7a1044642d82d775a03bd.

Shortly after that, you should receive an SMS with the vCard attached, similar to the screenshot below (allowing for my German mobile).

A vCard received in an SMS in iOS

After you click on the vCard, it will download and open in your phone's contact application, similar to the screenshot below.

A vCard opened in the iOS Contacts app

If Firefox is your default browser on iOS, the vCard will not open in contacts. Rather, you will only be given the option to save the file in the phone's storage. I've not checked how this works if Google Chrome is your default browser, or on Android.

That's how to send a vCard with Twilio SMS and PHP

Now, if your users need to send contacts to other people, they can now send a vCard quickly and easily. No longer do they need to copy and paste details into an SMS or an email.

Do you see yourself using them in your PHP applications? Let me know on Twitter. I can't wait to see what you build!

You can find the entire code for this tutorial in the accompanying GitHub repository if you're interested.

Matthew Setter is a PHP Editor in the Twilio Voices team. He’s also the author of Mezzio Essentials and Docker Essentials. You can find him at msetter[at]twilio.com, LinkedIn, and GitHub.

"Android Keyboard" by Azamat Bohed is licenced under the CC BY 2.0.