Sunday, March 8, 2015

PHP Tutorial

PHP is a scripting language, which is mostly used on webservers to create dynamical web pages. Here I want to offer a little introduction in this topic.
If you rented webspace somewhere or even rented / bought a whole server, PHP is very likely already installed on it. Those who want to set up their own web server and need help installing PHP I refer to other tutorials on the internet.
We write PHP code to .php files. If they are then uploaded to a webserver and executed, we do not get to see the source code but the output of the script. If the webserver is correctly configured, it further should be impossible to access the source code without administrator access to the server. This is good for us, because in this case we can, for example, access password protected areas, by using the password in the script, but no one gets to see the password.

Let us create a first PHP file: For that we create the file Hi.php. We open it using an arbitrary text editor and declare its input as PHP code, we do this with the tags: <?php and ?>.
Everything in between is interpreted as PHP code by the webserver. For outputting text, we use the command echo. We expand Hi.php to the following:
<?php
     echo "Hello World";
?>

We then upload the file to our webserver and open it in the browser by calling the URL of the script, I uploaded mine to http://bloggeroliver.bplaced.net/PHPExamples/Hi.php. The script is then executed and the browser returns the result, in this case "Hallo Welt".

Of course we also can run the script in other ways, e.g. with C#. For this we use for example a WebClient or WebRequest with the corresponding URL as target, also with this then the result can be read out as response.

Variables are defined in PHP via the $ - sign and do not have to be declared. They can just be used in the code, the type is then assigned during runtime. An example:
<?php
     $Greeting = "Hello";
     echo $Greeting;
?>

Alternatively even echo "$Greeting World"; is possible.

Let us come to the possibilites of how to handle user inputs. As is mentioned here, there are basically 2 ways to send data via HTTP to a webserver, thus also to our script: GET and POST. Here I want to cover POST. In both variants additional parameters in the form Param1=..., Param2=... are passed over when calling an URL. How this is done exactly via C# and POST, I explained again in the next post.
To this data we now have access in our PHP script with $_POST["ParameterName"];. The following example, which is supposed to be a preparation for a login function, shows this:
<?php
     $Username = $_POST["username"];
     $Password = $_POST["password"];
     echo "Given Data: $Username $Password";
?>

I uploaded my file to http://bloggeroliver.bplaced.net/PHPExamples/Post.php, it outputs the given POST parameters username and password.

No comments:

Post a Comment