PHP Beginners guide - Printable Version +- Support Forums (https://www.supportforums.net) +-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87) +--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18) +---- Forum: PHP The Hypertext Preprocessor (https://www.supportforums.net/forumdisplay.php?fid=21) +---- Thread: PHP Beginners guide (/showthread.php?tid=1609) |
PHP Beginners guide - Gaijin - 10-16-2009 Welcome and Enjoy! First things first, I don't mean to steal Tim's readers so please check out his tutorial too. http://www.supportforums.net/showthread.php?tid=335 Now after my series, 1 Tutorial per day, 7 days long, I've decided to change this to, 1 Tutorial per Week, to make better Tutorials. Since PHP is my Domain, I've been working on this tutorial in my free time over a period of 1 Week (5 work days) to make this Helpful as much as I can PHP new comers to get started writing own PHP scripts. The words in this tutorial that are bold, are those which you should also google if you don't understand them trought this tutorial. If you don't understand something or have any questions, please post them here and I will try to answer them as soon as posiblle. My first words to you are, don't stop learning and never think you've learned enough! What is PHP Since Wikipedia has this already I will just Quote for Truth! http://www.wikipedia.com Wrote:PHP originally stood for personal home page. Read before or after reading the below content! http://en.wikipedia.org/wiki/PHP http://en.wikipedia.org/wiki/Apache_server PHP Enviroment PHP is mostly used on an Apache Server, when the user requests a PHP written page, the request is sent to the server and the script is then handled by an, PHP Interpreter, and after the execution the result is sent back to the server and outputed to the end-user in a form of an HTML file. So for writing and using PHP scripts, you will need an Host that has PHP and mostly MySql installed/enabled, but writing and testing PHP on a host isn't the right way to go when developing PHP applications, therefor it is recommended using an local Apache server which runs on your local system and it is not avalible to the public on the internet. That way you can locally write and test your code, all your development should be don on a local server before published. Setting up a Local Server There are few ways to setup a local Apache Server, those variy depending on the Operational System you are using. On Mac OS the Apache and PHP are already installed but in most cases not enabled, therefor I recommend you reading this tutorial if you are a Mac user. http://foundationphp.com/tutorials/php_leopard.php On Windows you will need a software that installs Apache, PHP and MySql on your system and makes it ready for use. I'm using WAMP and can only recommend it. http://www.wampserver.com/en/ When WAMP is installed, all PHP script you write are to be placed insde "wamp/www" directory. http://www.apachefriends.org/en/xampp.html XAMPP is avaliable for mulitple Systems, Linux, Windows, Mac OS and Solaris. In XAMPP the dircetory for placing your script is called "htdocs". On windows you will get an installer to install the above two software, in your first install you can just click on the NEXT button until it's installed. On Linux there are more ways to enable Apache and PHP, so I recommend you to google your Linux distro and how to setup apache on it. For Ubuntu, read this. https://help.ubuntu.com/community/ApacheMySQLPHP After you are done with setting up your local Server, open your Text editor of choise and input this. PHP Code: <?php Now save the file as "test.php" and place it in the right directory, like said for WAMP it is the WWW directoy inside your wamp installation folder. Once your script is placed in the right spot, you can view it by opening your Web Browser and input in the Adrress bar "http://localhost/test.php". (without the quotes) If you done everything right, you will see Code: Localhost is ready and working! That means that you have successfully set up Apache and PHP on your System. Starting with PHP To let your Server know that the file is a PHP one, the first step is to save your files with the extension "*.php" (where * is the name of the file). Second step is the content of the file, PHP commands are put between the starting tag "<?php" and the closing tag "?>". That way the server know that there is a php code and needs to be sent to the PHP interpreter, and the parser only executes the code that is between the starting and closing tag. PHP Code: <?php PHP can also be embedded in regular HTML files. PHP Code: <html> I wouldn't recommend embedding PHP in HTML file, simply becasue you can use PHP to output HTML codes. Commenting When you develop Web applications your code can be small with only few lines, but in most cases it will be a long one and mostly spread into multiple files. Therefor commenting is one big and important setp in writing any code, not only PHP . You should learn to comment your code with right definitions, it will make your life easier when you need to go trought your code and finding a specific function or a variable. Comments are ingored by PHP interpreter and will not be executed. There are 2 types of comments "Singleline" and "Multiline", and are expressed with "//" or "/* */" PHP Code: <?php Output First words, Every PHP statement ends with a semi-colon ";", and forgeting this is probably the mistake that occurs most. There are two main commands used to output content to the actual web site, "echo" and "print". The main difference between those two is, "echo" is a language construct and it accepts multiple expressions while "print" is also a function and it doesn't except multiple expressions. (10-16-2009, 08:34 AM)Spl3en Wrote: The biggest difference between them is the return value ; print can return true or false, whereas echo doesnt return anything. But both are used for the same thing, to output content to the website. PHP Code: <?php The above code brings us to the: Strings A string is a collection of characters, like this sentence or "SupportForums". In PHP stings must be enclosed within the Quotation marks, single (') or double ("). The difference between ' and " is, values that are enclosed in double quotes (") are being automatically parsed for specal characters, such as variables. If the quotation marks used to enclose the string are also used within the sting itself, they must be ecaped with the "\" backslash. PHP Code: <?php If you don't escape the quotes you may encounter some errors. You can escape everything you want when you need it. Escaping is done with the "\" backslash. Numrical values The numbers dosn't need to be enclosed in quotation marks. Integer: Integer are whole Numbers: 1, 22, 452, -1238 PHP Code: <?php Boolean: Boolean variable can hold only two values, 1 or 0 / TRUE or FALSE. PHP Code: <?php Float: Floating-points are numbers with decimal expansions, 0.5, 156.2 or -2.0 PHP Code: <?php More about data types can be found on http://www.php.net/manual/en/language.types.php Variables In the above codes you've seen words that start with a dollar symbol ($), these are the so called variables. In PHP variables are declared using $ symbol and following with the name of the specific variable, variables names must start with a character or underscores, and can have multiple characters, underscores or numbers. Assigning the value to a variable is done with the egaul operator "=", following by the value of the array. PHP Code: <?php When declaring variables the best way to choose a name is based on the value they hold or should hold, that way you won't have problems knowing what variable holds when reading your code. In PHP variable names are case-sensitive, which in other words means that a variable declared with a name "var" is NOT as same as a variable with the name "Var". Also in PHP you don't have to declare the type of an variable and which value it holds, you can define a variable as boolean and then later in your script change it's value to a string, without the parser complaining about your decision. You can also assign a value to multiple variables PHP Code: <?php Basics Now that you know what variables are and how they are handled, let us go to calculations. Many may say you need to know Math for programming, well in few languages that is the case but not really in PHP, all you need to know are the basic forms of Mathematics. PHP Code: <?php As you can see it's simple, but there is more. When doing calculations you will need the exact form of what you need calculated. PHP Code: <?php Updating variables There are ways to update your variables fast, with the concatenation operator (.) you can add values to your variables. PHP Code: <?php You can also increase and decrease integral variables. PHP Code: <?php There is one little thing you should see, using "++" to increase the value of a variable by 1 can be done in two ways, those two ways are a bit different in output. PHP Code: <?php Passing The great power of PHP is the ability to pass your variables onto a different script, for example using a form where user can input his/her name. Passing variables can be done in two ways, the POST and the GET method. Here is a example of a post method: HTML Code: <html> In the above code, we create a form which when submitted will redirect the user to "login.php" file, that is done with the attribute "action". In the form tag you can see also a attribute called "method", this can be set to post or get, and based on which method you use you'll need the right variables to check and call. login.php PHP Code: <?php "$_POST" is a so called super-global variable, it holds the values of a HTML form that was sent using the "post" method. So when the form in the above html code is sent (the submit button was pressed), all "<input>" fields are saved to our "$_POST" variable and we can access them with our PHP script To access a specific value within the "$_POST" variable you need to call the right member. In the above code we have created a input field for our users name. Code: <input type="text" name="usrname" /> Take a look at the "name" attribute, it' defined as "usrname". So to access this input field with PHP you'll need to call it by it's name PHP Code: $_POST['usrname'] The other way is the "GET" method, the "GET" is used as same as "POST" but it works different. Look at the url of this page and you will see a "GET" method. Code: http://www.supportforums.net/showthread.php?tid=01 As you can see you are currently viewing the "showthread.php" file, after that you see "?tid=01", that is the "GET". ? symbol is used to define the use of the "GET" method, after that variable names follow and "=" their value, so to access the variable "tid" your PHP script will look like PHP Code: <?php Easy isn't it. There are more way to pass variables and you will learn more about them when you start writing your PHP scripts. Other two are $_COOKIE and $_SESSION. Arrays In the above code you've seen something new on our variables. PHP Code: $_GET['tid'] "['tid']", I bet you already wonder what that is, well it's a member of a so called Array. http://www.wikipedia.com Wrote:An array is a systematic arrangement of objects, usually in rows and columns. Specifically, it may refer to several things. PHP Code: <?php When using array the first thing you should know is, they can be called by the name of the member or by the ID. As seen in the above code "$user['name']" and "$user[1]", you might think why are the above outputs not the same since the first memebr of the array "name" is, well that's easy Array count starts with "0", so you would need to call "$user[0]" to output the value of "name" member. Checking The arrays brings us to the checking of variable values. PHP Code: <?php In the above code we use the if function to compare "$usrname" with "$admin", if both have the same value we print out a welcome message. For that we use Comparison Operators, to be exact we use "==", which checks if the two values are equal. More info: http://php.net/manual/en/language.operators.comparison.php But in the above code if "$usrname" isn't equal to "$admin" there will be no output, this we can change by using the else function. PHP Code: <?php "Else" is used to execute a code block if the comparison didn't match, so if "4usrname" don't have the value that is same as "$admin" (Geek), the code in the "else" block will be executed. And what to do in a case you have two admins, for that PHP has a function elseif, "elseif" is used to run another compare between two or more items if the first failed. PHP Code: <?php As you can see above we are first checking if "$usrname" is equal to "$admin[0]", if not we ust "elseif" to check if "$usrname" is equal to "$admin[1]". And if there is no match we print out "You are in the wrong place!". There is also a functions called switch, it it as same as using "if" and "elseif" mulitple times. PHP Code: <?php We use switch to check the value of "$int" and then output the right message. "case" is used to define a value that needs to be checked, so if our $int variable has a value of "0" it will output "$int = 0". "default" is the default "case" that is executed if no matches occured during our switch execution. Also not to forget break, as the words says, it breaks the execution of the switch function, if "break" isn't found the function will run until the end or the next matched "break" Looping There are times when you want your script to execute a code block more then one time, for this case you can use functions like for. PHP Code: <?php The first parameter "$i = 0" is used to define a variable that is used for counting the loops, the second parameter "$i <= 10" tells the function to run as long as "$i" is under or equal "10" ( <= ), and as you learned in the begining "$i++" is used to increase the value of "$i" by 1 on the end of the loop. The output of the above code will look like this. Code: 0 Another way of looping things is the while function, this function does the same as "for" function but it only uses one parameter. PHP Code: <?php As you see it's pretty simple, but if you don't increase the value of "$i" the function will run endless. Another way of using the "while" function is do function. Basiclly it's definition is DO FIRST CHECK LATER. PHP Code: <?php There is also a way to run loops throught a "array", a function used for this case is called foreach. As the name says it exectues a code block "for each" memebr of the given array. PHP Code: <?php The "foreach" function runs trought the array until it reaches the "end" of the array, the id of the member is declared in the "as $index" and the value of the memebr is then put into "$value" variable. Functions So far so good, there is even more, often you'll need the same code to do something more then one time but without using one of the looping methods. This can be done with the functions, functions are used to hold code blocks and excute them only when the function is called. PHP Code: <?php In this code we have created a function with the name "calculate", you can name your functions as you like but you should use a name that isn't already a PHP built in function, like for example "while". The code inside of function is only executed when the function is called. The above function accepts 2 parameter "$x" and "$y" those parameter can be set when the function is called. PHP Code: calculate(5, 5); Since all that our function does is "print $x + $y" it will output "10", since 5 +5 is 10. Variable scope http://www.php.net Wrote:The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. PHP Code: <?php The above function is used to output the value of "$i", but because "$i" was declared outside of the function the only thing the function will output is a "Undefined variable" error message. Because "$i" was declared outside of the function it has a "global scope" nad must be declared within the function as global. PHP Code: <?php The function now when called will output "5", because the "$i" was declared as global. All variables that are declared within the function have "local scope" and can only be accessed by the same function Read more: http://php.net/manual/en/language.variables.scope.php More Info Reading tutorials is good but you shouldn't concentrate much on tutorials, you should rather download and read already writen PHP applications and try to understand what the code is doing. You should also try writing everything you can think of. The best site to get help with PHP ist their own http://www.php.net/docs Thank you for reading and also check out my other tutorials Debugging your PHP code Securing Web Aplications Create Newsletter subscription RE: PHP Beginners guide - h1r0n - 10-16-2009 Good for starters... can you include classes?? RE: PHP Beginners guide - Gaijin - 10-16-2009 (10-16-2009, 03:52 AM)n1tr0b Wrote: Good for starters... can you include classes?? Thanks! Yeah I was thinking about that and I tought to write another tutorial that is only about the classes. RE: PHP Beginners guide - h1r0n - 10-16-2009 (10-16-2009, 03:53 AM)NinjaGeek Wrote: Thanks! classes are very useful for me.... always RE: PHP Beginners guide - Gaijin - 10-16-2009 (10-16-2009, 04:59 AM)n1tr0b Wrote: classes are very useful for me.... always Not only for you, but a newbie doesn't need them.... I will do one totally about classes in PHP RE: PHP Beginners guide - tartou2 - 10-16-2009 I know one thing. I am a noob when it comes to programming and you are my teacher now. Php doesn't looks hard, maybe because i know a little about c++ and they both have similars and close concepts but i remains a different language. thx for the tut, i was looking for a similar one to help learning php RE: PHP Beginners guide - Gaijin - 10-16-2009 (10-16-2009, 05:46 AM)tartou2 Wrote: I know one thing. Thank you! I'm glad it is helpful for you! If you have any questions just PM me or post it here. RE: PHP Beginners guide - immi - 10-16-2009 Nice tutorial. Thanks for sharing Ninja ;) RE: PHP Beginners guide - Gaijin - 10-16-2009 (10-16-2009, 06:32 AM)immi Wrote: Nice tutorial. Thanks for sharing Ninja ;) Thank you too, for reading it. RE: PHP Beginners guide - h1r0n - 10-16-2009 (10-16-2009, 05:00 AM)NinjaGeek Wrote: Not only for you, but a newbie doesn't need them.... dude classes... for me... speeds up some coding job, and time... |