minimal micropub media endpoint

raw

micropub-media-endpoint.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
/**
 * Minimal micropub media endpoint
 *
 * @author Christian Weiske <cweiske@cweiske.de>
 */
function error($code, $error, $description)
{
    header('HTTP/1.0 ' . $code);
    header('Content-type: application/json');
    echo json_encode(
        ['error' => $error, 'error_description' => $description]
    ) . "\n";
    exit(1);
}
 
if (!isset($_FILES['file'])) {
    error(400, 'invalid_request', 'file property missing');
}
$file = $_FILES['file'];
if (!is_int($file['error'])) {
    error(400, 'invalid_request', 'file not uploaded correctly');
}
if ($file['error'] != 0) {
    error(
        400, 'invalid_request',
        'file upload failed; php upload error' . $file['error']
    );
}
 
$reldir = '/micropub-media-endpoint/' . microtime(true) . '/';
if (!is_dir(__DIR__ . $reldir)) {
    $ok = mkdir(__DIR__ . $reldir, 0700, true);
    if (!$ok) {
        error(403, 'forbidden', 'Failed to create upload directory');
    }
}
if ($file['name'] == '') {
    $file['name'] = 'file.dat';
}
$relfile = $reldir . $file['name'];
$ok = move_uploaded_file($file['tmp_name'], __DIR__ . $relfile);
if (!$ok) {
    error(500, 'internal_error', 'Failed to move uploaded file');
}
 
$dir = dirname($_SERVER['PHP_SELF']);
header('HTTP/1.1 201 Created');
//RFC 7231 allows relative URIs in location header
header('Location: ' . str_replace('//', '/', $dir . $relfile));
?>
 
Christian Weiske Christian Weiske
owner

History