PHP for Big Nubs

An encyclopedia for everything related to harmlesswebsite, alanhw, other things, and projects embedded in those.

This is a simple community-written PHP tutorial.

Copyright

Copyleft. All rights reversed.

Setting it up

Note: The code in this file was tested on PHP 8.1.6, although it should work on other versions.

You need to install PHP. You can get it at https://php.net. After you install it, run the following command:

php -a

It should open a prompt where you can enter PHP and see the output.

Printing

To print in PHP, you just write the output in the file. How could life be easier?

Inside a PHP block, you can also print by using the echo and print statements. echo and print are pretty much the same.

Except... echo does not return anything and can take multiple parameters:

echo "poo", "poo";

...prints "poopoo" while

print "poo", "poo";

gives us:

PHP Parse error:  syntax error, unexpected token "," in FILENAME  on line LINENUMBER

Also, print returns 1.

Variables

Part of the functionality of programming languages is the ability to store data in the memory and access or change them later. You can create, read, edit, and delete (CRUD) them.

To assign a variable, use the $name = 'value'; syntax. We won't go into the lecture on data types, but you can use most values you would expect.

Also, to construct template strings, instead of "before" . $variable . " after", you can use "before$variable after" to get a shorter syntax. Be aware that this only works for strings in double quotes only.

Global variables

Functions and the outside code have different scopes.

<?php
$a = 1;
function printVar() { echo $a; $b = 1; }
printVar(); // Won't print '1' because $a is undefined in the function
echo $b; // Undefined as $b was in function scope.

Run that (either by using the server or running php filename.php) and you'll see this:

Warning: Undefined variable $a in /script.php on line 3

Warning: Undefined variable $b in /script.php on line 5

To make variables available inside and outside functions, there are several ways:

The global keyword

The global keyword makes a variable global. For example:

<?php
$a = 1;
function printVar() { global $a; echo $a . "\n"; global $b; $b = 2; }
printVar();
echo $b;

...will print 1 and then 2 due to the variable being global.

Function arguments and return values

Basically nothing fancy. This:

<?php
$a = 1;
function printVar(int $a): int {
  echo $a . "\n";
  $b = 2;
  return $b;
}
$b = printVar($a);
echo $b;

...will also print 1 and 2. (The int before the $a and after the function arguments are used to hint at the data types of the arguments.)

Forms

One of the things about the web is that users can enter data into sites. On the server side, you can catch the data using PHP and do whatever you want with it. You can write it to a file, to a database, even print out an image and toss it in the trash.

To start, make an HTML form in the file form.php using the form element:

<form 
  action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>"
  method="GET">
    <label>Enter your name: <input name="name" /></label>
</form>

This isn't too fancy. This is just a form that has an input with a name parameter.

Now run the server by running php -S 0.0.0.0:2000. If your port 2000 is already occupied, you'll need to choose a different number and substitute 2000 with your port number. Then, open http://localhost:2000/form.php in your browser.

You should see a text field with a label of "Enter your name." If you see that you were unable to connect, try making sure the command outputs something like this:

[Wed Jun 15 01:45:08 2022] PHP 8.1.6 Development Server (http://0.0.0.0:2000) started

Submit the form. When you submit the form, you get a URL like this:

http://localhost:2000/form.php?name=yournamehere

Try putting <?php var_dump($_GET); ?> at the top of your PHP file. The var_dump function prints debugging information about a variable.

When you visit the page without submitting, you should see the following when you press 'View Source':

array(0) {
}

But when you submit the form, the $_GET array has your parameter:

array(1) {
  ["name"]=>
  string(12) "yournamehere"
}

The $_GET array is populated with the URL parameters. Other superglobals like $_GET are:

Superglobal Description
$GLOBALS Global variables (more on that later)
$_SERVER Server information
$_REQUEST $_GET, $_POST, and $_COOKIE together
$_POST POST form data (more on that later)
$_GET URL parameters (aka GET parameters)
$_FILES Uploaded files (more on that in a long time)
$_ENV Environment variables
$_COOKIE Current cookies from the visitor's browser
$_SESSION Session data (more on that in a really long time)

Using POST instead of GET

GET creates a sharable URL for the submitted form data. You don't want that for passwords, as they are exposed in the address bar. For those, you want the POST form method.

Be aware that POST does not create extra security beyond hiding the data from the address bar. If you do not employ SSL/TLS encryption, a hacker could still sniff form data like passwords.

Also, it is not recommended that you share forms that ask users for sensitive data over HTTP, as they could be tampered to set the action to a malicious URL that eats up the data and stores it.

So to use POST form data, use method="POST" instead of method="GET" in the HTML for the form tag. To access POST variables, use $_POST instead of $_GET.

File uploads

Remember the last time you uploaded a file? PHP can do that too. To get started, make your form use the POST method and add the attribute enctype="multipart/form-data" to the form tag.

Additionally, add an <input type="file" name="myfile" /> input to the HTML form. When you visit the page again, it should show as a box where you can select files.

Check your upload_max_size value in your php.ini file (if you don't know where it is, run php --ini and see it) and make sure the file you are uploading is smaller than the size there. Otherwise, an error will occur.

Submit the form, var_dump($_FILES); and you will get an array with the keys as the names of the file inputs and the following values:

Key Description
tmp_name The place where the file is temporarily stored. It will be deleted at the end of script execution unless you move it to a permanent place.
name The filename. Note that this may contain special characters like / or .., so proper sanitation should be applied.
type The MIME type of the file. This can be manipulated, so don't trust it.
size The size of the file in bytes.
full_path The (not necessarily real) full path on the client's machine. Note that browsers may pass a fake value for privacy reasons.
error If not 0, describes the error code that happened when uploading the file. A list of error codes is available here.

Moving the uploaded file

So you got it uploaded, but it'll be deleted at the end of the script unless you move it somewhere useful. To move uploaded files, use the (wait for it...) move_uploaded_file function.

<?php
$filename = basename($_FILES['myfile']['name']);
if (move_uploaded_file($_FILES['myfile']['tmp_name'], "files/$filename")) {
  echo "File uploaded";
} else {
  echo "An error occurred";
}

A security risk can happen if you store your files in a place that is within your document root; in other words, it can be downloaded by visiting a URL on the server. Then, someone could upload a PHP file and open the URL to execute the PHP file. You don't want that to happen! So store uploaded files outside of your document root, or attach an extension to them and remove it, serve it when downloaded, and add it again to prevent them from being seen as .php. This security risk is CWE 434.

Files

Files are easy to work with. You can use fopen to open a file handle, fwrite to write to it, and fclose to close the file. All open file handles will be closed at the end of script execution, but it is still good practice to close them manually.

Session Data

Suppose you want to write a login/signup account system. You should use cookies to store the login info. But if you simply store the username alone in the login cookie, an attacker could set the cookie to someone's username to log in as them. You could also store the password in the cookie, but that would require verification every time, so that would be quite slow.

Instead, you can use sessions. The client only sees a cookie named PHPSESSID (although this can be changed using session_name) with a random ID. On the server, the sessions are stored. So to store session data, you can set the $_SESSION array.

For example:

session_start(); // Be sure to call this before any output is sent out
$_SESSION['a'] = 'data';

And page 2:

session_start();
echo $_SESSION['a']; // If you visited page 1, this will be 'data'

As long as you don't clear cookies, the session data will persist.

Session Hijacking

This means there is no verification as to if a user's session is actually theirs. If a session cookie was stolen, an attacker could replicate the user's session with all the authentication. So, either:

The End

Hopefully you're not a BIG NUB anymore. Anyways, if you have more questions, search them up on Geegle... err I mean Google. Or check out the documentation.