Thread: [PHP] Echo, Variables, Functions, Switch, If/else and Cookies [PHP]

Results 1 to 7 of 7
  1. #1 [PHP] Echo, Variables, Functions, Switch, If/else and Cookies [PHP] 
    puts "Hi "+name+
    Ruby's Avatar
    Join Date
    Apr 2012
    Age
    25
    Posts
    346
    Thanks given
    42
    Thanks received
    135
    Rep Power
    66
    Hello there Rune-Server.

    I consider myself pretty good with PHP, however I do sometimes leave loopholes and such and even leave it open to SQL Injection, so if you ever see me posting it with these problems don't hesitate to tell me. My code is sometimes scruffy and scrappy, but it does get the job done.

    Without further ado, here is my PHP crash course.

    With me posting this, I assume you have PHP set up and you have it ready to start creating scripts, I will not run through this, there are countless guides everywhere.

    Part 1, initiating php.
    The first thing you want to learn to do when learning PHP is how to initiate PHP. This tells your browser that it is relaying PHP, not HTML. You do this by using the following tags;
    Code:
    <?php //starts  php
    //your code in here
    ?>//ends php
    You will probably see me posting them like this though;
    Code:
    <? //starts php
    //your code in here
    ?>//ends php
    This does the very same job, but it's shorter and I think it looks tidier, but that's just me. You can use either and they'll work exactly the same. Just whenever you're programming php, you must use these tags and include all of the PHP coding between these tags.

    Part 2, echoing data.
    So, the second part of learning PHP is how to actually display writing on a page. You do this by using the echo() function. This can also be done using the print() function, however I remember reading somewhere that echo() was faster than print() so I always use echo(). Lets get to our first script!
    Code:
    <?
    echo "Hello there Ruby!";
    ?>
    If you put this inside a .php file and relay it through a server then you'll find your page will now just display the words "Hello there Ruby".

    What this code is is that you have your opening <? ?> tags, you then have your echo() function, your message between the quotation marks, and then finally, one of the most important parts of PHP, the semicolon at the end of the line.
    ALWAYS PUT A SEMI COLON AT THE END OF THE LINE UNLESS INSTRUCTED NOT TO.

    Echoing a variable, or several.
    Code:
    <?
    $testString = "Hello Ruby!";
    echo $testString;
    ?>
    Notice here how you do not use any kind of quotation marks around the variable when echoing.

    Code:
    <?
    $testString = "Hello ";
    $testString2 = " Ruby!";
    echo $testString.$testString2;
    ?>
    This here is what you would do if you wanted to echo two variables beside each other in a piece of code, you join them by a period "." this is used as a joining factor throughout PHP, but more on that later.

    Be careful when echoing quotation marks, for example, through HTML tags.
    Code:
    <?
    echo "<font color="red">I love ruby!</font>";  
    ?>
    The above code won't work because of the multiple quotation marks in the echo statement.

    Code:
    echo "<font color=\"red\">I love ruby!</font>";  
    
    echo "<font color='red'>I love ruby!</font>";
    The above two codes will however, work. The first because of the backward slashes showing they're not the end to the echo statement. The second because we used apostrophe's instead of quotation marks.

    Echoing variables and text strings:
    Code:
    <?
    $my_string = "Hello Ruby.  My name is: ";
    echo "$my_string Cammy <br />";
    echo "Hi, I'm Ruby.  Who are you?<br />"; 
    echo "$my_string Cammy";
    ?>
    Test this code out, it's rather fun to play around with these as they can be slightly confusing at first.

    Okay, that's our first section done on Echoing. We also covered some variables inside that there, however it shouldn't be too confusing as we move onto Variables right now.

    Part 3, Variables.

    A variable is a means of storing a value, such as text string "Hello World!" or the integer value 4. A variable can then be reused throughout your code, instead of having to type out the actual value over and over again. In PHP you define a variable with the following form:
    $variableName = Value;
    If you forget that dollar sign at the beginning, it will not work. This is a common mistake for new PHP programmers!
    Note: Also, variable names are case-sensitive, so use the exact same capitalization when using a variable. The variables $aNumber and $Anumber are different variables in PHP's eyes.

    Okay, so now you know the basics, lets use some more variables!

    We'll start off with this code;
    Code:
    <?
    $text = "Hello RuneServer!";
    $aNumber = 4;
    $anotherNumber = 8;
    ?>
    Here we have stored 3 variables, one text string and two numerical values. Note how the text must be wrapped in quotation marks, but the numerical values don't.
    PHP also doesn't need the variables to be declared before being initialized.

    Naming Conventions.

    PHP variables must start with a letter or underscore "_".
    PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _ .
    Variables with more than one word should be distinguished with capitalization. $testVariable

    You have already used variables in the echoing part, but we'll do a small exercise here.

    Code:
    <?
    $myVar = "Rubys tutorial ";
    $secondVar = "is ";
    $thirdVar = 1337;
    
    //echo all three together
    
    echo $myVar.$secondVar.$thirdVar;
    ?>
    Remember that? Mess around with it and get used to variables, these are essential in any programming language.

    You can also do mathematics inside variables and using variables. To times a number, use the asterisk - "*", to subtract, use "-", to add use "+" and to divide use "/".

    Use these for a while too, just get used to them.

    Part 4, Functions
    A function is just a name we give to a block of code that can be executed whenever we need it. This might not seem like that big of an idea, but believe me, when you understand and use functions you will be able to save a ton of time and write code that is much more readable! Functions are generally thought too hard for beginners to use, but if you stick with them and persevere then you'll be 100% fine and it'll bring you on a lot through programming.

    So, lets create our first function!

    Code:
    <?
    function whatIsThisSite() {
    echo "The best community ever!";
    }
    ?>
    This may seem just a question and answer, but you can do a lot with functions. For example;

    Code:
    <?
    function whatIsThisSite() {
    echo "The only site to go to!<br />";
    }
    echo "Welcome to MoparScape!<br />";
    whatIsThisSite();
    echo "We love to see new users coming in!<br />";
    echo "enjoy your stay, and remember we are...<br />";
    whatIsThisSite();
    ?>
    So this is more or less what you can use a function for, but the list is endless, there is hundreds of reasons to use functions.

    You may realise that the above function is more or less an oversized variable. Here's a much better use for functions;
    Code:
    <?
    function myFunction($firstName, $lastName){
        echo "Hello there ". $firstName ." ". $lastName ."!<br />";
    }
    myFunction("Mod", "Cammy");
    myFunction("Mod", "Nick");
    myFunction("Mod", "Omer");
    myFunction("Mod", "Tyler");
    myFunction("Mod", "Justin");
    myFunction("Mod", "Zeng");
    ?>
    This is a more useful function, just adapt it to your needs.

    Here's a few protips for when you're using php functions;
    - Always start your function with the keyword function
    - Remember that your function's code must be between the "{" and the "}"
    - When you are using your function, be sure you spell the function name correctly
    - Don't give up!

    Our last and final function is for php functions returning values.
    Code:
    <?
    function mySum($numX, $numY){
        $total = $numX * $numY;
        return $total; 
    }
    $myNumber = 0;
    echo "Before the function, myNumber = ". $myNumber ."<br />";
    $myNumber = mySum(3, 4);
    echo "After the function, myNumber = " . $myNumber ."<br />";
    ?>
    What this function does is holds a value of 0 before the function, after executing the function it then gains the value of the two numbers you had. You can also add in more variables such as $numZ and what not.

    Okay, so that wraps up functions, if you don't get it, don't worry. Keep at it!

    Part 5, switch statements.
    The way the Switch statement works is it takes a single variable as input and then checks it against all the different cases you set up for that switch statement. Instead of having to check that variable one at a time, as it goes through a bunch of If Statements, the Switch statement only has to check one time.

    Here's an example of a switch statement;
    Code:
    <?
    $revision = "317";
    echo "Your current revision is: <br />";
    switch ($revision){
    	case "317":
    		echo "317, the best there ever was!";
    		break;
    	case "474":
    		echo "474, alright, but starting to get worse.";
    		break;	
    	case "508":
    		echo "508, the peak of runescape, before it got horrible.";
    		break;	
    	case "525":
    		echo "525, the begin of the demise of runescape";
    		break;
    	case "525+":
    		echo "Over 525, ew.";
    		break;	
    }
    ?>
    After doing this, you can then put the default value in. If you look at my other tutorial on switch statements for pages in this board, you'll realise I use the default value there. This is more or less what shows if the variable is empty.

    You'd use it like this;
    Code:
    <?
    $revision = "317";
    echo "Your current revision is: <br />";
    switch ($revision){
    	case "317":
    		echo "317, the best there ever was!";
    		break;
    	case "474":
    		echo "474, alright, but starting to get worse.";
    		break;	
    	case "508":
    		echo "508, the peak of runescape, before it got horrible.";
    		break;	
    	case "525":
    		echo "525, the begin of the demise of runescape";
    		break;
    	case "525+":
    		echo "Over 525, ew.";
    		break;	
                  default:
                    echo "Would you like to find out what revision your server is?";
                    break;
    }
    ?>
    That's more or less switch statements, they're a lot easier than people think and can be used for a lot of things.

    Part 6, if/ifelse statements
    The if statement is necessary for most programming, thus it is important in PHP. Imagine that on January 1st you want to print out "Happy New Year!" at the top of your personal web page. With the use of PHP if statements you could have this process automated, months in advance, occuring every year on January 1st.

    Code:
    <?
    $yourName = "Ruby";
    
    if ( $yourName == "Ruby" ) {
    	echo "Your name is Ruby!<br />";
    } else {
           echo "Your name is not Ruby!<br />";
    }
    echo "Welcome to yourSite!";
    
    ?>
    This is just a general if else statement, if you wish to create an if statement, remove the else. Although, it works a tonne better with else in there, it's more professional in my opinion.

    There isn't really much to cover on this topic, you can add in as many else's as you need with certain parameters on them.

    Part 7, Cookies in PHP
    This is where I cover cookies and how you can use them, this type of cookie is a small text document that sits on your hard-drive and is accessed by the website that created them. These are used all the time, you probably have hundreds stored.
    Code:
    <?
      $visits = $_COOKIE['thissite'] + 1
        setcookie("thissite", $visits, time()+3600*24*365, "/", "www.yoursite.org", 0);
        if($visits > 1) {      
         echo "You have visited this site <? $visits ?> times.";      
      } else {
          echo "Welcome to this site, may you have many more pleasant visits.";
             }
    ?>
    This right here is almost the exact cookie I use on Xythax. What this does is that it stores the cookie on your hard drive with the setcookie() function and everytime I revisit a url with the name xythax.org in it, it adds 1 to the $visits variable and then you display it to someone who has more than 1 visit.

    This code uses everything from the setcookie() function, an if/else statement, mathematics in php and variables. This just shows you that a script this small uses all of that.

    Anyway Rune-Server, I've just spent the past like 2 and a half hours writing this guide for you, I hope you enjoy it and use it.

    Kind Regards,
    Ruby.
    Professional website developer
    Almost a decade experience
    Bespoke website templates
    CMS & forum themes
    Future proof & secure scripts
    We should chat...
    Reply With Quote  
     

  2. Thankful user:


  3. #2  
    Registered Member
    Join Date
    Jan 2013
    Posts
    6
    Thanks given
    0
    Thanks received
    0
    Rep Power
    0
    This is a really easy to follow guide it's really helped me.
    Reply With Quote  
     

  4. #3  
    http://smurl.es


    Join Date
    Nov 2012
    Age
    23
    Posts
    516
    Thanks given
    182
    Thanks received
    80
    Rep Power
    96
    I mean no disrespect buddy, but what you've just covered can be found on hundreds of sites that's had this up for ages. Sites like W3schools, tizag and so on.

    The guide is detailed and kept well, good one
    Thanks,
    DharmeshPHP.

    Creator of [Only registered and activated users can see links. ] - Check us out on [Only registered and activated users can see links. ]!
    [Only registered and activated users can see links. ] for MyBB show case.
    [Only registered and activated users can see links. ] - By DharmeshPHP
    Reply With Quote  
     

  5. #4  
    ♫ Start of Something Good ♫
    Jae`'s Avatar
    Join Date
    Mar 2012
    Posts
    1,495
    Thanks given
    236
    Thanks received
    245
    Rep Power
    69
    Cool share.

    I am not currently developing or administrating a public server, if you see my name on any server, it is likely an impersonator.
    Reply With Quote  
     

  6. #5  
    Registered Member
    Join Date
    Aug 2008
    Posts
    2,420
    Thanks given
    721
    Thanks received
    594
    Rep Power
    1233
    Don't use short tags, a lot of webservers have them turned off and it's a pain to change them all.

    Also your tabbing is messed up and is hard to read.
    [Only registered and activated users can see links. ]
    Reply With Quote  
     

  7. #6  
    Registered Member
    Sieu's Avatar
    Join Date
    Dec 2011
    Age
    24
    Posts
    1,167
    Thanks given
    186
    Thanks received
    131
    Rep Power
    160
    Quote Originally Posted by Joshua F View Post
    Don't use short tags, a lot of webservers have them turned off and it's a pain to change them all.

    Also your tabbing is messed up and is hard to read.
    yea, when i first started php i used short tags by accident and just had <? ?> and on some hosts it works but on others you gotta change it to <?php ?> and it's sooo annoying lol
    Reply With Quote  
     

  8. #7  
    Ballin~
    Wulfite's Avatar
    Join Date
    Nov 2013
    Posts
    163
    Thanks given
    13
    Thanks received
    10
    Rep Power
    49
    Very helpful thanks !
    Reply With Quote  
     


Thread Information
Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Replies: 4
    Last Post: 03-10-2011, 10:19 AM
  2. Replies: 20
    Last Post: 08-14-2010, 04:56 PM
  3. [PHP]The Echo
    By Z in forum Tutorials
    Replies: 13
    Last Post: 03-19-2008, 09:40 AM
Posting Permissions
  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •