PHP Master | Access the Windows Registry with PHP
Key Takeaways
- The Windows Registry, a hierarchically structured database storing configuration information, can be accessed with PHP using the win32std extension, which can be downloaded as a pre-compiled library from downloads.php.net/pierre/.
- The Windows Registry is divided into five main groups known as keys: HKEY_CURRENT_CONFIG, HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CLASSES_ROOT, and HKEY_CURRENT_USER. Each key contains subkeys which in turn contain other subkeys, configuration values, or both.
- The reg_open_key() function opens a connection to the registry and returns a resource, which can be used with other registry functions to act on that connection. The reg_close_key() function closes the connection. The reg_set_value() function is used to write a value to the registry, overwriting existing values or creating new ones.
- The Windows Registry can be used for practical applications such as storing configuration information for web-based applications, storing application data and user preferences for desktop applications, or verifying the presence of hardware devices like a USB dongle. However, modifying the registry should be done with caution as it can affect the system’s operation.
The Registry Layout
The registry has a reputation of being a dark, dangerous and scary place in the Windows operating system. This is probably an over exaggerated fear, but still I’ll reiterate Microsoft’s registry mantra: “Before you modify the registry, back it up and make sure you understand how to restore it if a problem occurs. Improper changes could cause serious problems that may require you to reinstall your operating system.” So what does this dark, scary place look like? The Windows Registry is divided up into 5 main groups known as keys: HKEY_CURRENT_CONFIGThis key stores information about the computer’s hardware such as monitor resolution and speaker settings. You may see this key abbreviated as HKCC. HKEY_LOCAL_MACHINE
This key contains configuration information for the machine such as printers, software and networking information. The key is loaded first and then entries from the user’s profile override various values. You’ll see this key abbreviated as HKLM. HKEY_USERS
This key holds all the profiles for the local user accounts on the machine. Such things as the user’s screensaver selection, theme information and other preferences are stored here. This key is abbreviated as HKU. HKEY_CLASSES_ROOT
This key is an alias pointing to HKEY_LOCAL_MACHINESoftware which stores information about file associations and mime-types. The abbreviation is HKCR. HKEY_CURRENT_USER
This key is an alias pointing to the profile in HKEY_USERS for the currently logged in user. You’ll see this key abbreviated as HKCU. Each key contains subkeys which in turn contain other subkeys, configuration values, or both. Working under HKEY_CURRENT_USER is sufficient for playing around with a few CLI scripts and a sandbox. Only use HKEY_LOCAL_MACHINE for system-wide application data and situations where you are comfortable working with Microsoft’s security permissions. Understand what is right for your situation, know under which account PHP runs, and create your keys appropriately.
Making a Sandbox
I recommend setting up a special key for use in your scripts for the sake of safety, especially when you’re developing. To err is human and we don’t want to accidentally overwrite anything important. Organization is another reason for setting up a designated key. There’s a lot of information stored in the registry and we want to be able to locate our own values easily. Registry Editor is a Microsoft program used to view and edit the registry. To create our sandbox, go to Start, type “regedit” in the search bar, and select regedit.exe in the results list that appears. The left pane shows a tree structure of the existing keys while the right pane shows values stored within them. Expand the HKEY_CURRENT_USER node, right-click on the Software key and select New > Key from the popup context menu. Alternatively, we could have also traversed through the tree using the arrow keys so that the Software key is highlighted and select New > Key from the Edit menu. Supply a name for the key and press enter.Reading from the Registry
The reg_open_key() function opens a connection to the registry and returns a resource. This resource is then used with other registry functions to act on that connection. The reg_close_key() function closes the connection. reg_open_key() takes two arguments: first a predefined constant representing one of the five primary registry groups, then the remainder of the path to the desired key.<span><span><?php </span></span><span><span>$keyConst = HKEY_CURRENT_USER; </span></span><span> </span><span><span>// backslash is used as an escape so it must be escaped itself </span></span><span><span>$key = "Software\Intel"; </span></span><span> </span><span><span>// open the registry key HKCUSoftwareIntel </span></span><span><span>if (!($reg = @reg_open_key($keyConst, $key))) { </span></span><span> <span>throw new Exception("Cannot access registry."); </span></span><span><span>} </span></span><span><span>... </span></span><span> </span><span><span>reg_close_key($reg);</span></span>
<span><span><?php </span></span><span><span>// retrieve an array of subkeys under the current key </span></span><span><span>$subkeys = reg_enum_key($reg); </span></span><span><span>foreach ($subkeys as $index => $subkey) { </span></span><span> <span>echo "The subkey at " . $index . " is " . $subkey . "n"; </span></span><span><span>} </span></span><span> </span><span><span>// retrieve a specific subkey </span></span><span><span>$index = 2; </span></span><span><span>$subkey = reg_enum_key($reg, $index); </span></span><span><span>echo "The subkey at " . $index . " is " . $subkey . "n";</span></span>
<span><span><?php </span></span><span><span>// retrieve an array of values under a given key </span></span><span><span>$values = reg_enum_value($reg); </span></span><span><span>foreach ($values as $index => $value) { </span></span><span> <span>echo "The value at " . $index . " is " . $value . " and stores "; </span></span><span> <span>echo reg_get_value($reg, $value) . "n"; </span></span><span><span>} </span></span><span> </span><span><span>// retrieve a specific value given the index </span></span><span><span>$index = 1; </span></span><span><span>$value = reg_enum_value($reg, $index); </span></span><span><span>echo "The value at " . $index . " is " . $value . " and stores "; </span></span><span><span>echo reg_get_value($reg, $value) . "n";</span></span>
Writing to the Registry
There are a handful of data types you can choose from when reading from and writing to the registry. They’re generally of little consequence because of PHP’s dynamic nature but you do have to specify the type when you write a value. Most of the time you’ll find yourself using REG_SZ or REG_DWORD, but here’s a list of the data types exposed By the extension:- REG_DWORD – value is stored as a 32-bit long integer
- REG_SZ – value is stored as a fixed-length string
- REG_EXPAND_SZ – value is stored as a variable-length string
- REG_MULTI_SZ – value is a list of items separated by a delimiter such as a space or comma
- REG_BINARY – value is a binary string
- REG_NONE – value has no particular data type associated with it
<span><span><?php </span></span><span><span>$keyConst = HKEY_CURRENT_USER; </span></span><span> </span><span><span>// backslash is used as an escape so it must be escaped itself </span></span><span><span>$key = "Software\Intel"; </span></span><span> </span><span><span>// open the registry key HKCUSoftwareIntel </span></span><span><span>if (!($reg = @reg_open_key($keyConst, $key))) { </span></span><span> <span>throw new Exception("Cannot access registry."); </span></span><span><span>} </span></span><span><span>... </span></span><span> </span><span><span>reg_close_key($reg);</span></span>
An Example – USB Drive Dongle
You might be wondering if there’s a practical use for working with the Registry. In a web-based application, you could store your configuration information in the registry. If you’ve written a desktop application then the registry could be a good place to store all sorts of information from application data to user preferences. Windows itself writes all sorts of interesting hardware and state related information to the registry, and some of it could be useful if you’re creative enough. Suppose our PHP application has been licensed in such a way that a USB dongle is required to be attached to the server to run it. How can PHP detect the presence of the dongle? The answer on Windows lies in the Registry! Each device has a unique identifier, and so the script can search the appropriate keys for the identifier when it starts up to determine whether the dongle is plugged in or not. The first step is to determine the identifier of the device. For this example I’ll use a commodity thumbdrive. Simply plug the drive into a USB port on the computer, and then go to Start, type “device” in the search bar, and select Device Manager in the results list that appears. Find the device in Device Manager, right click the entry, and select Properties from the context menu. Then go to the Details tab of the Properties window and select “Device Instance Path” from the drop down list. The sequence of the hexadecimal numbers towards the end of the value is the device id (marked in red).<span><span><?php </span></span><span><span>$keyConst = HKEY_CURRENT_USER; </span></span><span> </span><span><span>// backslash is used as an escape so it must be escaped itself </span></span><span><span>$key = "Software\Intel"; </span></span><span> </span><span><span>// open the registry key HKCUSoftwareIntel </span></span><span><span>if (!($reg = @reg_open_key($keyConst, $key))) { </span></span><span> <span>throw new Exception("Cannot access registry."); </span></span><span><span>} </span></span><span><span>... </span></span><span> </span><span><span>reg_close_key($reg);</span></span>
In Conclusion
Throughout the course of this article we’ve seen what the Windows Registry is and a small sample of what information can be found in it. You can write your own configuration data, or you can read back information, using the functions provided by the win32std extension. By the way, the win32std extension offers more than just access to the registry. If you’re interested, check out wildphp.free.fr/wiki/doku.php?id=win32std:index to see what else it offers. Image via FotoliaFrequently Asked Questions (FAQs) about Accessing the Windows Registry from PHP
How can I access the Windows Registry from PHP?
Accessing the Windows Registry from PHP can be achieved by using the COM class in PHP. This class allows PHP to interact with any COM objects, including the Windows Registry. You can create a new instance of the COM class and then use the RegRead method to read a value from the registry. However, please note that this method requires the correct permissions to access the registry.
What is the Windows Registry and why would I need to access it from PHP?
The Windows Registry is a database that stores low-level settings for the operating system and for applications that opt to use the registry. You might need to access it from PHP for various reasons, such as to retrieve system information, check for the presence of certain software, or to modify system settings. However, modifying the registry should be done with caution as it can affect the system’s operation.
Can I write to the Windows Registry from PHP?
Yes, you can write to the Windows Registry from PHP using the RegWrite method of the COM class. However, this should be done with extreme caution as incorrect modifications can cause serious problems that may require you to reinstall your operating system.
What permissions do I need to access the Windows Registry from PHP?
To access the Windows Registry from PHP, you need to have administrative privileges. This is because the registry contains critical system and application settings. If you’re running your script from a web server, the server’s user account will also need to have the necessary permissions.
What is the structure of the Windows Registry?
The Windows Registry is organized hierarchically as a tree, with keys and values. Keys are similar to folders, and values are the data entries within the keys. Each key can contain subkeys, and each subkey can contain further subkeys, forming a tree structure.
How can I handle errors when accessing the Windows Registry from PHP?
When accessing the Windows Registry from PHP, errors can be handled using the standard PHP error handling functions. For example, you can use the set_error_handler function to define a custom error handler.
Can I access the Windows Registry from PHP on a non-Windows system?
No, you cannot access the Windows Registry from PHP on a non-Windows system. The Windows Registry is a feature specific to the Windows operating system.
What is the COM class in PHP?
The COM class in PHP is a built-in class that allows PHP to interact with COM objects. COM (Component Object Model) is a binary-interface standard for software components introduced by Microsoft. It allows PHP to interact with any COM objects, including the Windows Registry.
Can I delete keys from the Windows Registry using PHP?
Yes, you can delete keys from the Windows Registry using PHP. This can be done using the RegDelete method of the COM class. However, this should be done with extreme caution as deleting the wrong key can cause serious problems.
What are the risks of modifying the Windows Registry?
Modifying the Windows Registry carries risks. Incorrect modifications can cause serious problems that may require you to reinstall your operating system. Therefore, it’s recommended to back up the registry before making any changes and to only make changes if you’re confident in what you’re doing.
The above is the detailed content of PHP Master | Access the Windows Registry with PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
