-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathfiles.php
More file actions
70 lines (57 loc) · 2.39 KB
/
files.php
File metadata and controls
70 lines (57 loc) · 2.39 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
// Include Composer autoloader (adjust path if needed)
require_once 'vendor/autoload.php';
use PubNub\PNConfiguration;
use PubNub\PubNub;
use PubNub\Exceptions\PubNubServerException;
// Create configuration
$pnConfig = new PNConfiguration();
$pnConfig->setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo");
$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo");
$pnConfig->setUserId("php-file-upload-demo");
// Initialize PubNub instance
$pubnub = new PubNub($pnConfig);
try {
// Define channel and file paths
$channelName = "file-sharing-channel";
$fileName = "example.txt";
$filePath = __DIR__ . DIRECTORY_SEPARATOR . $fileName;
// Create a sample file if it doesn't exist
if (!file_exists($filePath)) {
file_put_contents($filePath, "This is a sample file for PubNub file upload demo.");
}
// Open file handle for reading
$fileHandle = fopen($filePath, "r");
// Send file to the channel
$sendFileResult = $pubnub->sendFile()
->channel($channelName)
->fileName($fileName)
->message("Hello from PHP SDK")
->fileHandle($fileHandle)
->sync();
// Close file handle
fclose($fileHandle);
// Print success message
echo "File uploaded successfully!" . PHP_EOL;
echo "File name: " . $sendFileResult->getFileName() . PHP_EOL;
echo "File ID: " . $sendFileResult->getFileId() . PHP_EOL;
// Example of how to download this file
echo PHP_EOL . "To download this file, use:" . PHP_EOL;
echo '$result = $pubnub->downloadFile()' . PHP_EOL;
echo ' ->channel("' . $channelName . '")' . PHP_EOL;
echo ' ->fileId("' . $sendFileResult->getFileId() . '")' . PHP_EOL;
echo ' ->fileName("' . $sendFileResult->getFileName() . '")' . PHP_EOL;
echo ' ->sync();' . PHP_EOL;
} catch (PubNubServerException $exception) {
// Handle PubNub-specific errors
echo "Error uploading file: " . $exception->getMessage() . PHP_EOL;
if (method_exists($exception, 'getServerErrorMessage') && $exception->getServerErrorMessage()) {
echo "Server Error: " . $exception->getServerErrorMessage() . PHP_EOL;
}
if (method_exists($exception, 'getStatusCode') && $exception->getStatusCode()) {
echo "Status Code: " . $exception->getStatusCode() . PHP_EOL;
}
} catch (Exception $exception) {
// Handle general exceptions
echo "Error: " . $exception->getMessage() . PHP_EOL;
}