Publish a PHP application as an AzureCloudservice

Source: Internet
Author: User
Tags windows azure sdk azure sdk
This section describes how to publish a PHP application to Azurewebsite. Website is easy to use, but because Websites has many restrictions on user permissions, for example, it cannot open a port (memcache is not supported ). Sometimes, we want more flexibility, such as the need for special PHP plug-ins, different PHP versions, or other processes, or even

This section describes how to publish a PHP application to Azure website. Website is easy to use, but because Websites has many restrictions on user permissions, for example, it cannot open a port (memcache is not supported ). Sometimes, we want more flexibility, such as the need for special PHP plug-ins, different PHP versions, or other processes, or even

This section describes how to publish a PHP application to Azure website. Website is easy to use, but because Websites has many restrictions on user permissions, for example, it cannot open a port (memcache is not supported ). Sometimes, we want more flexibility, such as requiring special PHP plug-ins, different PHP versions, or running other processes, or even logging on to the target virtual machine. In this case, you can use Cloud service to run PHP applications. Cloud service is a set of virtual machines managed by Azure. It runs the windows operating system and loads the IIS and PHP running environments. It supports ASP and PHP running. When PHP is published to Website, you can upload the code using FTP. When Cloud service is used, the upload process is slightly different. You must use the Azure tool for packaging during upload. Next, let's take a look at the specific steps.

Create an Azure release project

This tool can only run in Windows. Download and install the Windows Azure SDK for PHP from here. This tool includes a local Azure simulator and Power shell tool. After installation, find the Windows Azure PowerShell program in the Start Menu,Run as Administrator

Next, we can release it. First, you must generate a Cloud service application for the PHP application.

PS C:\>New-AzureServiceProject myProject

This operation will generate a directory under C: \ that contains the basic files of the service, such as ServiceDefinition. csdef and ServiceConfiguration. Cloud. cscfg. They defined that the Service is composed of several roles, each of which has several virtual machines and various variable information. Any cloud service is composed of one or more roles. A Role represents a group of virtual machines with the same functions. For example, if a PHP site has a front-end Web page and a backend batch processing program, we can define two role types: WebRole and WorkerRole.

Next, you can generate a role.

PS C:\myProject> Add-AzurePHPWebRole MyWebRole

This operation will generate a directory under the current directory to hold the files contained by this role. When the new directory is generated, there will only be index. php and a bin directory. Index. php displays the current PHP environment information. The bin directory is the script required by Azure for system configuration. We can copy the existing PHP application code to the role directory (C: \ myProject \ MyWebRole ).

Test in a local simulated environment

Before uploading an application to Azure, we can test it locally. Start the simulator locally

PS C:\MyProject>Start-AzureEmulator

The following output is displayed:

Creating local package...Starting Emulator...Role is running at http://127.0.0.1:81Started

Then open your browser and access the address given above for testing. The following command can end debugging:

PS C:\MyProject> Stop-AzureEmulator

After the test is completed, the final release starts.

Release to Windows Azure

We need to subscribe to Azure before publishing. Run the following command:

PS C:\MyProject>Get-AzurePublishSettingsFile

This operation opens a browser and prompts you to log on to Azure. After you enter the logon information, a download dialog box is displayed. Download the file to your local device.

This file is Azure subscription information. Import the subscription information as follows:

PS C:\MyProject>Import-AzurePublishSettingsFile C:\Users\{MyAccount}\Downloads\****-credentials.publishsettings

Finally, run the publish command. Here, ServiceName is the service name, which will constitute the prefix of the Service URL, and Location is the published data center.

PS C:\MyProject> Publish-AzureServiceProject -ServiceName MyService -Location "East Asia"

After the release is complete, log on to the Azure Management Portal and find the newly created service under Cloud service. You can view its Dashboard. Click the Site URL on the right to access the service.



The result is as follows:

The Publish-AzureServiceProject command is used to package, upload, and deploy the code. Sometimes we do not want to directly deploy code, but just package it, manually upload it to Azure storage, and then manually execute application publishing on the Azure interface. You can use this command to package the Code:

Save-AzureServiceProjectPackage

After execution, a file named cloud_package.cspkg is generated in the project directory.

Configure cache

One problem with website services running PHP is that memcache extension modules cannot be added. The TCP port must be enabled for running memcache services, which is restricted by website services. Cloud service does not have this problem when running PHP, and Cloud service itself supports the Windows Azure Caching module. This module is similar to the Memcache function and uses the memory of each virtual machine to run cache data, however, the installation of this module is automatically completed in the background. As long as Caching is enabled during configuration, Azure will automatically enable this module on each virtual machine of Cloud service. Azure Caching provides interfaces compatible with the memcache client. PHP web pages can use Azure Caching by calling Memcache without any modifications.

Next, let's take a look at how to configure PHP to use Azure Caching. This feature will not incur any fees.

1. First, download php_memcache.dll, which is the memcache client. This module can be downloaded from http://downloads.php.net/pierre. Here we choose the php_memcache-2.2.6-5.3-nts-vc9-x86.zip (-0700)-44 K module.

2. decompress the package and put php_memcache.dll in the bin \ php \ ext directory of Role. In this example, the specific address is C: \ MyProject \ MyWebRole \ bin \ php \ ext.

3. Add a php. ini file under C: \ MyProject \ MyWebRole \ bin \ php with the following content:

Extension = php_memcache.dll

4. Open C: \ MyProject \ ServiceDefinition. csdef in notepad to edit

. In Added the definition of the Caching module.

 

. Added Disk Space definitions for caching

      
    
 

4.3 In Add port Definition

 

5. Save the edited content. The complete content is as follows:

 
   
      
         
        
       
         
            
               
       
        
                
                
                
              
           
        
       
         
        
       
         
          
        
       
         
            
               
              
           
        
     
  
 

6. Edit the C: \ myProject \ ServiceConfiguration. Cloud. cscfg file in Add the following configuration information about Azure Caching.

      
       
       
       
 

The AccountName and AccountKey after ConfigStoreConnectionString must be modified by yourself. You must enter the information of a storage account.

After editing, the result is as follows:

       
        
        
        
  
 

7. Next, modify the access entry to the cache in php and change it to the following format. MyWebRole is the name of Role.

$memcache = new Memcache;$memcache->connect('localhost_MyWebRole', 11211) or die ("Could not connect");

So far, PHP uses the memcache client to access the cache configuration. Next we can test it with a small program.

Create a cachetest. php file under C: \ myProject \ MyWebRole \. The content is as follows:

 connect('localhost', 11211) or die ("Could not connect");$version = $memcache->getVersion();echo "Server's version: ".$version."
\n";$tmp_object = new stdClass;$tmp_object->str_attr = 'test';$tmp_object->int_attr = 123;$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");echo "Store data in the cache (data will expire in 10 seconds)
\n";$get_result = $memcache->get('key');echo "Data from the cache:
\n";var_dump($get_result);?>


Next, re-release the project

PS C:\MyProject> Publish-AzureServiceProject -ServiceName MyService -Location "East Asia"


After the release is complete, visit http://myservice.cloudapp.nen/cachetest.php. If you can see the result below, it indicates that cachehas been configured successfully.


Configure Session

One limitation of Azure cloud services is that it does not support Server Load balancer at the application layer. That is, when a Server Load balancer user requests, it does not determine the session information in the request. In this way, different requests of a user may be sent to different backend Virtual Machine instances, causing session failure. To solve this problem, either the session (data exists in the cache) or session replication is required, that is, the same session data can be accessed on each instance. PHP native supports using memcache to provide session replication. On Windows Azure, we have achieved compatibility with memcache in the previous step. Therefore, we can use the existing PHP session replication method to enable PHP in cloud services to support sessions. The specific configuration method is: Modify the bin \ php. ini under the role directory, and add the following content at the end:

Session. save_handler = memcache
Session. save_path = "tcp: // localhost: 11211"

Of course, you must configure the cache according to the method described in the previous section.


Access Azure Storage

In PHP, we can use Azure php sdk to operate a variety of Azure services, including storage and service bus. The SDK installation method is to download the corresponding software package to the directory of the corresponding role of the cloud project. The specific method can refer to the https://github.com/windowsazure/azure-sdk-for-php


After the installation, You can reference the class library in the PHP code for operations. The following example uploads an image in PHP and displays the image list.

 createBlobService($connectionString);$createContainerOptions = new CreateContainerOptions(); $createContainerOptions->setPublicAccess(PublicAccessType::CONTAINER_AND_BLOBS);try {    // Create container.    $blobRestProxy->createContainer("imagecontainer", $createContainerOptions);}catch(ServiceException $e){    // Handle exception based on error codes and messages.    // Error codes and messages are here:     // http://msdn.microsoft.com/en-us/library/windowsazure/dd179439.aspx    $code = $e->getCode();if($code != 409) {   $error_message = $e->getMessage();       echo $code.": ".$error_message."
";} }// Insert any new image into storageif (isset($_REQUEST['completed']) and $_REQUEST['completed'] == 1) { $instr = fopen($_FILES['imagefile']['tmp_name'],"rb");$blob_name = $_FILES['imagefile']['name'];try { //Upload blob$blobRestProxy->createBlockBlob("imagecontainer", $blob_name, $instr);}catch(ServiceException $e){$code = $e->getCode();$error_message = $e->getMessage();echo $code.": ".$error_message."
"; } fclose($instr);}try { // List blobs. $blob_list = $blobRestProxy->listBlobs("imagecontainer"); $blobs = $blob_list->getBlobs(); foreach($blobs as $blob) { echo $blob->getName()."
";echo "getUrl()."'>

"; }} catch(ServiceException $e){ $code = $e->getCode(); $error_message = $e->getMessage(); echo $code.": ".$error_message."
";}?> Upload an image to a storage

Upload an image to a storage

Please upload a new picture



In addition, we can also manage the Cloudservice, such as expansion, monitoring, modify the configuration, can refer to the http://www.windowsazure.com/en-us/manage/services/cloud-services/

There is no discussion about how to publish a database here, you can refer to the http://blog.csdn.net/shaunfang/article/details/8555574

Currently the default PHP version is 5.3, if we want to change the PHP version, or customize the PHP runtime environment, you can refer to http://www.windowsazure.com/en-us/develop/php/common-tasks/create-web-and-worker-roles/#CreateProject

For more Powershell commands, refer to the http://www.windowsazure.com/en-us/develop/php/how-to-guides/powershell-cmdlets/#ImportPubSettings

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.