### PHP Example: Creating and Managing a Windows Service
Source: https://www.php.net/manual/en/function.win32-create-service.php
This example demonstrates how to create, install, uninstall, start, stop, and query the status of a Windows service using PHP's win32_service functions. It includes logic to handle different service actions via command-line arguments or GET parameters.
```php
[An example of how to create a Windows service. Evaluate code first and use at your own risk!]
$ServiceName,
'display' => $ServiceDisplay,
'params' => __FILE__ . " run",
'path' => $phpPath."\\php.exe",
));
echo "Service Installed\n\n";
exit;
} else if ( $ServiceAction == "uninstall" ) {
//Remove Windows Service
win32_delete_service($ServiceName);
echo "Service Removed\n\n";
exit;
} else if( $ServiceAction == "start") {
//Start Windows Service
win32_start_service($ServiceName);
echo "Service Started\n\n";
exit;
} else if( $ServiceAction == "stop" ) {
//Stop Windows Service
win32_stop_service($ServiceName);
echo "Service Stopped\n\n";
exit;
} else if ( $ServiceAction == "run" ) {
//Run Windows Service
win32_start_service_ctrl_dispatcher($ServiceName);
win32_set_service_status(WIN32_SERVICE_RUNNING);
} else if ( $ServiceAction == "debug" ) {
//Debug Windows Service
set_time_limit(10);
} else {
exit();
}
//Server Loop
while (1) {
//Handle Windows Service Request
usleep(100*1000);
if ( $ServiceAction == "run" ) {
switch ( win32_get_last_control_message() ) {
case WIN32_SERVICE_CONTROL_CONTINUE:
break;
case WIN32_SERVICE_CONTROL_INTERROGATE:
win32_set_service_status(WIN32_NO_ERROR);
break;
case WIN32_SERVICE_CONTROL_STOP:
win32_set_service_status(WIN32_SERVICE_STOPPED);
exit;
default:
win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED);
}
}
//User Loop
sleep(1);
echo "\n
YOUR CODE HERE";
}
//Exit
if ( $ServiceAction == "run" ) {
win32_set_service_status(WIN32_SERVICE_STOPPED);
}
exit();
?>
```
--------------------------------
### Example of Installation Path Output
Source: https://www.php.net/manual/en/mongodb.installation.php
The 'make install' command reports the directory where the mongodb.so extension was installed.
```text
Installing shared extensions: /usr/lib/php/extensions/debug-non-zts-20220829/
```
--------------------------------
### Basic Session Example - Page 1
Source: https://www.php.net/manual/en/function.session-start.php
This snippet demonstrates the initial setup of a session on page1.php. It starts a session, sets session variables, and provides links to navigate to page2.php, optionally passing the session ID.
```php
page 2';
// Or maybe pass along the session id, if needed
echo '
page 2';
?>
```
--------------------------------
### Windows Installation Steps
Source: https://www.php.net/manual/en/parallel.setup.php
A step-by-step guide for installing the parallel extension on Windows systems.
```text
On Windows Systems:
- Install PHP TS (Thread Safe)
- Download Extension from PECL (PHP-Version, Thread Safe (TS), Compiler - Version (VC15, VC16), Architecture must match)
- Copy extension to folder: /ext/php_parallel.dll
- Copy app to folder: /pthreadVC2.dll (It is important to copy pthreadVC2.dll not into the ext folder!)
- add pthreadVC2.dll to windows system environment path
- add in php.ini the line extension=parallel to load the extension
- restart
Try on console: php -v
If there are no errors, everything works and you can try the examples
```
--------------------------------
### PHP Installation and Configuration for OpenBSD 5.7+
Source: https://www.php.net/manual/en/install.unix.openbsd.php
User-contributed update for OpenBSD 5.7 and later, detailing installation with 'httpd' (OpenBSD's default server), 'php-fpm', and 'pear'. Includes steps to configure services to start at boot and a basic httpd.conf example.
```bash
#pkg_add php
#pkg_add php-fpm
#pkg_add pear
---- OpenBSD disables most services by default; a blank '_flags' line overrides default 'NO' value. pkg_scripts are located in /etc/rc.d/
To start at boot, edit "/etc/rc.conf.local":
httpd_flags=
pkg_scripts=php_fpm
---- Example /etc/httpd.conf
#
# paths are relative to chroot - e.g, '/var/www/run/php-fpm.sock'
server "default" {
listen on * port 80
location "*.php" {
fastcgi socket "/run/php-fpm.sock"
}
directory index index.php
root "/htdocs"
}
---- For date, timezone issues, copy /etc/localtime:
$cp /etc/localtime /var/www/etc/localtime
If 'localhost' DNS name fails to resolve, copy /etc/hosts
$cp /etc/hosts /var/www/etc/hosts
```
--------------------------------
### Start Apache Server
Source: https://www.php.net/manual/en/install.unix.apache2.php
Start the Apache server after installation. The default installation path is /usr/local/apache2.
```bash
/usr/local/apache2/bin/apachectl start
```
--------------------------------
### Composer Installation Output Example
Source: https://www.php.net/manual/en/mongodb.tutorial.library.php
This is an example of the output you can expect when running the Composer installation command for the MongoDB PHP library.
```text
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
- Installing mongodb/mongodb (1.0.0)
Downloading: 100%
Writing lock file
Generating autoload files
```
--------------------------------
### Start PHP-FPM Service
Source: https://www.php.net/manual/en/install.unix.nginx.php
Starts the PHP-FPM service using the installed binary. This command should be run after all configurations are in place.
```bash
sudo /usr/local/bin/php-fpm
```
--------------------------------
### Imagick Installation Guide for Windows
Source: https://www.php.net/manual/en/imagick.requirements.php
This guide provides instructions for installing the Imagick extension on Windows, including where to download different versions of the Imagick extension and ImageMagick library, and the necessary configuration steps for PHP and web servers.
```text
Imagick multiple versions available on https://windows.php.net/downloads/pecl/releases/imagick/
You can download ImageMagick library (many versions) from https://windows.php.net/downloads/pecl/deps/
The installation instruction is in https://mlocati.github.io/articles/php-windows-imagick.html
== Copied from the above URL ==
1. Extract from php_imagick-….zip the php_imagick.dll file, and save it to the ext directory of your PHP installation
2. Extract from ImageMagick-….zip the DLL files located in the bin folder that start with CORE_RL or IM_MOD_RL, and save them to the PHP root directory (where you have php.exe), or to a directory in your PATH variable
3. Add this line to your php.ini file: extension=php_imagick.dll
4. Restart the Apache/NGINX Windows service (if applicable)
```
--------------------------------
### Oracle 9i Init Script Example
Source: https://www.php.net/manual/en/oci8.installation.php
An example init script for starting and stopping the Oracle 9i database server and TNS listener.
```bash
#!/bin/bash
export ORACLE_HOME=/opt/ora9/product/9.2
export PATH=$ORACLE_HOME/bin:$PATH
export ORACLE_SID=netadmdb
export DISPLAY=:0
oracle_user=oracle
export oracle_user
case $1 in
start)
su - "$oracle_user"<
```
--------------------------------
### PHP Image Signature Example
Source: https://www.php.net/manual/en/imagick.getimagesignature.php
This example demonstrates how to get the image signature using the Imagick class. Ensure Imagick is installed and the image path is correct.
```php
$imagick = new Imagick('image.jpg');
$signature = $imagick->getImageSignature();
print "Image Signature: $signature\n";
$imagick->clear();
$imagick->destroy();
```
--------------------------------
### CollectionFind Example
Source: https://www.php.net/manual/en/mysql-xdevapi-collectionfind.execute.php
Demonstrates setting up a session, creating a database and collection, adding a document, and then performing a find operation with bound parameters. The results are fetched using fetchAll().
```php
sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();
// ...
$collection = $schema->getCollection("people");
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->execute();
var_dump($result->fetchAll());
?>
```
--------------------------------
### Swoole\Server::start
Source: https://www.php.net/manual/en/indexes.functions.php
Starts the Swoole server.
```APIDOC
## Swoole\Server::start
### Description
Start the Swoole server.
### Method
N/A (This is a class method)
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
#### Success Response
N/A
#### Response Example
N/A
```
--------------------------------
### ibase_backup() Example with Options
Source: https://www.php.net/manual/en/function.ibase-backup.php
This example shows how to attach to a database server and initiate a backup with specific options, such as backing up only metadata and not creating a transportable backup.
```php
```
--------------------------------
### Get variants using object-oriented style
Source: https://www.php.net/manual/en/locale.getallvariants.php
This example shows the object-oriented approach using `Locale::getAllVariants` to get locale variants. The intl extension must be installed and enabled.
```php
```
--------------------------------
### Example of sqlsrv_rows_affected()
Source: https://www.php.net/manual/en/function.sqlsrv-rows-affected.php
This example demonstrates how to use sqlsrv_rows_affected to get the number of rows updated by an UPDATE query. It includes connection setup, query execution, and error handling for both the query and the rows_affected call.
```php
"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1 SET data = ? WHERE id = ?";
$params = array("updated data", 1);
$stmt = sqlsrv_query( $conn, $sql, $params);
$rows_affected = sqlsrv_rows_affected( $stmt);
if( $rows_affected === false) {
die( print_r( sqlsrv_errors(), true));
} elseif( $rows_affected == -1) {
echo "No information available.
";
} else {
echo $rows_affected." rows were updated.
";
}
?>
```
--------------------------------
### Starting the Web Server
Source: https://www.php.net/manual/en/features.commandline.webserver.php
Starts the built-in web server from the command line. Ensure you are in the directory you want to serve as the document root.
```bash
$ cd ~/public_html
$ php -S localhost:8000
```
--------------------------------
### Swoole\Http\Server Start
Source: https://www.php.net/manual/en/indexes.functions.php
Starts the Swoole HTTP server.
```APIDOC
## Swoole\Http\Server::start
### Description
Start the swoole http server.
### Method
start
### Parameters
None explicitly documented in the provided text.
### Request Example
None provided.
### Response
None provided.
```
--------------------------------
### Swoole\Process::start
Source: https://www.php.net/manual/en/indexes.functions.php
Starts the process.
```APIDOC
## Swoole\Process::start
### Description
Start the process.
### Method
N/A (This is a class method)
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
#### Success Response
N/A
#### Response Example
N/A
```
--------------------------------
### Authentication Troubleshooting Note
Source: https://www.php.net/manual/en/features.http-auth.php
A brief note indicating that the user had trouble getting authentication to work with provided examples and started from a Zend tutorial.
```text
I couldn't get authentication to work properly with any of the examples. Finally, I started from ZEND's tutorial example at:
```
--------------------------------
### Basic ibase_backup() Example
Source: https://www.php.net/manual/en/function.ibase-backup.php
This example demonstrates how to attach to a database server, initiate a basic backup of a database file, and then detach from the server.
```php
```
--------------------------------
### Getting Method Body with an Extension
Source: https://www.php.net/manual/en/reflectionclass.getmethod.php
Shows how to access the body of a method using a third-party reflection extension. This example requires installing the 'sagittaracc/reflection' package.
```php
namespace sagittaracc\classes;
class Test
{
public function method()
{
if (true) {
return 'this method';
}
return 'never goes here';
}
}
$reflection = new ReflectionClass(Test::class);
$method = $reflection->getMethod('method');
echo $method->body; // if (true) { return 'this method'; } return 'never goes here';
```
--------------------------------
### Listing Supported Algorithms
Source: https://www.php.net/manual/en/function.mcrypt-list-algorithms.php
This example demonstrates how to get a list of all supported encryption algorithms by calling mcrypt_list_algorithms(). The output will vary based on the installed mcrypt library.
```php
```
--------------------------------
### Setting up Oracle Instant Client for Red Hat (x86_32)
Source: https://www.php.net/manual/en/oci8.installation.php
Installs Oracle Instant Client basic and SDK files on a Red Hat system for PHP 5.1.2. This involves creating directories, unzipping files, and creating symbolic links.
```bash
mkdir -p /usr/lib/oracle/10.2.0.2/client
unzip -jd /usr/lib/oracle/10.2.0.2/client \
instantclient-basic-linux-x86-32-10.2.0.2-20060331.zip
mkdir -p /usr/include/oracle/10.2.0.2/client
unzip -jd /usr/lib/oracle/10.2.0.2/client \
instantclient-sdk-linux-x86-32-10.2.0.2-20060331.zip
ln -s /usr/lib/oracle/10.2.0.2/client/libclntsh.so.10.1 \
/usr/lib/oracle/10.2.0.2/client/libclntsh.so
```
--------------------------------
### Example of mysql_xdevapi\CollectionFind::lockExclusive()
Source: https://www.php.net/manual/en/mysql-xdevapi-collectionfind.lockexclusive.php
This example demonstrates how to lock a document exclusively using lockExclusive() within a transaction. It retrieves a session, gets a schema and collection, starts a transaction, finds documents matching a criteria, locks them exclusively, and then commits the transaction.
```php
getSchema("addressbook");
$collection = $schema->createCollection("people");
$session->startTransaction();
$result = $collection
->find("age > 50")
->lockExclusive()
->execute();
// ... do an operation on the object
// Complete the transaction and unlock the document
$session->commit();
?>
```
--------------------------------
### Basic ibase_restore() Example
Source: https://www.php.net/manual/en/function.ibase-restore.php
This example demonstrates how to attach to a database server and initiate a basic restore process without any special arguments. Ensure you have a valid service handle and correct file paths.
```php
```
--------------------------------
### Enchant Usage Example
Source: https://www.php.net/manual/en/enchant.examples.php
This example demonstrates initializing the Enchant broker, listing available backends and dictionaries, requesting a specific dictionary, checking word correctness, and getting suggestions for misspelled words. Ensure you have the necessary dictionaries installed for your system.
```php
```
--------------------------------
### Windows OCI8 Instant Client 10g Setup Guide
Source: https://www.php.net/manual/en/oci8.installation.php
A step-by-step guide for setting up Oracle Instant Client 10g on Windows for use with OCI8. It covers downloading, configuring TNS_ADMIN, and registry settings.
```text
1. Download and install the Oracle Instant Client to where ever (lets say c:\ora\client )
2. Add your connect info, copy a previously created or provided tnsnames.ora file to the above directory.
3. Change Path in the Environment Variables area to add this directory to the path. ie. c:\ora\client;%SystemRoot%;
4. Open regedit and add a Key called ORACLE to HKEY_LOCAL_MACHINE\SOFTWARE
5. To the ORACLE key add a string value called TNS_ADMIN and assign it the directory above (ie. c:\ora\client ) So you end up with KEY_LOCAL_MACHINE\SOFTWARE\ORACLE\TNS_ADMIN = c:\ora\client
6. Set php to use Oci8 extension and bobs your uncle
7. Reboot.
```
--------------------------------
### QuickHashIntHash::loadFromFile() Example
Source: https://www.php.net/manual/en/quickhashinthash.loadfromfile.php
Demonstrates loading a QuickHashIntHash from a file and checking the existence of keys. Uses DO_NOT_USE_ZEND_ALLOC option.
```php
exists( $key ) ? 'set' : 'unset'
);
}
?>
```
--------------------------------
### Getting the trace of an executing generator
Source: https://www.php.net/manual/en/reflectiongenerator.gettrace.php
This example demonstrates how to use ReflectionGenerator::getTrace() to obtain the call stack of a generator. It starts by defining nested generator functions and then instantiates a ReflectionGenerator to capture the trace.
```php
valid(); // start the generator
var_dump((new ReflectionGenerator($gen))->getTrace());
```
--------------------------------
### QuickHashIntSet::__construct() Example
Source: https://www.php.net/manual/en/quickhashintset.construct.php
Demonstrates creating a new QuickHashIntSet with different configurations for size and options, including checking for duplicates and specifying hashing algorithms.
```php
```
--------------------------------
### SQLite3::__construct() Example
Source: https://www.php.net/manual/en/sqlite3.construct.php
Demonstrates creating an SQLite3 database file, creating a table, inserting data, and querying it.
```php
exec('CREATE TABLE foo (bar TEXT)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");
$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>
```
--------------------------------
### Reading a symbolic link with ssh2_sftp_readlink
Source: https://www.php.net/manual/en/function.ssh2-sftp-readlink.php
This example demonstrates how to establish an SSH2 connection, authenticate, open an SFTP session, and then use ssh2_sftp_readlink to get the target of a symbolic link. Ensure you have the ssh2 extension installed and configured.
```php
```
--------------------------------
### Launching Apache SSL Server on Windows
Source: https://www.php.net/manual/en/ref.exec.php
Demonstrates how to use the 'start' command in Windows to launch a specific Apache SSL server. The '/D' option specifies the directory, and '/B' launches the application without a console window.
```php
$cmd = "start /D C:\OpenSA\Apache /B Apache.exe -D SSL";
exec($cmd,$output,$rv);
```
```php
exec("start /? > start.txt");
```
```php
exec("COMMAND.COM /C START program args >NUL");
```
--------------------------------
### Install Oracle Instant Client
Source: https://www.php.net/manual/en/oci8.installation.php
Installs the Oracle Instant Client basic and SDK packages, creating necessary directories and symbolic links for the client library.
```bash
mkdir -p /usr/lib/oracle/10.2.0.2/client/lib
unzip -jd /usr/lib/oracle/10.2.0.2/client/lib instantclient-basic-linux-x86-64-10.2.0.2-20060228.zip
mkdir -p /usr/include/oracle/10.2.0.2/client
unzip -jd /usr/lib/oracle/10.2.0.2/client instantclient-sdk-linux-x86-64-10.2.0.2-20060228.zip
ln -s /usr/lib/oracle/10.2.0.2/client/lib/libclntsh.so.10.1 /usr/lib/oracle/10.2.0.2/client/lib/libclntsh.so
```
--------------------------------
### Stringable::__toString
Source: https://www.php.net/manual/en/indexes.functions.php
Gets a string representation of the object.
```APIDOC
## Stringable::__toString
### Description
Gets a string representation of the object.
### Method
Stringable::__toString
### Parameters
None explicitly documented in the source.
### Response
Returns a string representation of the object.
```
--------------------------------
### Basic fopen() Examples
Source: https://www.php.net/manual/en/function.fopen.php
Demonstrates opening files and URLs using fopen() with different modes.
```php
```
--------------------------------
### Updated Ban URL with VarnishAdmin (User Contribution)
Source: https://www.php.net/manual/en/varnish.example.admin.php
A user-contributed update to the VarnishAdmin ban example, adjusting the URL pattern and host configuration. This version may be more suitable for specific local setups after installing the PECL extension.
```php
"127.0.0.1",
VARNISH_CONFIG_PORT => 6082,
VARNISH_CONFIG_SECRET => "5174826b-8595-4958-aa7a-0609632ad7ca",
VARNISH_CONFIG_TIMEOUT => 300,
);
$va = new VarnishAdmin($args);
try {
if(!$va->connect()) {
throw new VarnishException("Connection failed\n");
}
} catch (VarnishException $e) {
echo $e->getMessage();
exit(3);
}
try {
if(!$va->auth()) {
throw new VarnishException("Auth failed\n");
}
} catch (VarnishException $e) {
echo $e->getMessage();
exit(3);
}
try {
$status = $va->ban('req.url ~ "^/."');
if (VARNISH_STATUS_OK != $status) {
throw new VarnishException("Ban method returned $status status\n");
}
} catch (VarnishException $e) {
echo $e->getMessage();
exit(3);
}
exit(0);
?>
```
--------------------------------
### swoole_event_wait
Source: https://www.php.net/manual/en/indexes.functions.php
Starts the event loop, which begins processing events and executing registered callbacks. This function blocks until the event loop is terminated.
```APIDOC
## swoole_event_wait
### Description
Start the event loop.
### Method
Not specified (global function)
### Parameters
None.
### Response
void. The function blocks until the event loop exits.
```
--------------------------------
### eio_mkdir() Example
Source: https://www.php.net/manual/en/function.eio-mkdir.php
Demonstrates how to use eio_mkdir to create a directory with specific permissions and a callback function to verify and clean up the directory. Requires the Eio extension.
```php
```
--------------------------------
### Setting and getting cache expire
Source: https://www.php.net/manual/en/function.session-cache-expire.php
This example demonstrates how to set the cache limiter, then set and retrieve the cache expiration time in minutes. It also shows how to start a session and display the configured values. Remember to call session_cache_expire() before session_start().
```php
";
echo "The cached session pages expire after $cache_expire minutes";
?>
```
--------------------------------
### Start the HTTP Server
Source: https://www.php.net/manual/en/class.swoole-websocket-server.php
The `start` method initiates the Swoole HTTP server, making it ready to accept connections and handle events.
```php
public function Swoole\Http\Server::start(): void
```
--------------------------------
### Creating a Gradient Image with Pixel Setting
Source: https://www.php.net/manual/en/function.imagesetpixel.php
This example generates a JPEG image with a horizontal or vertical gradient based on start and end colors provided via GET parameters. It uses imagesetpixel() within nested loops to color each pixel.
```php
$width=$_GET['width'];
$height=$_GET['height'];
$starts=explode(",",$_GET['startcolor']);
$ends=explode(",",$_GET['endcolor']);
$rstart=$starts[0];
$gstart=$starts[1];
$bstart=$starts[2];
$rend=$ends[0];
$gend=$ends[1];
$bend=$ends[2];
$r=$rstart;
$g=$gstart;
$b=$bstart;
$bigger=imagecreatetruecolor($width,$height);
for ($y=0;$y<=265;$y++) {
if ($mode == 'horiz') { //if doing a horizontal gradient, reset to the starting color every row
$r=$rstart;
$g=$gstart;
$b=$bstart;
}
for ($x=0;$x<=464;$x++) {
imagesetpixel($bigger,$x,$y,imagecolorallocate($bigger,$r,$g,$b));
if ($mode=="horiz") {
if ($r != $rend) {
$r=$r+(($rend-$rstart)/$width);
}
if ($g != $gend) {
$g=$g+(($gend-$gstart)/$width);
}
if ($b != $bend) {
$b=$b+(($bend-$bstart)/$width);
}
}
}
if ($mode == "vert") {
if ($r != $rend) {
$r=$r+(($rend-$rstart)/$height);
}
if ($g != $gend) {
$g=$g+(($gend-$gstart)/$height);
}
if ($b != $bend) {
$b=$b+(($bend-$bstart)/$height);
}
}
}
header("Content-type: image/jpeg");
header('Content-Disposition: inline; filename="gradient.jpg"');
imagejpeg($bigger,NULL,99);
imagedestroy($bigger);
?>
```
--------------------------------
### SoapServer::__construct() Example
Source: https://www.php.net/manual/en/soapserver.construct.php
Demonstrates various ways to instantiate SoapServer using different WSDL modes and options.
```php
SOAP_1_2));
$server = new SoapServer("some.wsdl", array('actor' => "http://example.org/ts-tests/C"));
$server = new SoapServer("some.wsdl", array('encoding'=>'ISO-8859-1'));
$server = new SoapServer(null, array('uri' => "http://test-uri/"));
class MyBook {
public $title;
public $author;
}
$server = new SoapServer("books.wsdl", array('classmap' => array('book' => "MyBook")));
?>
```
--------------------------------
### Get Week Boundaries and Navigate Weeks with IntlCalendar
Source: https://www.php.net/manual/en/class.intlcalendar.php
This example demonstrates how to obtain the current week's start and end dates, and calculate the dates for the previous and next weeks using the IntlCalendar class. It's useful for building calendar views.
```php
set(IntlCalendar::FIELD_DAY_OF_WEEK, $thisWeek->getFirstDayOfWeek());
// $thisWeek now points to the first day of the week
$weekStart = $thisWeek->toDateTime();
$daysToAdvance = $thisWeek->getMaximum(IntlCalendar::FIELD_DAY_OF_WEEK) - 1;
// Maximum number of days in a week minus 1 gets you to the last day
$weekEnd = $weekStart->modify("+{$daysToAdvance} days");
$previousWeek = IntlCalendar::fromDateTime($date, $locale);
$previousWeek->add(IntlCalendar::FIELD_WEEK_OF_YEAR, -1);
$previousWeek = $previousWeek->toDateTime();
$nextWeek = IntlCalendar::fromDateTime($date, $locale);
$nextWeek->add(IntlCalendar::FIELD_WEEK_OF_YEAR, 1);
$nextWeek = $nextWeek->toDateTime();
?>
```
--------------------------------
### Execute Command and Play Song on Windows
Source: https://www.php.net/manual/en/ref.exec.php
Use the 'start' utility to execute a command and open a file with its default application. This is useful for playing media files.
```php
exec("start song.mp3");
```
--------------------------------
### Basic GET Input Filtering Example
Source: https://www.php.net/manual/en/function.filter-input-array.php
A simple example demonstrating how to filter GET input using filter_request, with a predefined array of expected keys and default values.
```php
'DEFAULT',
'b' => array(
'c' => 'DEFAULT',
'd' => 'DEFAULT',
),
)));
?>
Sample Result:
array(2) {
["a"]=>
string(21) "DEFAULT"
["b"]=>
array(2) {
["c"]=>
string(12) "CORRECT"
["d"]=>
string(21) "DEFAULT"
}
}
```
--------------------------------
### QuickHashIntHash::__construct() Example
Source: https://www.php.net/manual/en/quickhashinthash.construct.php
Demonstrates creating a new QuickHashIntHash object with different configurations for size and options.
```php
```
--------------------------------
### QuickHashIntSet::loadFromFile Example
Source: https://www.php.net/manual/en/quickhashintset.loadfromfile.php
This example demonstrates how to load a QuickHashIntSet from a file and check for the existence of keys. It iterates through a range of keys and prints whether each key is set or unset in the loaded set. Ensure the 'simple.set' file exists and is correctly formatted.
```php
exists( $key ) ? 'set' : 'unset'
);
}
?>
```
--------------------------------
### Basic Key Generation and Encryption/Decryption in PHP
Source: https://www.php.net/manual/en/function.openssl-private-encrypt.php
This is a simplified example for getting started with PHP's OpenSSL encryption capabilities. It shows how to generate a new private and public key pair, export them, and then demonstrates encrypting data with the private key and decrypting it with the public key.
```PHP
$res = openssl_pkey_new();
// Get private key
openssl_pkey_export($res, $privkey);
// Get public key
$pubkey = openssl_pkey_get_details($res);
$pubkey = $pubkey["key"];
var_dump($privkey);
var_dump($pubkey);
// get some text from command line to work with
$tocrypt = trim(fgets(STDIN));
// some variables to work with
$encryptedviaprivatekey = ""; //holds text encrypted with the private key
$decryptedviapublickey = ""; // holds text which was decrypted by the public key after being encrypted with the private key, should be same as $tocrypt
$encryptedviapublickey = ""; // holds text that was encrypted with the public key
$decryptedviaprivatekey = ""; // holds text that was decrypted with the private key after being encrypted with the public key, should be the same as $tocrypt
```
--------------------------------
### PHP OCI8 Configuration Example
Source: https://www.php.net/manual/en/oci8.installation.php
This example demonstrates how to configure PHP with OCI8 support during the configure step. Ensure you replace '/path/to/ORACLE_HOME' with your actual Oracle installation path.
```bash
CC=gcc ./configure --with-apxs=/usr/local/apache/bin/apxs \
--with-config-file-path=/etc \
--with-mysql \
--enable-ftp \
--with-oci8=/path/to/ORACLE_HOME \
--with-oracle=/path/to/ORACLE_HOME \
--enable-sigchild
```
--------------------------------
### Loop Through Multiple IPs to Get SNMP Data
Source: https://www.php.net/manual/en/function.snmpget.php
This example iterates through a comma-separated list of IP addresses or DNS names to fetch system name, description, location, open TCP connections, and uptime. It also includes a check for Windows systems to retrieve installed memory.
```php
';
//system description
$sysdesc[0] = snmpget($sysip[$i], $snmpcommunity, "sysDescr.0");
$sysdesc[1] = eregi_replace("STRING:","",$sysdesc[0]);
echo 'System Description: '.$sysdesc[1].'
';
//system location
$sysloc[0] = snmpget($sysip[$i], $snmpcommunity, "sysLocation.0");
$sysloc[1] = eregi_replace("STRING:","",$sysloc[0]);
echo 'System Location: '.$sysloc[1].'
';
//current tcp connections
$tcpcons[0] = snmpget($sysip[$i], $snmpcommunity, "tcpCurrEstab.0");
$tcpcons[1] = eregi_replace("Gauge32:","",$tcpcons[0]);
echo 'Open TCP/IP Connections: '.$tcpcons[1].'
';
//get system uptime
$sysuptime[0] = snmpget($sysip[$i], $snmpcommunity, "system.sysUpTime.0");
$sysuptime[1] = eregi_replace("Timeticks:","",$sysuptime[0]);
echo 'System Uptime: Timeticks -'.$sysuptime[1].'
';
//windows only
//installed memory
if(eregi('Windows',$sysdesc[1])){
$mem[0] = snmpget($sysip[$i], $snmpcommunity, "HOST-RESOURCES-MIB::hrMemorySize.0");
$mem[1] = eregi_replace("INTEGER:","",$mem[0]);
$mem[2] = eregi_replace("KBytes","",$mem[1]);
echo 'Insalled Memory: '.$mem[2].' KiloBytes
';
}
echo '
';
}//end loop
?>
```
--------------------------------
### Get Hash Name Example
Source: https://www.php.net/manual/en/function.mhash-get-hash-name.php
Demonstrates how to get the name of the MD5 hash algorithm using its constant.
```php
```
--------------------------------
### Quickhash Example: Creating, Adding, and Saving an Integer Set
Source: https://www.php.net/manual/en/quickhash.examples.php
Demonstrates the creation of a QuickHashIntSet, adding integer values, checking for their existence, and saving the set to a file for later retrieval.
```php
add( 1 );
$set->add( 3 );
var_dump( $set->exists( 3 ) );
var_dump( $set->exists( 4 ) );
$set->saveToFile( "/tmp/test-set.set" );
$newSet = QuickHashIntSet::loadFromFile(
"/tmp/test-set.set"
);
var_dump( $newSet->exists( 3 ) );
var_dump( $newSet->exists( 4 ) );
?>
```
--------------------------------
### Create a Windows Service with Dependencies
Source: https://www.php.net/manual/en/function.win32-create-service.php
This example shows how to create a Windows service and specify its dependencies. The 'dependencies' parameter takes an array of service names that must be running before this service can start.
```php
'dummyphp',
'display' => 'sample dummy PHP service',
'description' => 'This is a dummy Windows service created using PHP.',
'params' => '"' . __FILE__ . '" run',
'dependencies' => array("Netman"),
));
debug_zval_dump($x);
?>
```
--------------------------------
### strftime() Locale Examples
Source: https://www.php.net/manual/en/function.strftime.php
Demonstrates how strftime() outputs the full day name based on different installed locales (C, Finnish, French, German). Ensure the respective locales are installed on your system for this example to work correctly.
```php
open('mysqlitedb.db');
}
}
$db = new MyDB();
$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");
$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>
```