Complete PHP Basics Tutorial

This tutorial is following the book called “Head First PHP”. This book explains the basic principles, syntaxes, giving concrete examples. I highly recommend it.

This article can be used in order to refresh your php knowledge and syntax. If you have a job interview for example. Most of the topics in this article might be asked in the job interview.

PHP

To send an email

1
mail($to, $subject, $message, 'From: yourmail@here.com');

or you can use variables. “From” doesn’t work with double quotes.

Inserting into the database

you can insert data into sql like this:

2
"INSERT INTO table ('test', 'test2') VALUES ('test', 'test');

To insert without typing the table structure names, use “INSERT INTO table VALUES (0, ‘test’, ‘test’);
You always need to put 0 there. The SQL database will use auto increment and not really set the value to zero.
You can also insert like this “INSERT INTO table (username, password) VALUES (‘chris’, ‘rocks’)”;

The most efficient way to insert is like this:

3
"INSERT INTO table (`username`, `password`) VALUES ('$username', '$password');

Checking for isset and empty

You can check if a variable is empty with empty(); or isset() if a variable exists or it is set.

Uploading files

Use $_FILES[‘filename’][‘name’]; when submitting files, not $_POST.

move_uploaded_file is a php function that allows to upload a file.
example:

4
move_uploaded_file($_FILES['file']['tmp_name'], 'files/'.$_FILES['file']['name']);

Constants

Constants in php cannot be changed.
define a constant:

5
define('GW_UPLOADPATH', 'files/');

To echo it, just use echo GW_UPLOADPATH;
no need for quotes.
To have files uploaded with different names, you can put an extra value after the GW_UPLOADPATH constant.

example:

6
move_uploaded_file($_FILES['file']['tmp_name'], GW_UPLOADPATH.''.rand(0,9).'_'.$_FILES['file']['name']);

Require and include

The difference between require and include is that require_once or require will generate an error if the file is not found, while include won’t generate any errors.

SQL order by

You can put “order by date DESC, score ASC”. Two statements in case there are more entries that have the same date.

$i++; is the same as $i+1;

unlink is used to delete files

example:

7
unlink('files/5_bscap0000.jpg');

You can put @unlink (in front of unlink) to suppress any errors that might be generated and displayed.

When you access a webpage, that page is delivered with the help of headers which contain some data like get, host, user agent, connection, content type,
date etc.

Basic authentication with headers in php (IT IS CALLED HTTP AUTHENTICATION)

8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
 
$username = 'chris';
$password = 'rock';
 
if (($_SERVER['PHP_AUTH_USER'] != $username) || ($_SERVER['PHP_AUTH_PW'] != $password)){
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm= header-login.php');
}
else{
echo 'ok';
}
?>

Headers redirect and refresh

To redirect a page using php headers:

9
header('Location: http://google.com');

To refresh using the php headers:

10
header('Refresh: 5; url=http://google.com');

5 is the number of seconds that the browser will wait until it will make the refresh. 0 would trigger an instant refresh.

is_numeric()

will check if a string is actually a number.

To set a table row not null from phpmyadmin, uncheck “Null”.

using SHA()

You can encrypt a string by using SHA() – a mysql function, not php.
Example:

11
"INSERT INTO users ('user') VALUES (SHA('$username'))";

SHA can be used only inside SQL queries, not in a php code like to encrypt a string and then to echo it.

For PHP, you can use SHA1(‘test’); or MD5(‘test’);

Cookies

A cookie is like a variable but it can still exists after you close the browser.
It can also be destroyed. It has a time value for which it is active. After the time expires, it will be destroyed.
But of course, you can set a cookie to last for a long time, even a year or more.

example:

12
setcookie('username', 'cristi);

this sets the cookie
you can echo your cookie: echo $_COOKIE[‘username’]; However, you will need to refresh your page or you will get an error.
cookie values are always text, you can’t set a cookie value to be a number(integer). So use quotes.

13
setcookie('name', 'cristi', 3600);

will set a cookie for one hour.

14
setcookie('name', 'cristi', -3600);

will destroy the cookie. A negative time value will simply destroy the cookie (get rid of it).

$_SESSION

15
session_destroy();

will logout a user, destroy a session.
To set a session, example:

16
$_SESSION['username'] = 'cristi';

Then you can assign a variable like:

17
$username = $_SESSION['username']; echo $username;

will result in displaying cristi.

session_destroy(); doesn’t deletes session variables, you can use unset:

18
unset($_SESSION['name']);

or you can use

19
$_SESSION = array();

– empty. This will unset all $_SESSION variables. It won’t display any array missing error.

Combining tables

it is called schema, it involves primary keys combined with foreign keys.

Ternary if else

example:

20
echo (2 == 3) ? 'x' :'y';

will echo y.

Using foreign keys to sql

Why use this? Because it makes the database have less data which will speed up things.
And also if you want to modify something, you can just modify it in just one table.
It is a good idea to give a table a primary key, usually numeric, to ensure that there are no duplicates in your table.

Now you understand why scrips like wordpress or prestashop are using a lot of tables that contain lots of numeric data.
Because the scrips have optimized database structure so they can create the fastest queries.

Remember to store your data into an “atomic form”, meaning, no repetitions, fastest possible queries.

Inner Join

You need to use this to make the code to look better and also to write less code.
Here is a good example:

21
22
23
24
25
26
$id = 1;
$requestSQL = mysqli_query($connection, "SELECT * FROM cats INNER JOIN dogs on (id = id_dog) where id = '$id'");
while ($row = mysqli_fetch_array($requestSQL))
{
echo ''.$row['name'];
}

You can join even 3 tables.

Example:

22
23
24
25
26
27
$id = 1;
$requestSQL = mysqli_query($connection, "SELECT * FROM cats INNER JOIN dogs on (id = id_dog) INNER JOIN parrots on (id_dog = $id_parrot) where id = '$id'");
while ($row = mysqli_fetch_array($requestSQL))
{
echo ''.$row['name'];
}

Search in PHP

The most basic search can be used like this: where title = ‘$title’.
This will return AN EXACT MATCH.
Not very reliable.

Another version is by using LIKE.

23
"SELECT * FROM table where title LIKE '%$title%'";

The percents values are called wildcards and they will make a limitation for the characters that is between them.
If for example you put something like this: LIKE ‘% tom %’; they will only match ” Tom is a cat.” and not “Tom is a cat.

LIKE “‘%title'” will only retrieve that data that ends with your search query.
LIKE “‘title%'” will only retrieve that data that starts with your search query, example: “fighter” but it will not return
“streetfighter”. It will return only if you have something like “Fighters”.

Explode

Explode separates string elements into array elements.

24
print_r explode(" ", "tom is a cat");

Implode

Does the opposite of explode.
Example:

25
26
27
28
29
<?php
$cats = array("tom", "fred", "bruno");
$cats = implode(" ", $cats);
echo $cats;
?>

It will echo “tom fred bruno”. The idea is that you add a blank space with the implode function.
This will work on an array and the result from the implode will be an actual string.

Another good example of good usage for implode (to create a SQL query with more than one parameter)

26
27
28
29
30
31
32
$explode = explode(" ", $user_search);
foreach ($explode as $word){
$where_clause = " description LIKE '%$word%' ";
$where_list[] = $where_clause;
}
$where_clause = implode(" OR ", $where_list);
echo $where_clause;

Creating an array from variables

example:

27
$array[] = $word;

can be used in a foreach like this:

28
29
30
31
32
$words = array('cat', 'blue', 'moon');
foreach ($words as $word){
$array[] = $word;
}
print_r($array);

Basically, it is the same thing, you can maybe add an empty check like this:

29
30
31
32
33
34
35
36
37
38
<?php
$words = array('cat', 'blue', 'moon', '', '  ');
foreach ($words as $word){
$new_word = $word;
if (!empty(rtrim($new_word))){
$array[] = $new_word;
}
}
print_r($array);
?>

As you see in the example, we have used rtrim to strip all white spaces so we get a clean code.

substr

Will cut a string and display only a part of it.
Example:

30
echo substr($row['description'], 0, 100). ' .. ';

So this will display the first 100 characters. 0 means that the substr process starts from the first character. 100 is the last character.

Functions

Use “return” if you want to retrieve the resulted data from a function.
A function can take “ARGUMENTS”, “PARAMETERS” or “VARIABLES”. They are all the same thing.

LIMIT SQL query

if you have two values for limit, like LIMIT 1, 10.
This will display the rows starting from 2 and with a limit of 10.

For LIMIT 10, 5, it will display 5 rows, starting from the 11th row.

The first argument tells LIMIT how many rows to skip.
The second argument controls how many rows are returned.

Regex

all regex expressions start with / and ends with / (forward slashes).

^ after the first slash means: start matching at the beginning of the string.
\d stands for digit
$ at the end is saying that the string must end.

an example: /^\d\d\d\d\d\d\d\d\d\d\$/ (needs 10 digits)
can be formatted like this: /^\d{10}$/ (our match must have 10 digits)

Regular expressions (regex) are rules used to match patterns in one or more strings.

\d stands for digits
\s matches spaces, tab spaces, new lines
\w matches alphanumeric characters a-z A-Z 0-9
\w+ one or more alphanumeric characters
^ means that the match should always start in the beginning of the string.
. (dot) will match anything, except a new line
$ means that the match should always end at the end of the string.

example (all the pre matches are put in an array and you can echo them out).

31
32
33
34
35
36
37
38
39
40
41
<?php
 
$string = 'she has two apples';
 
preg_match('/\w{3}\s\w/', $string, $array);
 
foreach ($array as $item){
echo $item.'<br>';
}
 
?>

example phone number:

32
33
34
35
36
37
38
39
40
41
42
<?php
 
$string = 'His phone number is 0770 523 786. Please call him.';
 
preg_match('/\d{4}\s\d{3}\s\d{3}/', $string, $array);
 
foreach ($array as $item){
echo $item.'<br>';
}
 
?>

/[0-9]/ will match numbers
/[0-9]{4}/ will match the first 4 numbers

[a-zA-Z] will match everything with caps or not (letters)

example will echo phone:

33
34
35
36
37
38
39
40
41
42
43
<?php
 
$string = 'His phone number is 0770 523 786. Please call him.';
 
preg_match('/[a-zA-Z]{5}/', $string, $array);
 
foreach ($array as $item){
echo $item.'<br>';
}
 
?>

if you want to use characters that are actually regex characters, you need to escape them with backslashes, like:
/^\(test\)$/ (at the start and before the end of the string).

preg_replace()

is like str_replace() but it is working with patterns instead of simple strings.
The syntax is this:

34
preg_replace($pattern, $replace_with, $string);

example:

35
echo preg_replace('/[a-zA-Z]{5}+/', 'iphone number', $string);

This will replace all the words that are from 5 characters with the “iphone number” string.

Example to remove all white spaces from a string, no matter how many or how they look:

36
echo preg_replace('/\s/', '', $string);

/^[a-zA-Z0-9][a-zA-Z0-9\._\-&!?=#]*@/
email addres like “stevejobs@
So the string starts with an alphanumeric character.
^[a-zA-Z0-9]

and is followed by any characters:
[a-zA-Z0-9\._\-&!?=#]

and should always contain one arond sign.
*@

preg_match_all

If you want to get all the matches from a string, use this syntax:

37
38
39
$string = 'Bob is beautiful and Andreea is smart';
preg_match_all('/\w{2}/', $string, $array);
print_r($array);

It will display: “is” and “is” because these two words are 2 characters long.

ocr

ocr = optical character recognition (OCR).

GD Libary

GD Libary is a php library for images, also knows as “Graphics Draw”.
GD can generated images in jpeg, png and gif formats.

Rand

rand returns a random number from a range.
example: rand(0, 9) will return anything from 0 to 9.

Chr

chr can generated letters (characters).
an example: (we need to have $i++ because chr can generate one number at a time.
chr always needs this syntax: chr(rand(97, 122));

“The ASCII character codes in the range 97 – 122, are mapping the lowercase letters a-z.”

38
39
40
41
42
43
44
45
<?php
$i = 0;
while ($i < 6){
$string = chr(rand(97, 122));
echo $string;
$i++;
}
?>

Creating an image with gd library

39
$img = imagecreatetruecolor(CAPTCHA_WIDTH, CAPTCHA_HEIGHT);

(it contains two contants, you can use variables as well).

So the syntax is “imagecreatetruecolor”.
Nothing will happen on our web page now.

these variables will improve our image, add background color, text color and gray graphics

40
41
42
43
44
45
$bg_color = imagecolorallocate($img, 255, 255, 255); //white
$text_color = imagecolorallocate($img, 0, 0, 0); //black
$graphic_color = imagecolorallocate($img, 64, 64, 64) //gray
 
//fill the image (this is the syntax for imagefilledrectangle).
imagefilledrectangle($img, 0, 0, CAPTCHA_WIDTH, CAPTCHA_HEIGHT, $bg_color);

A complete example:

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
header("Content-type: image/png");
 
//defining constants
 
define("CAPTCHA_WIDTH", 100);
define("CAPTCHA_HEIGHT", 25);
 
// Create the image
$img = imagecreatetruecolor(CAPTCHA_WIDTH, CAPTCHA_HEIGHT);
$bg_color = imagecolorallocate($img, 255, 255, 255); //white
$text_color = imagecolorallocate($img, 0, 0, 0); //black
$graphic_color = imagecolorallocate($img, 64, 64, 64); //gray
 
imagefilledrectangle($img, 0, 0, CAPTCHA_WIDTH, CAPTCHA_HEIGHT, $bg_color);
 
// Draw some random lines
for ($i = 0; $i &lt; 5; $i++) {
imageline($img, 0, rand() % CAPTCHA_HEIGHT, CAPTCHA_WIDTH,
rand() % CAPTCHA_HEIGHT, $graphic_color);
}
 
// Sprinkle in some random dots
for ($i = 0; $i &lt; 50; $i++) {
imagesetpixel($img, rand() % CAPTCHA_WIDTH,
rand() % CAPTCHA_HEIGHT, $graphic_color);
}
 
$pass_phrase = 'cristi';
 
// Draw the pass-phrase string
imagettftext($img, 18, 0, 5, CAPTCHA_HEIGHT - 5, $text_color, 'arial.ttf', $pass_phrase);
 
// Output the image as a PNG using a header
imagepng($img);
 
?>

Be sure to put the arial.ttf where your php file is or you will get an error.

Always use imagedestroy($img); at the end of your code.
This will free resources from your server, after the image was created. It won’t affect the current image.

imagettftext allows you to use any fonts you want. Just need to put the font along the php file that is calling the function.

.ttf stands for truetypefont.

Another example of creating an image that shows your ip:

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
 
header("Content-type: image/png");
 
$text = $_SERVER['REMOTE_ADDR'];
$len = strlen($text);
 
$img = imagecreatetruecolor(500, 500);
 
$bg_color = imagecolorallocate($img, 255, 255, 255); //white
$text_color = imagecolorallocate($img, 0, 0, 0); //black
$graphic_color = imagecolorallocate($img, 64, 64, 64); //gray
 
imagefilledrectangle($img, 0, 0, 500, 500, $bg_color);
 
imagettftext($img, 10, 0, 250-$len, 500/2, $text_color, 'arial.ttf', $text);
 
imagepng($img);
 
imagedestroy($img);
 
?>

How to display the newly created png image?

you can just use include php like this:

443
<img src="captcha.php">

The thing is, the image is actually a php page which has an image header: header(“Content-type: image/png”);

Captcha

a captcha image values can be set trough a $_SESSION and compared in the process page with the value from $_POST.

Here is a basic captcha example so you can tweak it further:

form.php:

43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
session_start();
if (isset($_POST['submit'])){
$name = $_POST['name'];
$captcha = $_POST['captcha'];
 
if ($captcha == $_SESSION['captcha']){
echo 'matches';
}
else{
echo 'robot found';
}
}
 
?>
44
45
46
47
48
49
50
51
52
<form name="test" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
 
<input type="text" name="name" value="" placeholder="name">
 
<input type="captcha" name="captcha" placeholder="enter captcha"> <img src="captcha.php"><br><br>
 
<button name="submit" type="submit">Submit</button>
 
</form>

and

captcha.php

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
session_start();
header("Content-type: image/jpeg");
 
$text = rand(1000, 9999);
 
$img = imagecreatetruecolor(100, 50);
 
$bg_color = imagecolorallocate($img, 255, 255, 255); //white
$text_color = imagecolorallocate($img, 0, 0, 0); //black
$graphic_color = imagecolorallocate($img, 64, 64, 64); //gray
 
imagefilledrectangle($img, 0, 0, 500, 500, $bg_color);
 
imagettftext($img, 20, 0, 20, 35, $text_color, 'arial.ttf', $text);
//first is size of the font, second is the curve, third is the left right margin, forth is the top bottom margin
 
imagejpeg($img);
 
imagedestroy($img);
 
$_SESSION['captcha'] = $text;
 
?>

Saving the image on the server, in a folder or not in a folder

46
imagejpeg($img, 'img.jpg');

This will save the image as img.jpg in the same folder where you have the php script file. You can put it in a folder as well and set a dynamic name for your image.

GD library means graphic draw library. Stands for: php function that can create and draw things on an image and return them in the browser or save them as files on the server.

REST stands for “Representational State Transfer. And it means to create requests by building urls.
$_GET is actually a REST request.

Objects

An object is a special data type that allows data to be packed together with functions in a single construct.
Basically, you merge a few functions into one, that is an object.

Objects can have executable code attached to them in the form of “methods”.
Methods are pretty much the same as functions, except that they work and are attached to an object.
Objects properties and methods are accessed by name using the -> operator.

An object is like a normal variable but it can store very complex data. Besides storing just strings and numbers, an object can store complex data like functions.

Here is an example where you can see the syntax of a simple object:

47
48
49
50
51
52
53
54
55
56
<?php
class newclass{
function echoit($var){
echo 'Echoing '.$var.'';
}
}
 
$function = new newclass;
$function->echoit("test");
?>

Another object example:

48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
class food{
var $food;
var $type;
 
function food($food, $type){
$this->food=$food;
$this->type=$type;
}
 
function eat(){
echo 'You are eating a '.$this->food.' which is a '.$this->type.'';
}
 
}
 
//creating the object
$food = new food("pizza", "diavola");
$food->eat();
?>

So you create the class which is how any object starts:

49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class food{
 
}
 
//you add two variables by declaring them with "var $variable";
 
//then you create the function that will hold and process the variables
 
function food($food, $type){
$this->food=$food;
$this->type=$type;
}
 
//you create the function that will echo.
 
function eat(){
echo ''.$this->food.', '.$this->type.'';
}

//and you call the object by
$food = new food(“pizza”, “diavola”);
and you run the eat function from inside the object (class).

50
$food->eat();

With this, you can create as many functions inside your object as you like. And also assign variables and do all kind of operations inside that object.

Here is an example of how to combine two functions from a method:

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
class food{
var $food;
var $type;
 
function food($food, $type){
$this->food=$food;
$this->type=$type;
}
 
function eat(){
echo 'You are eating a '.$this->food.' which is a '.$this->type.'';
}
 
function person($name){
echo ''.$name.' is eating '.$this->food.'';
}
 
}
 
//creating the object
$food = new food("pizza", "diavola");
$food->person("cristi");
?>

A few advantages of using objects

They can be easily re-used. They are independent of the other code from your page.
If you need to change something, you can only change it in the object.

The big disadvantage: is that the code is longer and it takes more time to type. And for simple tasks to write an object can be a turn off.
For complex apps, you should use objects.

-> operator in php means

-> operator in php means: reference to a property or method of an object.
example: echo $entry->group->title;

-> makes a reference to a child from a parent object. In our example, title is a child of a group. Group is a child of the $entry object.

Important. When you see the -> it means that you are dealing with an object.

Not using objects

It is called procedural programming. OOP is called object oriented programming.

display_errors=off

display_errors=off will hide all php errors.
display_errors=on will show all php errors (if there are any).

For important forms, you can use even strip_tags(); to get rid of hacking atempts.

Using paranthesis in an operation will dictate the order in which the operations are taking place.

example: (2*2)/1 = 4
2*(2/1) = 4

Php is not a server

php is not a server, it’s an environment.
Apache is the actual server.

Important pages from the headfirst php book.

194, 200, 350, 437, 455, 464, 472, 473, 501, 505, 542, 561 (regex start), 570 (in-depth regex), 577, 616

ADD A COMMENT: