PHP for Web Development

PHP for Web Development

PHP for Web Development DOUG LLOYD: So in our video on PHP syntax, we talked a lot about how PHP can be used at the command line to run programs in a manner that we’re pretty familiar with from C. But as I also mentioned in that video, PHP was initially developed to implement web programming, websites.

And so in this video, we’re going to talk about how we use PHP in the web development context. >> We know, already, from our video on HTML, that websites are built out of a set of HTML tags that semantically define the structure of a web page.

But websites that arebuilt with pure HTML suffer from a very,very serious limitation. >> And to illustrate this limitation,let’s consider the following. So now I want to build a web pagethat, whenever the user visits it, it gives me the currenttime in Cambridge, Mass., displaying it to the latest minute. If I was making this right now,I might say something like this.

Current time in Cambridge– so I haveHTML tags, head tags, title tags, body tags– the currenttime in Cambridge is 14:08, printing out military time. >> What happens if it’s now 2:09 PM, 14:09? Well so far, with HTML, I haveto go in and change it to 14:09. And then one minute later,I have to change it again. And then one minute later,I have to change it again. And as you can imagine, that’sprobably the worst job ever.

You’re the webmaster for a web page, and every minute, 24 hours a day, you need to update the current time manually opening time.html and changing just that snippet of code to say the current time in hours and minutes.

That’s probably not a very good use of our resources, both human and computational. >> Websites that are all HTMLare completely static. The only way you can update content, as we’ve just seen, is to manually open those source files, edit them, and save them. PHP for Web Development

And then when the userrefreshes the page, or visits the page for the firsttime, they’ll get the latest content. But only because we’vemanually edited it. >> If we start to mix some PHP in there,our code can get a lot more flexible. And we can have a way for our pagesto be dynamic, or update themselves, without requiring our poorwebmaster in the previous example to be manually updating things.

PHP for Web Development

They can do it automatically. We don’t have to intervene. We can get some sleep. Which is probably a good thing ifyou’re doing a lot of web programming. >> So in CS50 IDE, we run aweb server called Apache. It’s a very commonly used,open source web server system. This system has thecapacity to interpret PHP, which is going to be useful ifyou want to do any PHP programming. >> And in CS50 IDE,

we have a commandto make this very easy to do, apache50 start. And then that slashpath, slash to, slash dir, that’s just a really common way ofindicating what you’ve specified here is a path to a particulardirectory that you want to be the rootsite, or the root page, or the folder from which your web serverwill start to examine files and serve them up to clients who request them. PHP for Web Development

So let’s pop over to CS50 IDE, just toshow you, really quick, how this works. >> So here in CS50 IDE, I’m in adirectory called Week Zero Nine. And I have two– I haveexecuted an LS command just above to show you that I havetwo directories in here, PHP, which is the set of files that I used inthe PHP syntax video, and then PHP-web, which is the set of files that Iwould like to use in this video. >> And I would like to

starta web server instance with the contents of the PHP-web folderas the files are being served up. So what am I going to do? I going to type apache50 spacestart, space PHP, dash web. That’s the path to directoryfrom where I currently am. Then I hit Enter. It’s going to do alittle bit of stuff here. And then it’s going to say,Apache started successfully. Your site is now available at– andthen there’s the URL for the site.

So what am I going to do? I’m going to quickly copy this. And I’m going to open up– andI’ll zoom out a little bit here– I’m going to open upa new tab in Chrome. And I’m going to visit that URL. >> I’m going to hit Enter. It’s going to load. And I’ll zoom out again. And we can see here is thecontents of my PHP web directory. >> So now what is basically happeninghere is, my instance of CS50 IDE is serving up these

PHP for Web Development

files toanybody who requests them. And over the course ofthis video, we’ll sort of take a look at a bunch of thesedifferent files in context. >> To test that your Apacheserver is working, which is generally goingto be the case in CS50 IDE, but if you do this more generally,and you start building your own web servers, there’s a reallycommon sort of analog to, “hello world,” that is usuallyused for PHP web development. Which is to have a fileconsisting of just this code– a PHP delimiter set with PHP

info,parentheses, semicolon in between. Which is basically a specialPHP function that tells you what version of PHP you are running. >> So in CS50 IDE, I havethat file available just to show you what this would look like. So I’m looking at my indexfrom my PHP instance. My Apache instance is runningthe contents of PHP-Web. And I have a file here called info.php. >> I’m going to click it, zoom out. This is what you’re goingto see, pretty much. This is just telling me thatmy Apache server is working. And this is, apparently, theversion of PHP that I’m running.

This is my analog to “hello world.” >> So I know things are operational. So we’re good to go. We can proceed from here. >> So let’s revisit thattime example we were talking about with our poor webmasterwho had to update the page constantly. This might be a fix for howI would implement things so that the webmaster didn’thave to keep updating the time. It would just sort ofhappen automatically. >>

The down below, the HTML, it’spretty similar, with one exception. But here I’ve got some PHP at the top. I have, apparently, called thisfunction date_default_timezone_set. >> And we don’t talk about allthese functions in CS50, because PHP has probablytens of thousands. That might be a bit of anexaggeration, but it might not be. It’s got a lot of functions built in. And so this is a function apparentlysets my time zone as US/Eastern, which is the time zone that I’mcurrently in making this video.

>> Then I make a call tofunction called, date. And, apparently, I’m storing theHIS of something called, time. So what’s going on here? >> Well, basically what’shappening is, I’m making a call to some server that is going totell me what the time currently is. And I’m converting it to a formatof hours, minutes, seconds. And the reason it’s capital H is thisis going to give me 24 hour time, not 12 hour time, which would be lowercase h. And I’m just storing thatin a variable called, time. So that second line of PHPthere, the call to the function, date, is just gettingsome string, which is going to give me the date, and thetime, and a bunch of other information.

And the first argument there, that HIS,is just extracting the important part that I care about for this example,which is the hour, minute, and second. So that’s the all that’s going on. So I store that in a variable $time. And then down at thevery bottom there, I have that shorthand forprinting out the current time. So I’m just going to printout what the current time is. >> So let’s take a look at this inCS50 IDE and see how we’re now saving that webmaster a lot of trouble.

All right, so here I am againback at the root directory of my Apache instance. And I have a file here called time.php. I’m just going to click on that. And I’ll scroll up, becausewe’re zoomed in pretty far. The current time is 14:20:34. So I’m doing it hours,minutes, and seconds. And I can refresh thepage and get new time. –41. I’m going to refresh the pageand get new time, 44, 46, 47. >> So, I am clearly notchanging anything myself. I’m here refreshing the page. So I can’t be back there editing it. And I promise you, I don’thave any confederates who are editing the fileon my behalf on the side. >>

I’m just using that PHP function,time, to generate the time for me automatically. So that even if I’m asleep,and my web server is running, the user who visits that page is stillgoing to get exactly the current time. So that’s pretty good. I’ve made my site more dynamicwith not too much PHP code. It was just two lines of code and thena little bit of a print statement. And already I have amuch more dynamic site than that first example we sawat the beginning of the video. >> So, recall from the video on PHP syntaxthat when the PHP interpreter runs our program, it ignores everythingthat’s not inside of PHP delimiters, spitting it out. In that example, what the thingthat it was spitting out was HTML.

And this means I can nowintersperse HTML and PHP together. Because the interpreter will justignore the HTML and literally output it. Which is good, right? >> Because presumably,at the end of the day, I would like my site tobe constructed of HTML. So that any web browser can interpretit, or understand the HTML on the page and render it as something that wecan actually understand as humans. And I can only use PHPfor the parts of my site the require dynamism, that require meto have things that update constantly. The static informationcan stay the same.

>> OK, so that’s fine. But why would I do this? Why would I mix HTML and PHP? I could just print out all theHTML, using the PHP print function. Why am I not doing that? Think about it for a second. >> Why, when I could just print out– Icould have lines of PHP that just say, print HTML tag, print head. Why am I not doing that? Why am I mixing the PHP and HTML? >> Well, if you thinkabout it for a second. PHP, the interpreter hasto interpret what it sees. And so it’s going to haveto execute a line of code.

Print out HTML. Print out open head tag. Print out open title tag. It’s going to have toexecute and interpret that every single step of the way. Why not just let theinterpreter just gloss over things it doesn’t understandand do it automatically? It’s going to save me a lot of timeto mix my HTML and my PHP together. >> And so that’s why we don’tjust have open PHP delimiter and then just print out the entirecontent of our page as one giant PHP.

call to the function, Print, and thenclose PHP delimiter and we’re done. So that’s why we mix them up together. >> So far, we haven’t seen too much ofa difference from general PHP syntax. It’s been pretty straightforward. We’ve already seen thequestion mark, equal. We saw a couple of new function calls,but nothing really fancy going on. Let’s maybe make thingsa little fancier. What if we want to pass informationbetween different PHP files, so that maybe the user cansubmit information to me. And then I could do somethingwith it on another page.

>> So PHP has support forsomething called Super Global Variables, which sounds pretty awesome. They’re really justgiant associative arrays that help implement thisfunctionality of passing information between PHP files thatare existing on our web server. >> The first of these superglobals is called $_GET. And it’s probably thesimplest to understand. What happens with $_GET? Well, basically, the user isgoing to type extra information at the end of our URLs.

And whatever they type, assumingit’s formatted in a particular way called a query string, which is justa set of key value pairs separated by ampersands. Those key value pairs will bestored in a $_GET associative array. And from our video onPHP syntax, we know how to work withassociative arrays already. So here is an example ofsome PHP, where maybe I’m extracting all of the key value pairsthat the user supplied in the URL.

So I have my Open PHP delimiter. I have a foreach loop. I’m iterating across the SuperGlobal Array called $_GET. >> And I want to be able to referto both the key and the value. And I’m just printing themout, each one on apparently its own paragraph tag here. I’m printing out some HTMLand interpolating the values of key and value into that statement. >> So let’s take a look at how thiswould actually work on our IDE. And maybe this will helpillustrate a little bit of what GET is actually doing. So I’m back here in my web root. And I’ll zoom in alittle bit to show you that I have a file called, get1.php. >> So let’s click on get1.php.

And I’m not seeing any content. That’s weird, right? Well, not really actually. Because I didn’t supplyanything in the URL. I’m going to get1.php, but Ididn’t supply any key value pairs as part of my query string. So let’s add a query stringand see what this file can do. >> To begin a query string youjust type question mark. Then maybe I’ll say name=Doug&year=2015. And then I will hit Enter. Now notice what’s happening. I’m still in get1.php. But now I’ve suppliedkey value pairs, and I’m printing them out on their ownparagraph– name, Doug– year, 2015.

That’s exactly the code we justsaw on the slide a moment ago. >> And if I want to maybe add anotherkey value pair, &class=CS50. Now I have another key valuepair that’s printed out when I revisit the URL again. Now maybe this isn’tformatted terribly well. So I have another version of get.php. It’s get2.php. >>

The difference in thisone is I have CSS file, and it formats things alittle more nicely for me. It’s maybe not the mostbeautiful CSS in the world. But it’s just another way of doing it. So I can still get accessto my variables using $_GET. And in this case, I’m just kind ofmaking the CSS a little more fancy. And if we pop over tomy IDE for a second, I’ll show you in my PHP webdirectory here, get2.php. We’ll open it up, some HTML here. Apparently I’m linking in thatCSS file I was talking about.

I open a table tag. And then here’s my foreach loop. >> Here is that, what Ishowed on the slide before. The only difference is Ihave this key and value CSS styling that I’m applying to it. But that’s all I’m doing, is I’miterating across $_GET to get all of the key value pairs. >> And I’m printing them out as the table. And, apparently, I’m formatting the keysin one way, with the <td class=”key”.

So apparently that applies to someclass selector in my CSS file GET.CSS. And, apparently, I’m printing out my values a totally different way. Which is pretty muchwhat we saw here, where our values were printedwith a blue background, and our keys were printedwith a yellow background. So that’s how I’m gettingthose different styles. Because I’m using different CSS classes. But that’s pretty much it for GET. Like I’m just extracting information. And in this case, I’m justprinting it to the screen. I’m getting it out of the URL,and that’s what GET does for us.

>> Do you see a possibleproblem here though? Why would we maybenot want to use $_GET? What if, maybe, I was making this query? –to get3.php, which Idon’t have on my IDE. It’s just a hypothetical file. But notice here that apparentlypassing my password in. And maybe my password is embarrassing. Or maybe I don’t want people toknow what my password is, right. >> If I’m passing it though– if I’m using the $_GET method, what happens is, that’s going to be in the URL.

So some malicious user mightbe able to see what I’m doing. I may be passing themsensitive information. Or maybe it’s not even a malicious user. Maybe it’s just your friend whois standing over your shoulder. And now they know the passwordto your Facebook account. >> And maybe they wouldn’tdo anything with it. But if your password weresubmitted via $_GET to Facebook, now they know your Facebook password. Because it’s right there in the URL when

you’ve done submitting information. >> And so perhaps that’s not the bestway to pass sensitive information. It’s a good way to pass informationthat we don’t particularly care about as being too sensitive. Because GET is pretty fast,relative to the other super globals we’re going to talk about. But maybe not the best toolfor sensitive information. >> For that we might want touse something called $_POST, which is another Super Global Variable.

It’s another associative array. So it works pretty muchexactly the same as GET. Except, instead of extractinginformation from the URL, it does something through HTTP headers. So recall from ourvideo on HTTP, we talked about how browsers, servers,and clients communicate. And information is passed backand forth in HTTP headers. >> With $_POST, information is typicallysent through those HTTP headers.

And we’ll most commonly see $_POST inthe context of submitting HTML forms. You can still use HTML formsto submit things to GET. But they’re usually usedin the context of POST. >> So here’s an example of an HTML form. Now we’ve seen these before, but we havenot seen this part, action=”post.php”. So when we talked about forms in thecontext of HTML, I had a Submit button. And if you recall, I’d click Submitand then the page just refreshed, didn’t do anything. >> In this case, I’m submittingwhatever I type at this form, to a PHP file called post.php.

And, apparently, the way I’m doing thatin this form is using the POST method. So every piece of informationthat I type into this form will be submittedthrough the HTTP headers. >> It will be accessible in post.php,because that’s the action of my form. It will be accessibleby going to $_POST. And apparently, the way I canget at each individual element with that associative arrayis with this attribute,

the Name attribute of our input tags. >> So apparently I can say $_POST squarebrackets name to get whatever the user typed in the first field. And $_POST password, of pw rather,to get at whatever the user typed in the second field. >> So let’s take a look atthis over in CS50 IDE. So here we are, and I’llzoom in for a second. And we have a file called post.html. I click on post.html. At the very top here I havea very simple web form. It’s the form we just sawon the slide a second ago. >>

I can type, Doug, and I cantype my password, which we all know is squadgoals. And I will hit Submit. And apparently, thatsubmits to post.php. And I’m apparently printing that. So I’m getting rid of all the securitythat POST gives me by just printing out the username and password. >> The user’s name is Doug. The user’s password is squadgoals. How did I do this? Well, pop over to IDEagain for a second. We will scroll down to takea look at post.php,

which was the action that I used to submit here. That was the action of my HTML form. And that’s all I’m doing. The user’s name is, and I’m printingout the contents of $_POST “name”. And then the user’s passwordis $_POST “password”. So I was given that informationby submitting the HTML form. And I can now extract it using $_POSTbecause the method I used to transmit data with that form was the POST method. >>

Now it’s probably not so great– I’m going to go back for a second to our set here– it’s probably not so great if I am submitting information with POST, which is ostensibly more secure. It’s probably not so great if I’m doing that and then printing out the user’s password. It’s supposed to be more secure. >> OK, but it’s not entirely secure. And so in this little snippet here I want to just draw your attention to someday security concerns, just something to think about as you’reworking PHP for Web Development

or using the internet. This is just something to consider. >> I told you that information issubmitted through HTTP headers when you use the POST method. Which means they’re not entirely secure. They’re harder to find thanusing the GET method, where it’s just right in the URL. But there’s still a way to find it. And I just want to showyou this so that you maybe start to think about thisas you’re working,

or using websites and submittingpasswords, and maybe using the same password in alot of different places. Know that is is still actually prettyeasy to find out somebody’s password. >> And so here, I’m goingto go to post2.html. And the difference with post2.htmland post2.php is pretty subtle. The difference is justthat I don’t print out the password when I submit the form. >> So I’m going to type in, Doug. And I’m going to typein, squadgoals,

even though we know that’s the password. Before I submit the form though, I’m going to open up Developer Tools, just to show you what’s going to happen here. So in Chrome, I’m just going to hit F12. And that’s going to open up my developer Tools on the right-hand side. I haven’t submitted the form yet. Now I’m going to hit Submit on my form. And apparently, I made a call to, or I made a request to post2. PHP for Web Development

PHP, which makes sense. I’m going to click on that. >> Then over here, I’m going to click on Headers. There’s a lot of stuff going on here. But if I scroll down to the very bottom, notice right there– my calendar has blocked it for a second– right there at the very bottom corner, the name– Doug, PW– squad goals. PHP for Web Development

So even though I’m using the POSTmethod, which is more secure, just be aware that when you do so,you’re still transmitting information through HTTP. And it can still befound by an adversary. It’s just something we’re goingto have to deal with really. Maybe there’s some ways to encrypt ourpasswords before we send them over, which would be a better,which I’m not doing here. >> But just be aware that the POSTmethod has limitations too. It’s an improvement over GET interms of being immediately visible. But it’s not a complete fix.

So here’s an example ofa quick at home exercise that you can use to get somepractice working with PHP. Create the following pair of web pages. The first should just be a very simpleform with a single field and a Submit button. So very similar to what wejust did with post.html. >> And then the secondfile you should create is a file, a PHP file, thatis expecting input, via POST, and based on what the user typed, whichyou can assume will be an integer. You don’t have to do anyerror checking or the like. You can assume the userwill type an integer value, or something like.

an interpreted byPHP as an integer, into that form. You just want to create ann by n multiplication table. >> So if the user submits 10, we want tohave a 10 by 10 multiplication table. If the user submits a 12, we wanta 12 by 12 multiplication table. Just so you can see whatwe’re driving at here, we’ll take a look atthis file in my IDE. >> So here in IDE, I have mult_form.html. I’ll click it.

All I want to do is submit a value. Type in 10, hit Submit. And apparently, mult_table.php, whichwe can see at the top there in the URL, I’m creating a 10 by 10multiplication table. >> If I type 15 and hit Submit, now Ihave a 15 by 15 multiplication table. I’m, of course, not going to showyou the contents of mult_table.php, because that would take the funout of this at home exercise.

But it’s a great way to get somepractice working with PHP loops and POST, very simple, hopefullystress free example, just to do a little bit of practice. And I’ve got a little CSS going onhere to to make my individual table cells just kind of pop off alittle bit and look a little more like a multiplication table,as opposed to just text just kind of sitting there. The last super global we’ll talk aboutin this video is something called $_SESSION.

And maybe this is actuallythe best example of something we would consider global. It’s another array. It’s another associative array. But it is accessible through everyPHP file that exists on our system. >> We don’t have to submitinformation one page at a time like we do with GET and with POST. It’s always there. And so this is great for a pagewhere you are logged in, for example, and you want your login informationto persist from page to page to page. >> You can just start a session and thenuse $_SESSION to save things like the user’s name, or the user’sID information, and so on. PHP for Web Development

And that information will remain in$_SESSION until you destroy the session a little bit later on. >> Writing dynamic websites withPHP makes them a lot better. Your sites become verydynamic, and you don’t have to do too much more than whatyou otherwise would have done just doing it with HTML. But it requires practice,a lot of practice. >> You already know how to work with C,and so jumping to PHP isn’t too tricky. What is maybe a littlebit tricky is working with this new idea of GET and POST,

and maybe mixing your HTML and your PHP together. But also be aware that the internet is a vast repository of information. And PHP’s documentation is available in many places, but perhaps most canonically at And you can find there, lots of different functions, and use cases, and examples upon examples, upon examples. PHP for Web Development

Where if you want to try and figure out how to do something, odds are, somebody’s probably done it before you. And you can use them as inspiration to implement whatever it is you’re trying to implement too. >> I’m Doug Lloyd. This is CS50. PHP for Web Development

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts