Jump to content

[Tutorial]Introduction to PHP/Getting Started with PHP/Operators and Functions


Recommended Posts

Posted

PHP Development and Database Interaction

 

Introduction

 

Hey there, I'm Nicolás™. In this series of tutorials/lesson, I hope you help you guys out by providing a detailed introduction into the PHP programming language and its syntax. During the later lessons, I also hope to get into database interaction with PHP (more specifically, MySQL). 

 

If you know the fundamentals of any programming language, that would be a great help, but if not, we will be going over it a lot. Stick around!

 

FAQ and Prerequisites

 

Should I learn PHP?

- Yes, of course you should! PHP has gotten a lot of bad press due to a few inconsistencies in the language, however, there's a reason why it's the most popular web programming language in the world.

 

What can I do with PHP?

- PHP is predominantly a web programming language, so you can design and create web systems. However, PHP isn't only limited to that. It's a greatly versatile language capable of a lot, so don't feel as if you'd be tied down by learning it.

 

How do I run PHP code?

- PHP is a server-side language, meaning the code isn't run client-side (on the user browsing the site, for example), unlike JavaScript, which is processed in the browser. I'll talk more about this next.

 

What do I need?

 

Okay, so all of the code we'll be using in the series will be able to be run locally, on your machine. Firstly, make sure you have a code editor ready. I personally would recommend SublimeText 2 - it's quick, easy and looks great. Available on Windows, OSX and Linux!

 

Next thing we need is a local development environment. If you're running windows, I'd recommend getting XAMPP, however for Mac, I'd use MAMP.

 

Great! Once you've got a local server running, you'll want to run Apache (the webserver). Any code should be placed in the 'htdocs' directory. Once you have a server running, you can access everything in your htdocs directory by visiting "localhost" in your browser. Provided you're running Apache on port 80. Otherwise, just add the port (i.e. http://localhost:PORT/).

 

 



 

 

PART 1 - Getting Started

 

What is PHP?

 

PHP stands for "PHP hypertext pre-processor". I'm not going to go to in-depth about how it work or its history, you can read about that yourself.

 

PHP is an interpreted language which means every time a PHP script is "run", is it re-interpreted. This is as opposed to being a compiled language. The difference being that a script coded in an interpreted language is "processed" by an interpreter on each run which completes the set of instructions given, whereas with a compiled language, source code is compiled into a form that can be directly run in the computer operating system.

 

That's a very simple way of explaining the difference. Not too difficult to understand. HTML can also be integrated into PHP. This will be further explained in the lesson.

 

Starting to code

 

I don't want to really go into too many details about the language itself, so, let's get straight into the coding!

 

There are a ton of ways to start PHP. However we are going to use the most conventional way:

 


<?php

?>

 

ALL PHP code should be inside those two tags. This is great because anything outside the tags will be processed as HTML. You can have multiple PHP tags on a page. Any code between the PHP tags will be interpreted by the interpreter, as long as the page ends in the extension .php. (This can be changed, however for simplicity's sake, let's leave like this)

 

Comments

In any programming language, comments are HUGELY important. Commenting your code is highly recommended as it can help others and yourself down the line to know what any given piece of code does. Comments can be anything you want them to be. Comments will NOT be interpreted, so they can include PHP code.

 

In PHP there are three ways to comment your code:

 


// This is a comment. This method is the most popular as it's what's used in JavaScript, too. The comment can only be ONE line.

# This is my preferred method of commenting as it's shorter. The comment can only be ONE line.

/*
This is used for block commenting
and you can have a multi-line comment
*/

 

All code I provide throughout these lessons will be commented. Get into a good commenting habit; it'll be very useful to you down the line and shows a good coding standard.

 

Semi-colons

In PHP, ALL statements should end with a semi-colon. One of the biggest mistakes people make with PHP is forgetting a semi-colon. You'll see examples of this further in.

 

Datatypes, Strings and Variables

 

If you've coded in any other programming language, you'll know all about this. We're going to look at FOUR main data types for now. I won't go into too much detail right now, just what you need to know as a beginner:

 

  • Integers - Any whole number
  • Float - Any number
  • Strings - A string of text
  • Booleans - Either TRUE or FALSE. (1 or 0 respectively)

 

We'll come back to that in a second, after looking at variables in PHP. If you're unfamiliar with what a variable is, it's basically a "storage location" stated by an identifier (the variable name) and the variable itself contains data. To access the data inside, you access the variable.

 

Variables are different to constants in that, as the name suggests, they are variable. The data a variable holds can always be changed. Variables in PHP are awesome- you don't have to set a data type as they're automatically done for you, unlike other languages.

 

To make a new variable, we use the dollar sign ($). This is followed by the name of the variable. A variable must be alpha-numeric and the only special character allowed is an underscore. Variables cannot start with numbers. There are a few reserved variables that you cannot use.

 

So, let's declare a variable:


$myVariable;

 

Great! So, like I said before, variables hold data. They can hold any time of data, however in this lesson, we'll be looking at the four I mentioned previously. To assign data to a variable, we use the assignment operator, an equals sign (=). Makes sense, right? Let's make our variable equal to the number 5:

 


$myVariable = 5;

 

Now, the variable '$variable' is an INTEGER of 5. Easy peasy! The same can be done for floats and booleans:

 


$variableOne = 4.7545; # This is a float
$variableTwo = TRUE; # This is a boolean

 

It gets a little complicated when it comes to 1 and 0, however. They are both integers but they are also both booleans (TRUE and FALSE respectively):

 


$var1 = 1; # This is equal to TRUE
$var2 = 0; # This is equal to FALSE

 

Get it? Let's move on to strings.

 

Strings

There are two ways to declare strings in PHP, one is using single quotes and the other is using double quotes:

 


$var1 = 'This is a string';
$var2 = 'This is also a string!';
$var3 = '123'; # This is also a string

 

What's the difference? Well, a string is a datatype. And in our strings, we maybe want to put in another variable, be it an integer, string or a float. When you put a variable inside a string, it is converter to a string. In strings with double quotes, you can display variables with interpolation. This is just as simple as putting a variable between the quotes. However, to improve readability, an variables that are interpolated should be wrapped in curly braces ({ }). Example:

 


$number = 17;
$colour  = 'Green';

$string    = "The number is {$number} and the colour is {$colour}";

/*
* The contents of $string is now
* "The number is 17 and the colour is Green"
*/


 

Now let's look at something else. Concatenation. This is used when we want to add variable to a string; append/prepend a variable to another or to append/prepend the return value of a function to a string/variable. Concatenation in PHP is done by using a period ( . ). When concatenating a single quote string, you have to end the string before doing so. Then, you can "restart" the string after, but you need another period. Let's give it a whirl:

 


$name = 'Foo';
$age  = 20;

$string = 'My name is '.$name.' and I am'.$age;

/*
* $string is now
* "My name is Foo and I am 20
*/

 

Which should you use? Well, if you have a string and you know you're going to have variables in it, interpolate with double quotes. For a string where you're not going to have any variables, you should use single quotes.

 

Escaping

"Escaping" (in this context) is when you want to use a a 'special' character inside of a string. For example, if you want to use a single quote inside a single quoted string. In PHP, the escaping character is a back-slash ( \ ). Example:

 


# WRONG
$string = 'I'm walking my dog';


#RIGHT
$string = 'I\'m walking my dog';

 

This can also be applied to double quotes. Also, when you have a double quoted string and you want to include dollar signs, you must escape them. That's the basics of strings!

 

Appending to Strings

We can also append to a string using the ' .= ' operator. Let's look at an example:

 


$string = 'Hello, my name is ';
$string .= 'Jeff';

# String is now "Hello, my name is Jeff"

 

Hello World!

 

So now, we're going to take a look at the echo language construct. This is used to output anything we want to output. It can be an integer, boolean, string or float. If it's a boolean, TRUE will output 1 and FALSE will output nothing. So let's make our first PHP script!

 


<?php
echo 'Hello World!';
?>

 

Turn on your Apache server. Visit the page, and voila! Easy. Let's try this with variables.

 


<?php
$colour  = 'blue';
$number = 3;
$string    = 'I like turtles.';

echo "The colour is {$colour} and the number is {$number}. ";
echo $string;

/*
* Will output:
* "The colour is blue and the number is 3. I like turtles."
*/
?>

 

==

END OF PART ONE

==

 

 

 

 

 



 

 

 

 

 

Part 2 - Operators and Functions

 

Arithmetic Operators

 

There are lots of operators in PHP. An operator, as the name would suggest, is something that performs an operation.

 

In this section, we'll be looking at arithmetic operators. They're pretty straight forward:

  • + - This is the addition operator and is used to add two integer or floating point values together. (x + y)
  • - - This is the subtraction operator and is used to subtract an integer or floating point value from another. (x - y)
  • * - This is the multiplication operator and is used to multiple two integer or floating point values together. (x * y)
  • / - This is the division operator and is used to divide an integer or floating point value by another. (x / y)
  • % - This is the modulus operator and is used to find the remainder when an integer of floating point value is divided by another.
  • ++ and -- - These are used to increase or decrease a variable by 1, respective. (x++, y--)

 

Below are some examples of their uses:

 


$number = 1 + 2; # $number equals 3
$number = 3 - 2; # $number equals 1
$number = 5 * 3; # $number equals 15
$number = 15 / 3; # $number equals 5
$number = 10 % 3; # $number equals 1
$number = 10 / 3; # $number equals 3.3333

##

# Here are some examples of using operators with variables.

$num1 = 10;
$num2 = 20;

echo $num1 + $num2; # Will output 30
echo $num2 / $num2; 

$num1++;
echo $num; # Will output 11

$num2--;
echo $num2; # Will output 19;

echo $num2--; # Will output 18;

 

Let me clarify on the last two: When you use them, they actually change the value of the variable. See:

 


$num = 1;

$num++;

# Is the same as

$num = $num +1;

 

Assignment and Comparison Operators

 

We've already looked at two assignment operators when assigning data to a variable in the for lesson. Those being ' = ' and ' .= '. So I won't be re-covering them. Here is a list of all the assign operators.

 

Now let's look at the comparison operators. So in PHP, we use a single equals sign to assign a variable a value. When we compare things in PHP, the output returns a boolean (TRUE or FALSE) based on whether the condition of comparison was met. I know that sounds confusing, but it really isn't. Let's look deeper into it.

 

If we want to compare two values in PHP, we use the double-equals operator, ==. When we use this operator, it will, it compares two sets of data for their value and not their type. Case matters as well. Let's see some examples:

 


$var1 = 5;
$var2 = 5;

$var1 == $var2; # The result of this is TRUE as they are equal.

$string1 = 'This is a StRing of teXt';
$string2 = 'THIS IS a string of text';

$string1 == $string2; # FALSE

 

An exclamation mark ( ! ) is equivalent to NOT in other languages. It basically returns the opposite boolean from the comparison operator, and this is how we use it with the above:

 


$var1 = 5;
$var2 = 5;

$var1 != $var2; # The result of this is FALSE as they are equal.

 

Now let's look at the strict comparison operator ( === ). This is used to compare values strictly. This means that the value would have to have the same data type and be of the same value for it to return TRUE. Examples:

 


'string' === 'sTring'; # FALSE
'4' === 4; # FALSE

$var1 = 'Password';
$var2 = 'PASSWORD';

$var1 === $var2; # FALSE

 

You can use the NOT with this too. You only use two equal signs:

 


$var1 = 'Password';
$var2 = 'PASSWORD';

$var1 !== $var2; # TRUE

 

PHP is great because it can parse numbers if they're quoted, too. Let me show some examples of this, along with arithmetic operators:

 


$num1 = '23';
$num2 = 4;

echo $num1 + $num2; # Outputs 27

$num3 = '33';
$num4 = 33;

$num3 == $num4; # TRUE
$num3 === $num4 # FALSE

 

There are 4 more operators I'd like to introduce in this less and their meaning will be pretty obvious if you've studied any mathematics: >, <, >=, =<. They are greater than; less than; greater than or equal to and less than or equal to, respectively.

 

Examples:


4 > 5; # FALSE

$num1 = 10;
$num2 = 20;

$num1 >= $num2; # FALSE
$num1 =< $num2; # TRUE
$num1 < $num2; # TRUE
$num2 > $num1; # TRUE

 

--

 

What are these used for? Well, in any programming language, what makes it interesting is comparing values in order to run a piece of code. We will be looking more into this in the next lesson, now that you have a grasp on what these comparison operators are and do.

 

== ==

 

Functions

 

Functions are awesome and a huge part of programming. A function is essentially a piece of code given an identifier (the function name). The piece of code is a function because it can be used again, without the need to re-write the code.

 

PHP has lots of in-built functions to help you out, but you can make your own functions, too.

 

ALL functions in PHP are used by giving their name followed by parentheses (brackets):

 


functionName();

 

Inside a the parentheses, you supply the function with parameters. These are essentially variables that the function can use in order to give an output. We'll learn more about this when we look into writing out own functions.

 

Functions perform an action (or multiple actions) and then return a value. Let's have a look at a few in-built PHP functions. Firstly, let's start with the strlen() function. This function takes one parameter (a string) and the output of the function is the length of the string we entered, hence the name of the function (strlen = str len = string length):

 


$string = 'This is my string';
$length = strlen($string);
echo $length; # Outputs 17

echo strlen('Hello World!'); #Outputs 13

 

Easy right? Let's look at another one. The strtolower() function is a function that takes a string and returns the lower case version of the string. It takes one parameter. A string:

 


$string = 'Apples and Tomatoes and 1234';
echo strtolower($string); # Outputs "apples and tomatoes and 1235"

 

Functions can be outputted, assigned to variables and even concatenated to strings:

 


$string = 'My name is Joe. Joe contains '.strlen('Joe'). ' number of letters';

 

Now let's take a look at making our own functions. The name of your function can be anything and has the same conditions as a variable. You start by writing 'function' followed by the function name and then parentheses. All code inside of your function is to be inside of curly braces:

 


function my_function()
{
    # Code here
}

 

Now you may have notice that I have indented my code. Indenting is a good habit to get into when programming. All code that is inside of these 'curly braces' should be indented. Any code that is 'within' something should be indented. This is done simply by hitting the tab key, however most code editors will indent for you. There are a lot of other ways people use to indent, but I won't go into that.

 

So, anyway, between the brackets, you put your parameters. These are variables that you want to use inside of the function. Whatever they are named when creating the function is the name of the variable inside the function. When calling the function, the variable name does not matter.

 

Variables outside of the function cannot be used. (They can, but we'll look into that later). Any variables you use inside of functions cannot be used outside of functions. Your functions can have functions within it, however, you cannot create a function within a function. We're going to look at the return statement. This used when you want to return fata from your function. Once you return something from a function, any code after will not be run.

 

Let's make a function that takes two parameters and multiplies them together and then dives by 2 and returns the result. Let's name the function 'do_something'.

 


function do_something($numberOne, $numberTwo)
{
    $result = $numberOne * $numberTwo / 2;
    return $result;
}

 

Now let's run that function with sample numbers:

 


echo do_something(1, 2); # This will output 1

 

 

 

==

END OF PART TWO

==

 

 

Greetings, Nicolás™

Posted

What's so awesome about this c/p post which you can find it on every tutorial site. Who really wants to learn php or needs a very good tutorial pm me. I have a very good book which is easy to understand, free ofc.

Posted

What's so awesome about this c/p post which you can find it on every tutorial site. Who really wants to learn php or needs a very good tutorial pm me. I have a very good book which is easy to understand, free ofc.

yeah ok,show me the c/p link!

 

Really impressive.Keep sharing dude.;) :alone: :troll:

thank you
  • 3 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Posts

    • 🏆 UPDATE: CLAN RACE — R$ 300 (PIX in Brazil, or the equivalent in USDT/PayPal) for the first clan ready for World B PvP Worlds opens on Friday, September 25, 19:00 BRT (GMT-3). Everyone starts together, from scratch. The challenge: the first clan with 9 members ready to enter World B wins. Ready = level 51, World C registered and the full C set equipped (weapon, armor and jewelry) with at least 3 attributes on each piece. Only Queen Ant stands between you and World B. Rules: main character only; 9 different people, each on their own PC; the server records the exact time each member became ready. Deadline: October 14. Sign up your clan on our Discord (link on the site): l2mog.com/pvp
    • 🚀 L2-Gold Custom PvP – Beta Test is LIVE! 🚀 Hey guys! We are opening a brand new Custom PvP server and looking for passionate players to help us test it out before the official grand opening! 💥 What we offer: High Rates & Custom PvP Gameplay Custom NPC Buffer, GM Shop & Global GK Balanced classes and epic custom items Interlude with c4 skills 🎁 Beta Rewards: Every active tester who reports bugs or gives feedback will receive Exclusive Custom Rewards on the official launch day! 🛑 No website needed yet! All files, patch, and support are inside our Discord. 🔗 Join Beta Test Here: [https://discord.gg/9qkSxQtTq]
    • "CAN YOU DO A BULGARIAN REVOLUT?" – WE DID. FIRST DRAFT, NO EDITS The request came in short: a photo of a bank card, Bulgaria, Revolut. We said yes and asked the only question that matters – what data. The client was on the road, asked for a couple of hours, then sent the lot: number, expiry, CVV, payment system, bank, cardholder name. Then came the part the client never sees: - ran the number through Luhn – the check digit has to add up, otherwise the card is dead the second anything automated looks at it - matched the BIN to the issuer: Revolut in Bulgaria isn't a "local bank", the cards run through Revolut Bank UAB. The number range has to actually belong there, not just start with the right digit - built the current design, not a five-year-old picture: vertical layout, flat laser print instead of embossing, correct chip module, contactless mark where it belongs - the payment system logo – with the right gradient where the circles overlap and the wordmark sitting exactly where it should. A small thing that kills half the fakes out there - and finally, physics. Plastic has to catch light: a highlight along the edge, a micro-shadow under the chip, a faint fingerprint. A phone shot, not a render Sent the draft for approval. The client looked it over, signed off with zero corrections – final files went out. One pass, no rework. A card is a deceptively simple document. Looks like a rectangle and sixteen digits. In reality it's maths in the number, a tie to the issuer, a current design and light on plastic. Miss any one of the four and the file gets exactly two seconds of attention. Need a card for a specific bank and country? Message us. We'll tell you straight what's realistic for your case – then build it. { all data published with the client's consent} › TG: @mustang_service_ms ( https:// t.me/ mustang_service_ms ) › Channel: Mustang Service ( https:// t.me/ +JPpJCETg-xM1NjNl ) #drawing #card #photoshop #revolut #case
    • ============================================================               CLExt Classic Interlude: v7.80 ============================================================   01. Fixed ValidateLocation handling and player/client position synchronization. 02. Added protection against invalid coordinates and characters falling under the map. 03. Improved XY/Z position and heading validation. 04. Fixed MoveToLocation and MoveToPawn packet conversion and target validation. 05. Fixed TargetSelected, TargetUnselected and MyTargetSelected packet handling. 06. Improved GeoData Z-location handling and disabled unsafe PathNode modifications. 07. Added ExUserInfoInventoryWeight support. 08. Fixed inventory weight and maximum load synchronization. 09. Fixed incorrect 0% inventory weight after character login. 10. Added automatic inventory weight updates after EnterWorld and inventory changes. 11. Added inventory weight packet spam protection and safe weight caching. 12. Fixed BuyList and SellList inventory, slot and weight synchronization. 13. Improved NPC target and Buy/Sell packet validation. 14. Reworked mail attachment inventory and weight validation. 15. Added all-or-nothing mail attachment receiving and safe retry handling. 16. Fixed stackable mail attachment validation and INT_MAX overflow protection. 17. Improved COD Adena validation and post-mail inventory weight refresh. 18. Improved Warehouse Deposit and Withdraw validation. 19. Added protection against malformed warehouse item counts, DBIDs and amounts. 20. Added warehouse INT_MAX, CItem and pSID validation. 21. Improved warehouse anti-dupe protection. 22. Reworked the HTML Cache system for improved stability and memory usage. 23. Added lazy HTML loading instead of loading ~20,000 files during startup. 24. Fixed HTML Cache startup crashes with large HTML collections. 25. Added thread-safe HTML Cache access and Clear/Reload support. 26. Added bad allocation, invalid HTML and oversized HTML protection. 27. Reduced HTML Cache RAM usage, startup allocations and disk I/O. 28. Added HTML Caching ON/OFF with live HTM loading support. 29. Fixed ToggleCachingHook and added VS2005-compatible live HTML handling. 30. Fixed ShortcutInit processing and skill synchronization order. 31. Improved shortcut item validation, augmentation handling and va_list safety. 32. Added LiveMode Ability Point system. 33. Added inventory-item-based Ability Points with configurable pointItemId. 34. Preserved the original level-based Ability Point system as fallback. 35. Fixed incorrect Ability Point display and inventory synchronization. 36. Improved Ability skill learning and point validation. 37. Improved OfflineShopRestore loading and FakePC/DBID handling. 38. Added safer OfflineShopRestore socket limits and batch processing. 39. Prevented thousands of restore sockets from loading simultaneously. 40. Added delayed, non-blocking OfflineShopRestore after server startup. 41. Improved OnEnterWorld initialization order and stability. 42. Improved inventory weight, SkillList and acquired-skill initialization after login. 43. Added VIP integration to the EnterWorld process. 44. Added safe UserExtData initialization without modifying the native User structure. 45. Improved duplicate Bronch Jewel and equipped-slot protection. 46. Improved Bracelet, Belt, Bronch and general UseItem validation. 47. Improved general packet, UserSocket, User, pSD and Creature validation. 48. Added safer INT32/INT64 packet handling and malformed-packet protection. 49. Improved L2Server startup memory usage and lazy resource loading. 50. Reduced unnecessary startup allocations. 51. Improved account-only KeyEngine authentication and remote account validation. 52. Removed account expiration-time requirements. 53. Added updater/restart design without requiring CLExtUpdate.exe. 54. Improved CLIEXT HWID, shared-memory and client/server version validation. 55. Improved ReadFile/WriteFile hooks and MemoryProtector handling. 56. Added UoPilot and Extreme Injector detection handling. 57. Reworked VIP point loading, saving and database synchronization. 58. Fixed VIP Level 0 initialization and first VIP activation. 59. Fixed vip.htm activation after login and from party-shared points. 60. Fixed VIP points being incorrectly reset before successful activation. 61. Improved VIP progression from Level 1 through Level 7. 62. Added proper VIP Level 7 MAX/DONE behavior with no Level 8 requirement. 63. Disabled further VIP point collection after reaching maximum level. 64. Reworked VIP BonusInfo/ReceiveVipInfo packet synchronization. 65. Fixed VIP tier, points, duration and level requirement packet fields. 66. Added VIP duration, tier, point and User validation protections. 67. Added safer 64-bit VIP EXP and party EXP calculations. 68. Preserved subclass maximum EXP protection. 69. Improved ItemDataEx validation during character loading. 70. Fixed augmentation loss during login, relog and server restart. 71. Added safe restoration of augmentation IDs directly from the database. 72. Added CItem, pSID, pExItem and User validation during ItemDataEx loading. 73. Improved Shadow Item mana and item lifetime loading. 74. Preserved item protection timeout data during character loading. 75. Added augmentation loading diagnostics and protected valid augmentation data. 76. Preserved database value 0 for genuinely non-augmented items. 77. Added RaidBoss Status synchronization with the World Map. 78. Fixed alive/dead RaidBoss status updates after spawn and death. 79. Added RaidBossStatus as the source of truth for RaidBoss map packets. 80. Fixed RaidBoss map status synchronization after server/database loading.
  • Topics

×
×
  • Create New...

Important Information

This community uses essential cookies to function properly. Non-essential cookies and third-party services are used only with your consent. Read our Privacy Policy and We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue..