PHP file_get_contents and ord
Write a small binary payload and read one byte as an unsigned value.
A simple example
file_get_contents and ord
- Start with Two bytes, 0 and 7
- Do this Write and read the bytes
- Result 0, 7
Syntax
ord($data[2])
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpRecover the brightest setting from a preset
A camera club stores three brightness levels in a compact binary preset. Read the saved bytes back and display the brightest setting as an unsigned number on the familiar 0–255 scale.
<?php
$base = sys_get_temp_dir() . DIRECTORY_SEPARATOR . bin2hex(random_bytes(12));
if (!mkdir($base, 0700)) throw new RuntimeException("Cannot create workspace");
try {
$preset = $base . '/preset';
if (file_put_contents($preset, pack('C*', 0, 64, 255)) !== 3) throw new RuntimeException('Write failed');
$data = file_get_contents($preset);
if ($data === false || strlen($data) !== 3) throw new RuntimeException('Incomplete preset');
echo ord($data[2]), PHP_EOL;
} finally {
foreach (['preset'] as $name) {
$path = $base . '/' . $name;
if (is_link($path) || is_file($path)) unlink($path);
elseif (is_dir($path)) rmdir($path);
}
rmdir($base);
}
255
The final byte has all eight bits set and represents 255.
Read a display preset
A museum sign saves three brightness levels as individual bytes. Read the unsigned byte at the indicated zero-based offset. Which stored sample is returned?
Read the first locker state
A desk stores two status values in a compact file. Read the unsigned byte at the indicated zero-based offset. Which stored sample is returned?
What to watch for
Text encoding can change byte values. Use binary I/O for this format.