Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development

PHP and .NET

Andrew Stopford, author of "PHP Programming for Windows," shows you how PHP can be used within the .NET framework.
Like this article? We recommend

Like this article? We recommend

Using PHP with .NET

In this article we will look at Microsoft .NET and how you can use .NET's COM Interop feature to write a .NET component in Visual Basic .NET and use that object from within PHP.

What Is Microsoft .NET?

It is important to remember that .NET is not COM, and vice versa. .NET is a brand-new strategy from Microsoft. COM is the cornerstone of the current Microsoft platform. .NET, however, is the cornerstone of future Microsoft development. .NET applications run not only on Microsoft platforms but on any device (your PC, your WebTV, your handheld, and so on).

.NET is a combination of things. Largely, it's a framework that encompasses a Common Language Runtime (CLR, discussed in a moment) and common class set (also covered in a moment). It also gives application developers new ways of working with the platform they are targeting and creating the applications they want to deploy. As we will see, .NET is a far more powerful way of working than COM and is decidedly COM's successor.

What Makes Up Microsoft .NET?

Microsoft .NET is a broad concept that Microsoft splits into four terms:

  • .NET framework
  • .NET development tools
  • .NET OSs and servers
  • .NET services

.NET Framework

This is how .NET applications are created; they use the CLR and a common class set. Microsoft provides the .NET framework SDK to allow you to do this.

The .NET framework also gives you several new languages that make use of the CLR and common class set: Visual Basic .NET, a new version of Visual Basic; C# (pronounced "C sharp"), a language with the control and power of C and C++ but with the rapid application development capability of a language like Visual Basic; and J# (pronounced "J sharp"), which is a version of Java for the .NET framework.

.NET Development Tools

Microsoft offers Visual Studio .NET for easy .NET development. You don't need Visual Studio .NET to create .NET applications, but it has been developed to aid in this process.

.NET OSs and Servers

Microsoft has rebranded most of its product line to use the .NET name. However, Microsoft OSs and servers don't yet use the .NET framework. (However, plans are underway to include the CLR in future versions of Microsoft Server 2000 and to allow the creation of stored procedures in C# for SQL Server.) Microsoft also plans to release the next version of Windows 2000 as Windows .NET. This OS won't be based on the .NET framework, but it will contain parts of the .NET framework.

.NET Services

Web Services are a big part of Microsoft .NET. They are very easy to build and deploy using Microsoft .NET. To aid in this sort of development, Microsoft is building a set of web services called Microsoft MyServices to allow your web service applications to connect to Microsoft services such as Microsoft Passport and HotMail.

What Makes Up the .NET Framework?

The .NET framework is split into two parts: the CLR and the common class set.

CLR

The Common Language Runtime (CLR) is the runtime of the .NET framework. In a .NET language (such as Visual Basic .NET or C#), the compiler compiles the code to something called MSIL (Microsoft Intermediate Language). MSIL can then be run on any CLR. The CLR itself can be targeted at any platform (Windows, Linux, Solaris, UNIX, and so on), so instead of your having to rewrite your .NET application to suit the platform, all the platform needs is a suitable CLR. In theory, this means that your applications can target any application that has a suitable CLR.

NOTE

The CLR is to be ported to the FreeBSD UNIX platform by Microsoft and to Linux by several third parties.

This approach might be familiar to Java developers. In the case of Java, the common runtime is called the Java Runtime Environment (JRE).

Common Class Set

The .NET framework provides a common class set that a .NET-compatible language can use. The common class set provides you with classes for many things, from handling data such as strings and variables to working with the Win32 API. The class set handles much of the functionality that was often difficult, such as working with databases with ADO (now called ADO.NET).

.NET Applications

.NET applications can be several different things, from conventional Windows GUI applications to console applications, web services, Windows services, and .NET components (which is the .NET equivalent of COM components).

All .NET applications can make use of something called an assembly. Microsoft .NET assemblies allow a .NET application to package itself into a single compact unit. For example, an assembly can contain an application's .exe file, any related component (DLL) files, and graphics files. The assembly spells the end of "DLL hell," in which different versions of the same DLL could be installed to a computer, causing compatibility problems. Now an application needs to look no further than its assembly.

Assemblies can be of two types: private and shared. In a private assembly, the assembly's contents are available only to the application within that assembly (any DLL files in that assembly can be used by that assembly's application). A shared assembly can be accessed by files (applications, DLLs, and so on) in other assemblies. A shared assembly is stored in the GAC (Global Assembly Cache), which you can view under C:\WINNT\Assembly\ if you have the .NET framework installed. You can use the shfusion.dll (a Windows shell extension that comes with the .NET framework) to obtain more information about the GAC.

Obtaining the .NET Framework

The .NET framework was in beta 2 at the time of this writing. It is available for Windows XP, Windows 2000, and Windows NT 4.0 platforms only. You can download the .NET framework from http://www.gotdotnet.com. You can also order it on a CD for free (there is a small shipping charge).

.NET and PHP

PHP currently does not support .NET natively. You can access .NET libraries, but PHP has no support for the CLR. Daniel Beulshausen of php4win.com has developed a version of PHP and a related PHP extension that can access .NET libraries. However, this is currently in beta and cannot be used with standard PHP extensions. However, you can access .NET libraries and other features by wrapping them into .NET components and exposing such components to PHP using a feature of .NET called COM Interop.

COM Interop lets you create a COM wrapper around your .NET components. The .NET component remains a .NET component, but it uses the CLR and is built using the .NET framework. However, it is built in such a way that Windows thinks it's a COM component and makes it available to all calling COM clients.

In this way, you can make a .NET component available to PHP via the same COM features of PHP discussed earlier. To use a .NET component with PHP successfully, you must make sure that you place your .NET component in the GAC. Unlike COM, .NET does not use the Registry to find components; it uses the GAC. In order for your PHP script to find your component, you must place it in the GAC.

Creating the .NET Component

The first step is to create the .NET component. You could use Visual Studio .NET for this, but all you need is the .NET framework installed. As such, you will use a simple text editor (Notepad is fine) and the command line.

Creating the examples.vb File

Create the file examples.vb using the following code:

Namespace php4winbook
  Public Class examples
    Public Function showname(ByVal name As String)
      Return "hello " & name
    End Function
  End Class
End Namespace

This is Visual Basic .NET code, but you can use any .NET language you choose (such as C#). Save the file as examples.vb.

Creating a Key File

Every component in the GAC must be versioned and signed. To do this, you will use a cryptographic key. You create the key from the command line by typing the following:

sn -k key.snk

This creates a cryptographic public key (a private key to encrypt and a public key to decrypt) called key.snk. To create this key, the CLR uses the contents of the assembly using a private key it creates itself. Anyone can use the public key to decrypt the assembly. It helps ensure that the assembly has not been tampered with. (If the assembly's contents have changed, the public key would be different.)

Creating a Reference File

You must now add a reference to the component and use that reference to sign the assembly. Create the file AssemblyInfo.vb and add the following:

Imports System.Runtime.CompilerServices

<assembly: AssemblyVersion("1.0.*")>
<assembly: AssemblyKeyFile("key.snk")>

Note that you need to use the Imports statement and that

<assembly: AssemblyKeyFile("key.snk")>

must point to the directory containing the key.snk file (in case it's in the same directory as the VB.NET files).

Compiling a Reference File

You must now compile the reference file with the following:

vbc /t:module /out:AssemblyInfo.dll AssemblyInfo.vb

Compiling examples.vb with a Reference File

Now that you have the compiled reference file, you can use it when you compile the examples.vb file. This indicates to the CLR that you have a reference file and that it can be used to sign the assembly.

The following line creates the assembly file examples.dll:

vbc /t:library /addmodule:AssemblyInfo.dll examples.vb

A Shortcut for Creating a Signed Assembly File

You can add the reference file directly to the VB.NET code:

Imports System.Reflection
Imports System.Runtime.CompilerServices

<assembly: AssemblyVersion("1.0.*")>
<assembly: AssemblyKeyFile("key.snk")>

Namespace php4winbook

  Public Class examples

    Public Function showname(ByVal name As String)

      Return "hello " & name

    End Function

  End Class

End Namespace

You can compile with this:

vbc /t:library examples.vb

However, if you have many components in your assembly, you might want to keep the reference file and the code for various assembly contents separate (thus making changes to the reference file code easier to make), as you did in the first example.

Adding examples.dll to the GAC

You must now add the signed assembly file to the GAC using the following:

drive letterProgram Files\Microsoft.NET\FrameworkSDK\Bin\gcutil /i examples.dll

If you open the GAC in Windows Explorer (drive letter\WINNT\Assembly\), you should see the entry for your component (see Figure 1.1).

Figure 1.1Figure 1.1 The Global Assembly Cache displayed in Windows Explorer.

Adding the Assembly to the Registry

In order to complete the process of fooling Windows, you must create a type library (TLB) file for your assembly. COM requires TLB files so that it can gather the information it needs about the component to access its public functions correctly (that is, what data type the function is and what data type it needs to send and receive from those functions).

Regasm examples.dll /tlb:examples.tlb

Remember that Windows looks for COM components in the Windows Registry, but .NET components reside in the GAC. Regasm fools Windows by adding information to the Registry about your component, but instead of loading the COM component from the file system, it loads from the GAC.

Creating the PHP File

Create the file testcode.php with the following code:

<?php

$test = new COM("php4winbook.examples");
$hellmes = $test->showname("Andrew");

print($hellmes);

?>

Notice that you have used the same syntax as the COM example you built earlier in this chapter. As far as PHP is concerned, you are using a COM component.

Running the PHP File

If you now run the testcode.php file, you should see the result printed to the screen, as shown in Figure 1.2.

Figure 1.2Figure 1.2 The output of your .NET component in PHP.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020