-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathpublish.php
More file actions
72 lines (61 loc) · 2.6 KB
/
publish.php
File metadata and controls
72 lines (61 loc) · 2.6 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
71
72
<?php
// Include Composer autoloader (adjust path if needed)
require_once 'vendor/autoload.php';
use PubNub\PNConfiguration;
use PubNub\PubNub;
use PubNub\Exceptions\PubNubServerException;
use PubNub\Exceptions\PubNubException;
// snippet.publish_complete
// Create configuration with demo keys
$pnConfig = new PNConfiguration();
$pnConfig->setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo");
$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo");
$pnConfig->setUserId("php-publisher-demo");
// Initialize PubNub instance
$pubnub = new PubNub($pnConfig);
try {
// Create message data
$messageData = [
"text" => "Hello from PHP SDK!",
"timestamp" => time(),
"sender" => [
"name" => "PHP Publisher",
"id" => "php-demo"
]
];
// Publish a message to a channel
$result = $pubnub->publish()
->channel("hello_world") // Channel to publish to
->message($messageData) // Message content
->shouldStore(true) // Store in history
->ttl(15) // Time to live (hours)
->usePost(true) // Use POST method
->customMessageType("text-message") // Custom message type
->sync(); // Execute synchronously
// Display success message with timetoken
echo "Message published successfully!" . PHP_EOL;
echo "Timetoken: " . $result->getTimetoken() . PHP_EOL;
// Convert timetoken to readable date
$timestamp = floor($result->getTimetoken() / 10000000);
$readableDate = date('Y-m-d H:i:s', $timestamp);
echo "Published at: " . $readableDate . PHP_EOL;
// Display published message
echo PHP_EOL . "Published message: " . PHP_EOL;
echo json_encode($messageData, JSON_PRETTY_PRINT) . PHP_EOL;
} catch (PubNubServerException $exception) {
// Handle PubNub server-specific errors
echo "Error publishing message: " . $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 (PubNubException $exception) {
// Handle PubNub-specific errors
echo "PubNub Error: " . $exception->getMessage() . PHP_EOL;
} catch (Exception $exception) {
// Handle general exceptions
echo "Error: " . $exception->getMessage() . PHP_EOL;
}
// snippet.end