Skip to content

Instantly share code, notes, and snippets.

@sh-sh-dev
Last active April 19, 2023 22:26
Show Gist options
  • Save sh-sh-dev/801b13dcd497ed8ec301a4c0f55863e1 to your computer and use it in GitHub Desktop.
Save sh-sh-dev/801b13dcd497ed8ec301a4c0f55863e1 to your computer and use it in GitHub Desktop.
Generate QR Code using Google service
<?php
/**
* @param string $data The data to encode. Data can be digits (0-9), alphanumeric characters, binary bytes of data, or Kanji. You cannot mix data types within a QR code. Note that URLs have a 2K maximum length, so if you want to encode more than 2K bytes (minus the other URL characters).
* @param int $width
* @param int $height
* @param int $margin The width of the white border around the data portion of the code. This is in rows, not in pixels.
* @param string $errorCorrection QR codes support four levels of error correction to enable recovery of missing, misread, or obscured data. Greater redundancy is achieved at the cost of being able to store less data. The supported values: L (Allows recovery of up to 7% data loss) | M (15%) | Q (25%) | H (30%)
* @param string $encoding How to encode the data in the QR code. The available values: UTF-8 | Shift_JIS | ISO-8859-1
* @return string URL of the QR code.
*/
function generateQrCode(string $data, int $width, int $height, int $margin = 4, string $errorCorrection = 'L', string $encoding = 'UTF-8') {
$parameters = http_build_query([
'cht' => 'qr',
'chs' => $width . 'x' . $height,
'chl' => urlencode($data),
'choe' => $encoding,
'chld' => $errorCorrection . '|' . $margin
]);
return 'https://chart.googleapis.com/chart?' . $parameters;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment