Lab 8 - PHP - COMP2100/6442 Skip navigation COMP2100/6442 ANU College of Engineering & Computer Science Search query Search ANU web, staff & maps Search COMP2100/6442 Exams menu Search query Search ANU web, staff & maps Search Search COMP2100/6442 labs Overview Lab 1 - Install Lab 2 - Git / SSH Lab 3 - Trees Lab 4 - Parser Lab 5 - Android 1 Lab 6 - Android 2 Lab 7 - Persistent Data Lab 8 - PHP Lab 9 - Lab Test 1 Lab Test 2 related sites Wattle Lab 8 - PHP Lab 8 - PHP & Firebase This week’s lab does not contain examinable tasks. The purpose of this lab is to give you an idea on how to implement a server-client environment for the web-based services. You may decide to add some of the network features in your group project. There are many languages that can be used to create web services including Java with Spring being one of the most popular frameworks for Java web applications. Due to time limitation of the lab, we will be looking at these two following technologies to quickly create a server for your Android application: PHP: Hypertext Preprocessor (or simply PHP) is a general-purpose programming language originally designed for web development (from Wikipedia). Firebase: A mobile and web application development platform that includes support for much more than just creating a server. Task 1 - Executing PHP PHP is generally run on a web server. If you are connected to ANU internet, you will be able to access webpages generated from the “public_html” folder in your home directory. If you are not connected to ANU internet you will not be able to access your pages, you may instead host your own local server using XAMPP. Once installed, run the program and start your “Apache” service (you may need to open the “Services” tab depending on your operating system”. When using XAMPP, you will place your php files inside the “htdocs” folder. However, the location of this folder will vary depending on your operating system: Windows: C:\xampp\htdocs OSX: Go to the “Volumes” tab, click “Mount” then “Explore” Linux: /opt/lampp/htdocs Create a file containing the following:
Save it as index.php in the public_html folder in “htdocs” folder if you have set up XAMPP (or in your home directory for when ANU is open again). You will need to delete/overwrite the existing index.php file if there is any. Now head to your local IP address (or head to http://partch.anu.edu.au/~u1234567/ (replace 1234567 with your uid) if you are using your ANU home directory). This should be shown in the “General” tab on Linux/OSX, you will need to run ipconfig in your command prompt to find it if you are using Windows. You should be able to see a familiar phrase if this worked. Task 2 - RESTful Representational State Transfer (REST) is an architecture for the development of web services. RESTful services conform to an api that provides stateless operations for the transfer of data. We will use an Android application to query our PHP service and display the result. Create a new project or open your lab 6 project in Android Studio and add the following to your manifest file right above
Android Studio may prompt the error Cleartext HTTP traffic not permitted depending on version. If that’s the case, please add android:usesCleartextTraffic="true" inside the application as follows: Create a Connector class in the same folder as your MainActivity, making sure to replace YOUR_URL_HERE with the URL you used in Task 1: import android.os.AsyncTask;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Connector extends AsyncTask
{
@Override
protected String doInBackground(String... args) {
try {
URL url = new URL("YOUR_URL_HERE"); // TODO: Replace with your URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode() == 200) {
// 200 OK is the response normally used for successful requests in HTTP
InputStream response = connection.getInputStream();
// Parse data received
String res = "";
int data;
while ((data = response.read()) != -1) {
res += (char) data;
}
// Close InputStream
response.close();
return res;
} else {
return "Connection Failed";
}
} catch (Exception e) {
e.printStackTrace();
return "Exception Occurred";
}
}
}
Connector extends Async task as Android does not allow network operations to be run on the main thread of the application. Now go back to your Lab 6 work where pressing Results button will lead to ResultActivity. Inside the method that is called when Results button is pressed, send a request to your server with String result = new Connector().execute().get();. Now when you run your application and click the button, you should be able to receive the phrase from your Task 1 service. However, this isn’t particularly exciting. Append ?choice1Num=23 to the url in your Connector class e.g: http://partch.anu.edu.au/~u1234567/?choice1Num=23
or http://YOUR_LOCAL_IP/?choice1Num=23
where YOUR_LOCAL_IP should be viewable from XAMPP application. This is a query string, where we have set the parameter number to 23. You can have multiple parameters by separating them with an ampersand e.g. ?choice1Num=23&choice2Num=3&choice1Num=12. Now let’s make our PHP service more interesting. Remove the echo "Hello World!"; line and initialise a variable to 0: $choice1Num = 0;
To access the parameters from our request, we can use the predefined variable $_GET which contains a map of each of our parameters. This means that: $choice1Num = $_GET["choice1Num"]; will set choice1Num to the value given in the URL. However if you try access the page without providing a parameter, you will get an error. Additionally, if we were to perform some operations on the value of choice1Num it should ideally be a numeric value. We will use the isset() and is_numeric() functions to ensure that the above is true: if(isset($_GET["choice1Num"]) && is_numeric($_GET["choice1Num"])) {
$choice1Num = $_GET["choice1Num"];
}
Finally, return the value of $choice1Num multiplied by 2 (similar to how you returned “Hello World!” in Task 1). Now when you run your android application, try sending the value of the first choice from MainActivity to the server and use the response from the server to display in your ResultActivity. (Tip: you can pass extra parameters to new Connector().execute(...) and access it in doInBackground(...) function by using args - the array of parameters). Task 3 - REST API with Firebase Follow Firebase instruction here to create a Firebase Realtime Database URL, which can be used as a REST endpoint to return the value of choice1Num in Task 2 instead. You can then find the URL to access your database by selecting “Realtime Database” option next to “Database”, see screenshot below: On the same screen, add some data and make sure that read and write are enabled on “Rules” tab: { "rules": { ".read": true, ".write": true } } You can then test your service by going to [Your URL].json on your browser or execute the following common command on your terminal if you have curl installed: $ curl [Your URL].json
{"choice1Num":23}
Now, modify your Connector class (or consider creating a new one) to connect to [Your URL].json to get the value of choice1Num instead. (Tip: you can reuse part of Lab 7 to parse JSON). Once you can display value of choice1Num from the REST API in your ResultActivity. You have successfully retrieved data from Firebase API. Next, you might wonder how to save, update or delete data. The basic write operation through the REST API is PUT. Here is an example of how you can update data with a PUT using java.net.HttpURLConnection. URL url = new URL("http://partch.anu.edu.au/~u1234567/"); // TODO: Replace with your URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(args[0]);
out.close();
See Firebase - save data for other operations. Updated: / Responsible Officer: / Page Contact: Contact ANU Copyright Disclaimer Privacy Freedom of Information +61 2 6125 5111 The Australian National University, Canberra CRICOS Provider : 00120C ABN : 52 234 063 906 You appear to be using Internet Explorer 7, or have compatibility view turned on. Your browser is not supported by ANU web styles. » Learn how to fix this » Ignore this warning in future