Wednesday 3 November 2021

 

Setup your own WAMP stack – Part II

In our previous post “Setup you own WAMP stack – Part I”, we installed and setup Apache server in our Windows 10 PC.

We already know what is the WAMP stack. Now we will put (install & setup) PHP in the stack.

Download and extract PHP

Step1:

Now download PHP 7.x from http://windows.php.net/download/; you need this file: VC15 x64 Non Thread Safe

(related to the latest stable version number).

Please download the VC11/14 x86/x64 ‘Non Thread’ Safe OR VC11/VC14/VC15 x86/x64 Thread Safe if you need to run PHP as module.

I downloaded the php non thread safe zip file. As a ‘non thread’ safe php increases the performance a lot while a thread safe php uses much memory in synchronizing the thread.

Step 2:

Extract the contents of this zip file and move the contents to where you intend to use PHP such as C:\php7.

Step 3:

Now navigate the folder C:\php7 and find the php.ini-production file. It is a pure text file. Open it with editor like Notepad++ for ease. Find there the extension_dir directive and change it so that it can properly locate full path.

extension_dir = "C:\php7\ext"

To enable the mysqli change the following extensions by removing the comment character.

extension=php_mysqli

extension=mbstring

extension=pdo_mysql

 

Now enable the opcache:

zend_extension=php_opcache.dll

Now search for opcache:

opcache.enable=On

opcache.cli_enable=On

To hide php from Apache response header:

expose_php = Off

Search the pathinfo inside the script:

cgi.fix_pathinfo=1

To set your timezone. Find your zone at http://php.net/date.timezone:

date.timezone = “Asia/Kolkata"

Now check whether all of the modules have loaded properly:

At the command prompt, write: >php – m

It will display all the modules loaded.

save this file as php.ini.

Step 4:

Go back to C:\Apache24\conf and open httpd.conf text file.

Now, to be able to access the php, change the httpd.conf file inside the C:\Apache24\conf directory.  The httpd.conf file is also a pure text file. Open it with Notepad++ for ease. There, make sure it contains the code block mod_fcgid. (mod_fcgid is an additional download).

First, uncomment the following LoadModule:

LoadModule fcgid_module modules/mod_fcgid.so

Now add the following fcgid module. If it is already present inside the httpd.conf file modify it accordingly[uncomment it].

The mod_fcgid code is as following:

<IfModule fcgid_module>

   FcgidMaxProcesses 300   

   FcgidMaxProcessesPerClass 300   

   FcgidOutputBufferSize 65536   

   FcgidConnectTimeout 10   

   FcgidProcessLifeTime 0   

   FcgidMaxRequestsPerProcess 0   

   FcgidMinProcessesPerClass 0   

   FcgidFixPathinfo 0   

   FcgidProcessLifeTime 0   

   FcgidZombieScanInterval 20   

   FcgidMaxRequestLen 536870912   

   FcgidIOTimeout 120   

   FcgidTimeScore 3   

   FcgidPassHeader Authorization   

FcgidInitialEnv PHPRC "C:\\php7"   

FcgidInitialEnv PATH "C:\\php7;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;"   

FcgidInitialEnv SystemRoot "C:\\Windows"   

FcgidInitialEnv SystemDrive "C:"   

 

FcgidInitialEnv TEMP "C:\\WINDOWS\\TEMP"   

FcgidInitialEnv TMP "C:\\WINDOWS\\TEMP"   

FcgidInitialEnv windir "C:\\WINDOWS"   

<Files ~ "\.php$">      

      Options Indexes FollowSymLinks ExecCGI      

      AddHandler fcgid-script .php      

      FcgidWrapper "C:/php7/php-cgi.exe" .php   

</Files>

</IfModule>

 

Now save the httpd.conf file

Step 5:

Now install Apache service in your system. To do that:

C:\Apache24\bin>httpd -k install ß[Enter]

This will install the Apache service in our system.

We can check this in services window from the search box in the status bar(for Windows 10).

To restart Apache, we need to give the following command:

C:\Apache24\bin>httpd -k restart ß [Enter]

Window 10 automatically sets the path for php7. For Windows 2000, XP, vista, we need to restart the computer.

 (Apache for Windows contains the ability to load modules at runtime, without recompiling the server. If Apache is compiled normally, it will install a number of optional modules in the \Apache2.4\modules directory. To activate these or other modules, the LoadModule directive must be used. For example, to activate the status module, use the following (in addition to the status-activating directives in access.conf)

For example: LoadModule status_module "modules/mod_status.so"  

To stop the Apache serviece we need to write the following at the command prompt: C:\Apache24\bin>httpd -k shutdown ß [Enter]

Rather doing a shutdown we should do a restart whenever we make a change in the httpd.conf  configuration file. So, we need to do: C:\Apache24\bin>httpd -k restartß [Enter]

This will restart the apache services.

 

Friday 29 October 2021

 Know about Web Server & Wamp Stack in brief

 

Setup your own WAMP stack – Part I

Though a distinct module for wamp server is available over the internet and one can download and install it as a package, wamp stack components can be installed separately (manually). Here we have shown how to install and setup wamp stack components separately (manually). 

Significance:

It is very essential for a Windows user who wants to establish his/her own dynamic web presence. A WAMP stack will enable you to test your own web pages on your own server on your own windows pc.  Once successful, you can easily put your web pages and server code into the actual domain server.

What is WAMP stack?

It is a stack to set up your own server on your Windows PC. First you need Windows environment (the OS), then you need to install Apache server, after that you need to install PHP and then setup your MYSQL database. In short it is Windows-Apache-MySQL-PHP stack. PHP is needed for your server-side coding.

For users of other environments like linux, they need to setup their LAMP stack which is Linux-Apache-MySQL-PHP stack. There are other stacks like MAMP – the Mac-Apache-MySQL-PHP stack etc.

Start:

As a Windows user we already have windows installed in our pc. I have Windows 10 installed in my pc. Now I need to install and setup Apache.

Before that we need to disable IIS in our Windows PC, if it is enabled. To disable IIS, follow the steps below:

1. Go to Services window by typing services in search bar at the bottom left; from there disable IIS admin service.

2. Now open "Turn Windows features on or off" in the same way.

3. Go to Internet Information Services

4. Click the square next to it so that it becomes empty.

5. Click OK and reboot the PC.

Start with Apache:

We need to start apache as a service in our Windows Pc. Apache can be downloaded from any of its official sites. (it an open source software).

Before downloading and installing Apache we need to uninstall Apache if it is previously installed anytime. The code to uninstall Apache is >httpd-k uninstall

[Note: httpd is available in bin folder of the root directory. If apache is installed in c:\Apache24 then the command will be available in c:\Apache24\bin> folder.

Again, the command prompt( dos prompt) should be opened with administrative privileges.

It is necessary to restart the apache server each time.]

To check whether Apache is running in our system we need to check the services running in our system. For windows 10 users we need to write services in the search box in the status bar.


v

On hitting enterß the services window will open. In this window we will get all the services running in our system. As I have Apace 2.4 already installed in my system the Apache service is seen to be running in my system. Below is the figure:



 

So, if apache is installed in our system, we need to uninstall it first. To do that first we need to check where Apache was installed in our system. Mostly it is in the C:\Apache directory. For me it is C:\Apache24 directory. And the httpd is in the C:\Apache24\bin directory. So, we need to go to C:\Apache24\bin> and then >httpd -k uninstall ß

If you don’t have Apache installed in your system You can start with next step:

Step 1:

Install the Microsoft VC++ Redistributable. We can do this from http://www.apachelounge.com/download. And look for 2.4.x VC11/14/VC15/VC1 link for windows 32 bit or 64 bit processor. In my case, my pc was Windows10 64 bits.

Be sure you installed latest 14.25.28508.3 Visual C++ Redistributable for Visual Studio 2015-2019 : vc_redist_x64 or vc_redist_x86 see Redistributable

Step 2:

Now download the zip file httpd-2.4.x-win64-VS16.zip from http://www.apachelounge.com/download/ for Apache 2.4.

Unzip the zip file, then rename the unzipped folder to anything suitable. I renamed it as Apache24. Put the folder in C:\ directory. So, my Apache is now at C:\Apache24.

Step 3:

Now get the file httpd.conf located at C:\Apache24\conf directory. It is a text file.

Open it with a suitable editor. I used Notepad++ for ease.

Specify the ServerRoot in this file: change it accordingly[ we have to uncomment and change these lines accordingly]

Define SRVROOT "c:/Apache24"

ServerRoot "${SRVROOT}"

Now specify the document root as in the following way: [We have to uncomment and change these lines accordingly]

DocumentRoot "${SRVROOT}/htdocs"

<Directory "${SRVROOT}/htdocs">

      ……………

       …………..

</Directory>

Step 4:

Now, at the command prompt, go to the bin folder of Apache24 i.e. C:\Apache24\bin>. Put there httpdß. This will will start apache services in your system.

Always remember to get the Command Prompt with Administrative privilege.

To check whether apache properly started in your system or not, you need to go to your internet browser and type in the address bar: http://localhost. Press Enter. If the browser shows “It Works”, it ensures that Apache is working successfully.

Actually, the Apache server executes the index.html or index.php file stored in the document root; This file is preinstalled when Apache is installed.

Now, again at the command prompt window, press CTRL + Cß. this will stop Apache and command prompt will come back again.

Note: whenever there is any change in apache system ie. httpd.conf or any allied files, you need the restart apache.

We can restart Apache with the following command:

>httpd -k restart

httpd command path should be accessible from the document root & remember to put command prompt in administrative mode.

Monday 25 October 2021

 

SEND FIREBASE CLOUD MESSAGES (FCM) TO YOUR DESIRED ANDROID USERS USING NODE JS SERVER

Architecture:



As the figure says, we will send notification messages from our android set to our own server (say Node js web app). In the Node js web app we implemented the admin sdk of Firebase Cloud messaging (FCM) server. The Nodejs web app communicates with the firebase cloud server using its app credentials. The FCM (Firebase Cloud Messaging) server now serve the users of defined categories.

[This article should be read as the appended section of SEND YOUR FIRST ANDROID NOTIFICATION USING FCM (Firebase Cloud Messaging)]

 

1. In your Firebase console go to Project Settings>Service Accounts

2. In the Service Accounts window click Generate New Private Key. Then in the confirmation window click Generate Key.

3. The Google Credential json file will be downloaded to the downloads folder of the browser.

Keep this file safe.

4. We need to put this file in the project root of our Node js web app.

5. SETUP THE NODEJS WEB SERVER

Now install firebase admin sdk in our server.

In my case my server is an apache shared server. I have node js setup tool in it.



(i) first create a folder in my shared server root directory. Under it I will create my base directory for my nodejs web app.

(ii) it is better to create a demo app in our local WAMP or LAMP server with npm init.

(iii) the main app.js file along with package.json will be created there.

(iv) now upload this app.js along with package.json to our shared server base directory.

(v) Now go to nodejs setup.



(vi) specify Node js app root directory in Application root.

And put the application url.

(vii) Application startup file(app,js) & log file

(viii) click on Edit under Run NPM Install.

(ix) Here enter in the dependency section the firbase-admin as following:

“firebase-admin”: “”

(x) Now install packages by clicking Run NPM Install.

(xi) After successful installation open app.js and add the following code in app.js file:

var express = require('express')

var admin = require("firebase-admin");

const port = 2388;

app.get('/', (req,res)=>{

    res.status(200).send("Hello World")

})

app.listen(port, () =>{

console.log("listening to port"+port);

})

(xii) Save app.js and restart the web app from Node js setup.

 

(xiii) Setup the subdomain for your web app. Make https redirect to it. (xiv) Now in the browser test your web app by typing your (sub)domain name.

This will show now Hello World on the browser.

It proves that our web app setup is correct and working.

6. Now we have Google Credential json file containing firebase keys stored in the base directory of our web app.

7. Now inside the app.js add the following code to initialize the Firebase Admin SDK for messaging.

var admin = require("firebase-admin");

var serviceAccount = require("./myTopic-firebase-msg.json");

admin.initializeApp({

  credential: admin.credential.cert(serviceAccount),

  databaseURL: "htts://<your firebase database>.firebaseio.com"

})

Here myTopic-firebase-msg.json is the json file I downloaded in the step 3 and renamed it. I put this file in web app’s base directory.

Also the initialization requires a database url to the realtime database (rtdc) of your Firebase Account (You will get it from Real Time Database section on your Firebase console).

8. Further put a module like below to accept request from the messaging app that controls the notification to all users.

 app.post('/firebase/notification', (req, res)=>{

    var topic;

    var title;

    var message;

    var body = [];

    req.on('error', (error)=>{

        console.log(error);

    }).on('data', (chunk)=>{

        body.push(chunk);

   }).on('end', ()=>{

        body = Buffer.concat(body).toString();

        res.on('error', (err)=>{                                   

                console.error('Error Occured :'+err);

        });

        var json = JSON.parse(body);

        topic = json.topic

        title = json.title

        message = json.body

   

        const messaging = admin.messaging();

        var payload = {

                notification: {

                        title: title,

                        body: message

                }

        };

        messaging.sendToTopic(topic, payload)

        .then(result=>{

                Console.log('The response: '+result)

        });

        res.send('Its OK..');

        res.end();

   })

})

Here be careful to construct the right payload with notification and topic. This payload will reach to the end users.

9. Now save the app.js file. Restart the Node js web app from nodejs setup.

10. Now make the following changes in our message sending android app:

In your MainActivity do the following changes:

   

public class MainActivity extends AppCompatActivity{

        protected void onCreate(Bundle savedInstanceState) {

                super.onCreate(savedInstanceState);

                setContentView(R.layout.your_layout);

               

                --------   --------- ------

                Button btn = findViewById(R.id.sendMsg);

                Btn.setOnClickListener(new View.OnClickListener() {

                @Override

                public void onClick(View v) {

                        AsyncTaskClass asyncClass = new AsyncTaskClass();

                        asyncClass.execute();

                 }

                });

        }

 

        class AsyncTaskClass extends AsyncTask<Void,Void,String> {

        @Override

        protected void onPreExecute() {

            super.onPreExecute();

        }

 

        @Override

        protected void onPostExecute(String string1) {

            super.onPostExecute(string1);

        }

 

        @Override

        protected String doInBackground(Void... params) {

            ServerUploadPath = "https://your.domain.com/firebase/notification";

            String topic = "urgent";

                        String title = "Test Notification";

                        String body = "Meeting called at 8:30 pm";

            QString = makeMessageString(new MsgToSend(topic , title, body));

 

            String finalData = sendData(ServerUploadPath,QString);

            runOnUiThread(new Runnable() {

                @Override

                public void run() {

                    //process the response finalData

                }

            });

            return finalData;

        }

    }

       

        private String sendData(String requestURL, String QString){

                final StringBuilder stringBuilder = new StringBuilder();

 

        try {

 

            URL url;

            HttpURLConnection httpURLConnectionObject ;

            OutputStream outPutStream;

            BufferedWriter bufferedWriterObject ;

            BufferedReader bufferedReaderObject ;

            int respCode ;

 

            url = new URL(requestURL);

 

            httpURLConnectionObject = (HttpURLConnection) url.openConnection();

            httpURLConnectionObject.setReadTimeout(19000);

            httpURLConnectionObject.setConnectTimeout(19000);

            httpURLConnectionObject.setRequestMethod("POST");

            httpURLConnectionObject.setDoInput(true);

            httpURLConnectionObject.setDoOutput(true);

            outPutStream = httpURLConnectionObject.getOutputStream();

            bufferedWriterObject = new BufferedWriter(new OutputStreamWriter(outPutStream, "UTF-8"));

            bufferedWriterObject.write(QString);

            bufferedWriterObject.flush();

            bufferedWriterObject.close();

            outPutStream.close();

            respCode = httpURLConnectionObject.getResponseCode();

            if (respCode == HttpsURLConnection.HTTP_OK) {

                bufferedReaderObject = new BufferedReader(new InputStreamReader(httpURLConnectionObject.getInputStream()));

                //StringBuilder stringBuilder1 = new StringBuilder();

                String received;

                while ((received = bufferedReaderObject.readLine()) != null){

                    stringBuilder.append(received);

                }

                                Handler handler = new Handler(Looper.getMainLooper());

                handler.post(new Runnable() {

                    @Override

                    public void run() {

                        Toast.makeText(MainActivity.this, stringBuilder.toString(), Toast.LENGTH_LONG).show();

                    }

                });

            }

 

        } catch (Exception e) {

            e.printStackTrace();

        }

        return stringBuilder.toString();

       

        }

       

        private class MsgToSend{

        String topic;

        String title;

        String body;

        public MsgToSend(String topic,String title, String body){

            this.topic = topic;

            this.title = title;

            this.body = body;

        }

    }

        private String makeMessageString(MsgToSend msg){

        Gson gson = new Gson();

        Type type = new TypeToken<MsgToSend>(){}.getType();

        String rjson = gson.toJson(msg,type);

        return rjson;

    }

}      

 

11. In the user’s client Android app keep the FrebaseMessageReceiver class unchanged. (This class we created earlier in the previous section -SEND YOUR FIRST ANDROID NOTIFICATION USING FCM).

Also, In the main launcher activity onCreate method must add the following code to subscribe the user for definite topic.

FirebaseMessaging.getInstance().subscribeToTopic(topicname);

To unsubscribe the topic topicname user app must call unsubscribeFromTopic(topicname);

FirebaseMessaging.getInstance().unsubscribeFromTopic(topicname);

Note:

12. This change in user’s client android app will enable it to receive FCM messages based on its subscribed topic.

Now Install client android app in user’s device and install the sender app to your device. On clicking the button on sender app push notification will be served to those user’s app who have subscribed to topic “urgent” (as I have mentioned “urgent” as the topic in query string (QString) in my sender’s app. This query string is collected by our nodejs web app and extracts the topic from this query.).

 

FURTHER READING: HANDLING RECEIVING OF FCM MESSAGES IN ANDROID IN EFFICIENT MANNER.