PHP: What You Need To Know To Play With The Web

Advertisement

In this article, I’ll introduce you to the fundamentals of PHP. We’ll focus on using PHP to access Web services and on turning static HTML pages into dynamic ones by retrieving data from the Web and by showing different content depending on what the user has entered in a form or requested in the URL.

You won’t come out a professional PHP developer, but you’ll be well on your way to building a small page that uses Web services. You can find a lot of great PHP info on the Web, and most of the time you will end up on PHP.net1 itself. But I was asked repeatedly on several hack days and competitions to write this quick introduction article, so here it is.

What Is PHP? Link

PHP is a server-side language that has become a massive success for three reasons:

  • It is a very easy and forgiving language. Variables can be anything, and you can create them anytime you want.
  • It is part of the free LAMP stack (Linux, Apache, MySQL, PHP) and thus available on almost any server you can rent on the Web.
  • It does not need a special editor, environment or build process. All you do is create a file of the .php file type, mix PHP and HTML and then put it on your server for rendering.

Installing PHP Locally, And Your First Code Link

To run PHP locally on your computer, you’ll need a local server with PHP enabled. The easiest way to do this is to download and install MAMP for OS X2 or XAMPP for Windows3. Once you’ve installed any of these packages, you can start using PHP. Simply create a file named index.php in the htdocs folder of your MAMP or XAMPP installation.

In this file, type (or copy and paste) the following:

<?php
  $myname = 'Chris';
  echo '<p>This is PHP</p>';
  echo "<p>My name is $myname</p>"
  echo '<p>My name in another notation is still  '.$myname.'</p>';
?>

If you open this file in a browser by accessing your XAMPP or MAMP installation (via http://localhost/index.php or http://localhost:8888/index.php), you should see the following:

This is PHP
My name is Chris
My name in another notation is still Chris

But you won’t see that. The problem is that the third line does not end in a semicolon (;). This is an error. Depending on your PHP installation, you’ll get either an error message or simply nothing. If you get nothing, then find the file named php_error.log on your hard drive, and open it. It will tell you what went wrong.

The PHP error log as shown on a Mac

The first thing to remember, then, is that every line of PHP has to end in a semicolon. If we fix this problem, we get this result4:

PHP rendered in a browser

<?php
  $myname = 'Chris';
  echo '<p>This is PHP</p>';
  echo "<p>My name is $myname</p>";
  echo '<p>My name in another notation is still  '.$myname.'</p>';
?>

We can see here the first few important features of PHP:

  • PHP blocks start with <?php and end with ?>. Anything between these two commands is interpreted as being PHP and returned to the document as HTML.
  • Every line of PHP has to end with a semicolon (;), or else it is an error.
  • Variables in PHP start with a $, not with the var keyword as you do in JavaScript (this is where it gets confusing with jQuery and Prototype).
  • You print content to the document in PHP with the echo command. There is also a print command, which does almost the same, so you can use that, too.
  • In this example, we have defined a string named myname as “Chris”. To print it with the echo command surrounded by other text, you need to either embed the variable name in a text with quotation marks or concatenate the string with a full stop when you use single quotation marks. This is line 3 and 4: they do the same thing but demonstrate the different syntax. Concatenation is always achieved with a full stop, never with a + as you do in JavaScript.

You can jump in and out of PHP anywhere in the document. Thus, interspersing PHP with HTML blocks is totally fine. For example:

<?php
  $origin = 'Outer Space';
  $planet = 'Earth';
  $plan = 9;
  $sceneryType = "awful";
?>
<h1>Synopsis</h1>

<p>It was a peaceful time on planet <?php echo $planet;?> 
and people in the <?php echo $sceneryType;?> scenery were unaware 
of the diabolical plan <?php echo $plan;?> from <?php echo $origin;?> 
that was about to take their senses to the edge of what could be endured.</p>

This outputs the following5:

Rendered variables in PHP

Are you with me so far? To show something on the screen, particularly numbers or a string, we use echo. To show more complex structures, we need loops or specialized debugging methods.

Displaying More Complex Data Types Link

You can define arrays in PHP using the array() method:

$lampstack = array('Linux','Apache','MySQL','PHP');

If you simply want to display a complex data type like this in PHP for debugging, you can use the print_r() command:

$lampstack = array('Linux','Apache','MySQL','PHP');
print_r($lampstack);

This gives you all the information6, but it doesn’t help you structure it as HTML:

Displaying arrays with print_r

For this, you need to access the elements with the array counter. In PHP this is done with the [] brackets:

<ul>
<?php
$lampstack = array('Linux','Apache','MySQL','PHP');
echo '<li>Operating System:'.$lampstack[0] . '</li>';
echo '<li>Server:' . $lampstack[1] . '</li>';
echo '<li>Database:' . $lampstack[2] . '</li>';
echo '<li>Language:' . $lampstack[3] . '</li>';
?>
</ul>

See this demo in action7.

This is, of course, stupid programming because it is not flexible. If a computer is able to the dirty work for you, make it do it. In this case, we can define two arrays and use a loop8:

<ul>
<?php
$lampstack = array('Linux','Apache','MySQL','PHP');
$labels = array('Operating System','Server','Database','Language');
$length = sizeof($lampstack);
for( $i = 0;$i < $length;$i++ ){
  echo '<li>' . $labels[$i] . ':' . $lampstack[$i] . '</li>';
}
?>
</ul>

The for loop works the same as it does in JavaScript. The only difference is that you read the size of an array not with array.length but with sizeof($array).

Again, this example is not very clever because it assumes that both the $lampstack and the $labels array are of the same length and in the same order. Instead of using this, I’d use an associated array9:

<ul>
<?php
$lampstack = array(
  'Operating System' => 'Linux',
  'Server' => 'Apache',
  'Database' => 'MySQL',
  'Language' => 'PHP'
);
$length = sizeof($lampstack);
$keys = array_keys($lampstack);
for( $i = 0;$i < $length;$i++ ){
  echo '<li>' . $keys[$i] . ':' . $lampstack[$keys[$i]] . '</li>';
}
?>
</ul>

The function array_keys() gives you back all the keys of an array as an array itself. This way, we can display the keys and the values at the same time.

A shorter way to achieve the same principle, and which works with both arrays and objects, is to use the foreach() loop construct10:

<ul>
<?php
$lampstack = array(
  'Operating System' => 'Linux',
  'Server' => 'Apache',
  'Database' => 'MySQL',
  'Language' => 'PHP'
);
foreach( $lampstack as $key => $stackelm ){
  echo '<li>' . $key . ':' . $stackelm . '</li>';
}
?>
</ul>

This is the shortest way to display a complex construct. But it will fail when $lampstack is not an array. So, checking for sizeof() is still a good plan. You can do this with a conditional.

Using Conditionals Link

Conditionals are “if” statements, both in the English language and in almost any programming language I know. So, to test whether an array is safe to loop over, we could use the sizeof() test11:

<ul>
<?php
$lampstack = array(
  'Operating System' => 'Linux',
  'Server' => 'Apache',
  'Database' => 'MySQL',
  'Language' => 'PHP'
);
if( sizeof($lampstack) > 0 ){
  foreach( $lampstack as $key => $stackelm ){
    echo '<li>' . $key . ':' . $stackelm . '</li>';
  }
}
?>
</ul>

Common conditionals are:

  • if($x > 10 and $x < 20)
    Is $x bigger than 10 and less than 20?
  • if(isset($name))
    Has the variable $name been defined?
  • if($name == 'Chris')
    Does the variable $name have the value of "Chris"?
  • if($name == 'Chris' or $name == 'Vitaly')
    Does the variable $name have the value of "Chris" or "Vitaly"?

Cool, but what if we want to make this reusable?

Functions In PHP Link

To make a task even more generic, we can write a function. In this case, we put the loop and the testing in a function and simply call it with different arrays12:

<?php
function renderList($array){
  if( sizeof($array) > 0 ){
    echo '<ul>';
    foreach( $array as $key => $item ){
      echo '<li>' . $key . ':' . $item . '</li>';
    }
    echo '</ul>';
  }
}
$lampstack = array(
  'Operating System' => 'Linux',
  'Server' => 'Apache',
  'Database' => 'MySQL',
  'Language' => 'PHP'
);
renderList($lampstack);

$awfulacting = array(
  'Natalie Portman' => 'Star Wars',
  'Arnold Schwarzenegger' => 'Batman and Robin',
  'Keanu Reaves' => '*'
);
renderList($awfulacting);
?>

Note that functions do not begin with a dollar sign.

We've already seen most of the magic of PHP. The rest is all about building functions to do all kinds of things: converting strings, sorting arrays, finding things in other things, accessing the file system, setting cookies and much more, each of which does one and only one thing right. I keep catching myself writing complex functions in PHP, only to realize from looking at the documentation that a native function already exists for it.

Interacting With The Web: URL Parameters Link

Let's start playing with the Web in PHP… or, more precisely, playing with information that comes from the browser's address bar or with forms that we can re-use. To get parameters from the current URL, we use the global $_GET array. So, if you call the index.php script with http://localhost/index.php?language=fr&font=large, you can change the display and locale by checking for these settings. The language parameter will be available as $_GET['language'], and the font parameter as $_GET['font']:

<?php
$name = 'Chris';

// if there is no language defined, switch to English
if( !isset($_GET['language']) ){
  $welcome = 'Oh, hello there, ';
}
if( $_GET['language'] == 'fr' ){
  $welcome = 'Salut, ';
}
switch($_GET['font']){
  case 'small':
    $size = 80;
  break;
  case 'medium':
    $size = 100;
  break;
  case 'large':
    $size = 120;
  break;
  default:
    $size = 100;
  break;
}
echo '<style>body{font-size:' . $size . '%;}</style>';
echo '<h1>'.$welcome.$name.'</h1>';
?>

This means we can now send URL parameters to change the behavior of this document:

changing the content and look of a document with parameters

Notice that predefining a set of values that are acceptable for a certain parameter is always best. In the earlier example, we may as well have set the font size in pixels as a parameter and then written that to the document—but then we would have needed a good validation script to prevent end users from sending bad values or even malicious code through the parameter.

Sending malicious code via a parameter without filtering is called cross-site scripting16 (XSS), and it is one of the big security problems of the Web. You can prevent it by not printing out the values of parameters, and instead using them in comparisons, and by using the filters provided by PHP17.

Say you want to allow users to enter data in a form that you will display later on. Make sure to filter out the results:

<?php
  $search_html = filter_input(INPUT_GET, 's',
                              FILTER_SANITIZE_SPECIAL_CHARS);
  $search_url = filter_input(INPUT_GET, 's',
                             FILTER_SANITIZE_ENCODED);
?>
<form action="index.php" method="get">
  <div>
    <label for="search">Search:</label>
    <input type="text" name="s" id="search" 
           value="<?php echo $search_html;?>">
  </div>
  <div class="bar"><input type="submit" value="Make it so"></div>
</form>
<?php
if(isset($_GET['s'])){
  echo '<h2>You searched for '.$search_html.'</h2>';
  echo '<p><a href="index.php?search='.$search_url.'">Search again.</a></p>';
}
?>

See this filtering example in action18. Without the filters, attackers could send parameters like index.php?s="<script>, which would execute third-party code on your website. With filtering, this malicious code is converted to HTML entities.

If you want to use POST as the method to send the data in your form, then the PHP variables will change accordingly to $_POST for the array and INPUT_POST for the filter.

Loading Content From The Web Link

PHP comes with a lot of file functions19 that allow you to read and write files from the hard drive or to load content from the Web. I've found, however, that for security reasons a lot of hosting companies disable them, especially when you try to read content from a third-party resource. The workaround is to use cURL to load information from the Web. cURL is a tool that allows you to make HTTP requests to retrieve information—a kind of browser in command-line form. I've written a detailed post about cURL and how to use it20. Here, then, is a simple use case to illustrate:

<?php
  // define the URL to load
  $url = 'http://www.smashingmagazine.com';
  // start cURL
  $ch = curl_init(); 
  // tell cURL what the URL is
  curl_setopt($ch, CURLOPT_URL, $url); 
  // tell cURL that you want the data back from that URL
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  // run cURL
  $output = curl_exec($ch); 
  // end the cURL call (this also cleans up memory so it is 
  // important)
  curl_close($ch);
  // display the output
  echo $output;
?>

If you run this in the browser21, you'll see Smashing Magazine's home page.

Smashing Magazine homepage loaded with cURL

You could also strip out content from the data:

<?php
  // define the URL to load
  $url = 'http://www.smashingmagazine.com';
  // start cURL
  $ch = curl_init(); 
  // tell cURL what the URL is
  curl_setopt($ch, CURLOPT_URL, $url); 
  // tell cURL that you want the data back from that URL
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  // run cURL
  $output = curl_exec($ch); 
  // end the cURL call (this also cleans up memory so it is 
  // important)
  curl_close($ch);
  // if a filter parameter with the value links was sent
  if($_GET['filter'] == 'links'){
    // get all the links from the document and show them
    echo '<ul>';
    preg_match_all('/<a[^>]+>[^</a>]+</a>/msi',$output,$links);
    foreach($links[0] as $l){
      echo '<li>' . $l . '</li>';      
    }
    echo'</ul>';
  // otherwise just show the page
  } else {
    echo $output;
  }
?>

If you open this in your browser, you'll get all of the links from Smashing Magazine22 and no other content.

Smashing magazine links

Nowadays, though, we are more likely to use APIs than to load websites this way, which is why we need a way to convert the XML and JSON that are returned from Web services into PHP-friendly data.

Displaying XML Content Link

The easiest way to deal with XML content in PHP is to use the SimpleXML functions of PHP23. Using these, we can turn a bunch of XML into a PHP object and loop over it. To show Smashing Magazine's RSS feed24, we can do the following:

<?php
  $url = 'http://rss1.smashingmagazine.com/feed/';
  $ch = curl_init(); 
  curl_setopt($ch, CURLOPT_URL, $url); 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  $output = curl_exec($ch); 
  curl_close($ch);
  $data = simplexml_load_string($output);
  echo '<ul>';
  foreach($data->entry as $e){
    echo '<li><a href="' . $e->link[0]['href'] . 
         '">'.$e->title.'</a></li>';
  }
  echo '</ul>';
?>

The simplexml_load_string() function turns the XML document into a PHP object with arrays. How did I figure out to loop over data->entry and get the href via link[0]['href']? Simple. I did a print_r($output) and checked the source of the document by hitting Cmd + U in Firefox on my Mac. That showed me that this entry is an array. I then did a print_r($e) in the loop to see all the properties of every entry. If it is part of the @attributes array, then you need to use the [] notation.

That's all. The only stumbling block you will encounter is CDATA blocks and namespaces in SimpleXML. Stuart Herbert has a good introduction to these two issues in this article25.

Displaying JSON Content Link

The data format JSON26 is the low-fat alternative to XML. It is far less complex (e.g. no namespaces), and if you work in a JavaScript environment, it is native to the browser. This makes it very fast and easy to use, and for this reason it has started to become a popular data format for APIs. In essence, JSON is a JavaScript object. For example, I could write the LAMP stack example as follows:

{"lampstack":
  {
    "operatingsystem" : "Linux",
    "server" : "Apache",
    "database" : "MySQL",
    "language" : "PHP"
  }
}

You can convert this to PHP27 using the json_decode() method, and get it back as a PHP object:

<?php
  $json = '{
  "lampstack":
  {
    "operatingsystem":"Linux",
    "server":"Apache",
    "database":"MySQL",
    "language":"PHP"
    }
  }';
  print_r(json_decode($json));
?>

One API that returns JSON is the Twitter trends API28. If you load the API's URL with cURL and do a print_r() after json_decode(), you get the following back29:

<?php
  $url = 'http://search.twitter.com/trends.json';
  $ch = curl_init(); 
  curl_setopt($ch, CURLOPT_URL, $url); 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  $output = curl_exec($ch); 
  curl_close($ch);
  $data = json_decode($output);
  print_r($data);
?>
stdClass Object
(
[trends] => Array
  (
    [0] => stdClass Object
    (
      [name] => #nowplaying
      [url] => http://search.twitter.com/search?q=%23nowplaying
    )

    [1] => stdClass Object
    (
      [name] => #Didntwannatellyou
      [url] => http://search.twitter.com/search?q=%23Didntwannatellyou
    )

    [2] => stdClass Object
    (
      [name] => #HappyBirthdayGagaBR
      [url] => http://search.twitter.com/search?q=%23HappyBirthdayGagaBR
    )

    [3] => stdClass Object
    (
      [name] => Justin Bieber
      [url] => http://search.twitter.com/search?q=%22Justin+Bieber%22
    )

    [4] => stdClass Object
    (
      [name] => #FreakyFactSays
      [url] => http://search.twitter.com/search?q=%23FreakyFactSays
    )

    [5] => stdClass Object
    (
      [name] => #YouSoGangsta
      [url] => http://search.twitter.com/search?q=%23YouSoGangsta
    )

    [6] => stdClass Object
    (
      [name] => I ?
      [url] => http://search.twitter.com/search?q=%22I+%E2%99%A5%22
    )

    [7] => stdClass Object
    (
      [name] => #MeMyselfandTime
      [url] => http://search.twitter.com/search?q=%23MeMyselfandTime
    )

    [8] => stdClass Object
    (
      [name] => #2010yearofJonas
      [url] => http://search.twitter.com/search?q=%232010yearofJonas
    )

    [9] => stdClass Object
    (
      [name] => Easter
      [url] => http://search.twitter.com/search?q=Easter
    )
  )
  [as_of] => Sun, 28 Mar 2010 19:31:30 +0000
)

You can then use a simple loop to render the current trends as an unordered list30:

<?php
  $url = 'http://search.twitter.com/trends.json';
  $ch = curl_init(); 
  curl_setopt($ch, CURLOPT_URL, $url); 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  $output = curl_exec($ch); 
  curl_close($ch);
  $data = json_decode($output);
  echo '<h2>Twitter trending topics ('.$data->as_of.')</h2>';
  echo '<ul>';
  foreach ($data->trends as $t){
    echo '<li><a href="'.$t->url.'">'.$t->name.'</a></li>';
  }
  echo '</ul>';
?>

Putting It All Together Link

Let's do a quick example using all of the things we've learned so far: a simple search interface for the Web.

Using Yahoo's YQL31, it is pretty easy to do a Web search for "cat" with the command select * from search.web where query="cat" sent to the YQL endpoint. You can define JSON as the return format, and the rest means you simply enhance the earlier form example32:

<?php
  $search_html = filter_input(INPUT_GET, 's', FILTER_SANITIZE_SPECIAL_CHARS);
  $search_url = filter_input(INPUT_GET, 's', FILTER_SANITIZE_ENCODED);
?>
<form action="index.php" method="get">
  <div>
    <label for="search">Search:</label>
    <input type="text" name="s" id="search" 
           value="<?php echo $search_html;?>">
   <input type="hidden" name="demo" value="17">
   <input type="submit" value="Make it so">
  </div>
</form>
<?php
if(isset($_GET['s'])){
  echo '<h2>You searched for '.$search_html.'</h2>';
  $yql = 'select * from search.web where query="'.$search_url.'"';
  $url = 'http://query.yahooapis.com/v1/public/yql?q='.
          urlencode($yql).'&format=json&diagnostics=false';
  $ch = curl_init(); 
  curl_setopt($ch, CURLOPT_URL, $url); 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  $output = curl_exec($ch); 
  curl_close($ch);
  $data = json_decode($output);
  echo '<ul>';
  foreach ($data->query->results->result as $r){
    echo '<li><h3><a href="'.$r->clickurl.'">'.$r->title.'</a></h3>'.
         '<p>'.$r->abstract.' <span>('.$r->dispurl.')</span></p></li>';
  }
  echo '</ul>';

  echo '<p><a href="index.php?search='.$search_url.'&demo=17">Search again.</a></p>';
}
?>

Interaction With JavaScript Link

One thing people keep asking about is how to send information from PHP to JavaScript and back. This can be done in a few ways.

  • To send information from JavaScript to PHP, you need to either alter the href of a link or populate a hidden form field. The other solution of course is to use AJAX.
  • To send information from PHP to JavaScript, simply render a script element and write out the PHP information with an echo statement.
  • Using PHP's header() function and json_encode(), you can send data back to the browser as JavaScript, which allows us to use it as a src attribute of a script node.

For example, to get Smashing Magazine's RSS feed as a JavaScript object, you could do the following33:

<?php
  header('Content-type: text/javascript');
  $url = 'http://rss1.smashingmagazine.com/feed/';
  $ch = curl_init(); 
  curl_setopt($ch, CURLOPT_URL, $url); 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  $output = curl_exec($ch); 
  curl_close($ch);
  $data = simplexml_load_string($output);
  $data = json_encode($data);
  echo 'var smashingrss='.$data;
?>

You could then use this in a JavaScript block:

<script src="http://icant.co.uk/articles/phpforhacks/index.php?demo=18"></script>
<script>alert(smashingrss.title);</script>

Using header() and json_encode(), you could do any complex conversion and filtering in PHP and re-use it in JavaScript.

Summary Link

I hope this gives you an idea of what PHP is and how you can use it to access Web services and to build your own APIs to re-use in JavaScript. Using PHP for the Web boils down to a few tricks:

  • Use cURL to load data from Web resources;
  • Convert information with simplexml_load_string() and json_decode();
  • Check the structure of returned information with print_r();
  • Loop over information with foreach();
  • Use the $_GET[] and $_POST[] arrays to re-use form data and URL parameters;
  • Filter information from the user and from URLs using the built-in PHP filtering methods.

A lot of documentation is out there, and your best bet is to go directly to the PHP home page34 to read or download the documentation. Check out the user comments in particular, because that is where the real gems and examples of implementation appear.

(al)

Footnotes Link

  1. 1 http://php.net
  2. 2 http://www.mamp.info/en/index.html
  3. 3 http://www.apachefriends.org/en/xampp-windows.html
  4. 4 http://icant.co.uk/articles/phpforhacks/index.php
  5. 5 http://icant.co.uk/articles/phpforhacks/index.php?demo=1
  6. 6 http://icant.co.uk/articles/phpforhacks/index.php?demo=2
  7. 7 http://icant.co.uk/articles/phpforhacks/index.php?demo=3
  8. 8 http://icant.co.uk/articles/phpforhacks/index.php?demo=4
  9. 9 http://icant.co.uk/articles/phpforhacks/index.php?demo=5
  10. 10 http://icant.co.uk/articles/phpforhacks/index.php?demo=6
  11. 11 http://icant.co.uk/articles/phpforhacks/index.php?demo=7
  12. 12 http://icant.co.uk/articles/phpforhacks/index.php?demo=8
  13. 13 http://icant.co.uk/articles/phpforhacks/index.php?demo=9
  14. 14 http://icant.co.uk/articles/phpforhacks/index.php?demo=9&language=fr
  15. 15 http://icant.co.uk/articles/phpforhacks/index.php?demo=9&language=fr&font=large
  16. 16 http://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29
  17. 17 http://uk.php.net/manual/en/intro.filter.php
  18. 18 http://icant.co.uk/articles/phpforhacks/index.php?demo=10
  19. 19 http://uk2.php.net/manual/en/ref.filesystem.php
  20. 20 http://www.wait-till-i.com/2009/12/18/curl-your-view-source-of-the-web/
  21. 21 http://icant.co.uk/articles/phpforhacks/index.php?demo=11
  22. 22 http://icant.co.uk/articles/phpforhacks/index.php?demo=12&filter=true
  23. 23 http://php.net/manual/en/book.simplexml.php
  24. 24 http://icant.co.uk/articles/phpforhacks/index.php?demo=13
  25. 25 http://blog.stuartherbert.com/php/2007/01/07/using-simplexml-to-parse-rss-feeds/
  26. 26 http://json.org
  27. 27 http://icant.co.uk/articles/phpforhacks/index.php?demo=14
  28. 28 http://apiwiki.twitter.com/Twitter-Search-API-Method%3A-trends
  29. 29 http://icant.co.uk/articles/phpforhacks/index.php?demo=15
  30. 30 http://icant.co.uk/articles/phpforhacks/index.php?demo=16
  31. 31 http://developer.yahoo.com/yql/
  32. 32 http://icant.co.uk/articles/phpforhacks/index.php?demo=17
  33. 33 http://icant.co.uk/articles/phpforhacks/index.php?demo=18
  34. 34 http://php.net

↑ Back to top Tweet itShare on Facebook

An international Developer Evangelist working for Mozilla in the lovely town of London, England.

Advertisement
  1. 1

    Programming and SM? Isn`t this basic stuff already learned at school?

    -10
  2. 2

    I’m sorry but this is not the right way to guide someone to start learning php. It’s good to show himher some of it’s potential benefits but it’s worthless as a guide to start learning a scripting language. One should first start by learning the concepts of any language (variables, arrays, data types, classes, objects, etc…) then he could start learning more about the libraries and other facilities (cURL, GD, HTML_Template, PEAR packages etc…).

    This is probably why we find so many vulnerable websites! People read one article, they think they know it all and they engage in creating messy and unprotected websites.

    If you want to learn php, go to php.net and download the manual, then do your own local server configuration (Apache for example) instead of using WAMP or XAMP or MAMP or whatever, and learn how to configure a database, MySQL or LiteSQL etc… This is the only and correct way to learn.

    -1
  3. 3

    Rarely in life is there only one way to accomplish something, and this is doubly true when it comes to the learning process. No two people learn the same way. If they did, we’d be a pretty homogeneous species. I, for one, could never learn a programming language from reading a manual. If that works for you, that’s great, and I hope it makes you a stronger programmer than me in the end.

    I know many people are like me, in that they need to be able to see how something ties into the big picture before they can begin to learn the details. PHP is an easy language to pick up this way, and I’m grateful for Smashing Magazine giving an introdution to the language is such a manner.

    3
  4. 4

    Equally blank as mentioning that you work for Yahoo in every comment you make. As if that means you have the moral right to decide on what is right or wrong. The analogy with jQuery is ridiculous, all I was saying is that mixing markup in PHP is fine for a simple example, but quickly becomes an unmaintainable mess. Smarty could be an answer, native PHP with a controller up front can be an answer too. Either way, I would not have this opinion if I would not have seen the actual mess in the last 10 years or so at various companies. But hey, what do I know. I don’t work for Yahoo.

    1
  5. 5

    ColdFusion has always been my preferred language. To each his own, we had a guy who came in and knew only PHP, but we converted him over to CF, and though he still loves PHP (hard to get programmers to change their first ‘love’, he really likes how ‘to the task’ CF is, and how little code it takes to do things.

    1
  6. 6

    Looks like someting is broken with the article…

    0
  7. 7

    Great post for people who already use other languages like asp or asp.net and want to explore php. Kudos!!

    1
  8. 8

    Great article, and awesome reference point to those friends of mine who poke me once in a while on how to get started. I am glad SM is also including these sorts of articles. Web design is going beyond just static html, and I believe it’s important that designers understand how the dynamic flexible pages work, and aren’t just converting psd into html pages and leaving the complexity to the developers.

    1
  9. 9

    For those who are going to say bad comments, Smashing magazine is mainly a design community, but somewhere in the world, there is a designer who wants to learn how to code. I don’t see a programming article that negative, instead it helps to clear some scratches that a programmer could have.

    Thanks Christian

    2
  10. 10

    thanks for sharing this. i’ve been trying to learn a little php. will give this a try.

    0
  11. 11

    Don’t check the existence of an array using sizeof(), use is_array().

    And since is_array() is slow if it’s not an array, the fastest benchmarks say to use this:

    if(isset($array) AND is_array($array)) { /* do something */ }}

    0
  12. 12

    Nice article!

    0
  13. 13

    Too basic. If you don’t use a php framework you can’t be competitive.

    -4
  14. 14

    Nice article on PHP :)

    -1
  15. 15

    Bassem is right, you should not mix the basics of php with stuff like json, curl etc. Instead you could give some examples of basic interactions with databases and working with forms. Also, at the end of the article i expected to see a refference to w3schools and/or articles about the way pages should be coded.

    Anyone who will run through this “tutorial” and create a webpage afterwards will think, that he is a programmer, despite the fact that everything you shown here is wrong :)

    p.s. codeigniter FTW !

    1
  16. 16

    this is helpful

    0
  17. 17

    Average 2.26? That’s ridiculous. If you downvoted it because it’s not the sort of thing that interests you, then maybe just don’t bother.

    Chris, it was a very well written article and I hope to see more of your writing on SM!

    0
  18. 18

    Ha! maybe you can’t.

    You can be competitive if you don’t rely on only using frameworks to get stuff done, and instead actually learn the ins and outs of your language of choice.

    don’t get me wrong i love frameworks, but with a mind set like that, you will never be competitive only handicapped. What happens when your framework doesn’t have something you need?

    knowing the basics along with the more complex would allow you to compensate for any incompleteness in any particular framework. Learn PHP, then learn a PHP framework.

    3
  19. 19

    Maybe its basic for you, not for me, and probably a lot of other people. I’ve learned some HTML in some simple ICT classes at school. I learned more through the web, and now know HTML & CSS, but I’ve never started PHP, so this is a great article to begin with. And why is such an article wrong for Smashing Magazine?
    I think its great, it only shows that its good as it gets good reactions, and sure, there will be people like you who already know this stuff. But does that matter? No. It wasn’t intended for you, but for beginning PHP-coders. Don’t immediately think something is bad, if its not handy for you.

    Great article, thanks!

    9
  20. 20

    That’s absurd, like saying you can’t use vanilla JavaScript because jQuery exists. Sure, jQuery makes it easier, but knowing how it works beneath the scenes allows you to leverage its power. Frameworks are an accessory, not a means to an end.

    0
  21. 21

    Kevin Chapelier

    April 15, 2010 8:14 am

    Explaining how to access remote webservices to beginners without telling them anything about how to cache the webservices’ output is irresponsible.

    0
  22. 22

    great article, helped me a lot.
    keep on the great work

    0
  23. 23

    exactly what ive searched for
    thanks

    0
  24. 24

    As a self taught programmer, I appreciate the occasional code based post. I’m currently studying PHP to create a more dynamic web experience and this helps expand what I’m learning and guide me in what I need to read more into… especially XSS. Thanks a bunch.

    0
  25. 25

    I’m a self-taught programmer and designer. I started out on ASP and have forced myself to transfer over to PHP. I think this is a great article and is very relevant. I would recommend it to anyone I know who is learning PHP. My only critique would be that some of the code could have used some better explanations as to what is going on. (the curl functions for example) This is not that big of a deal as someone who is self-taught I am used to using the web to learn. Hope to see more articles on PHP!!!

    0
  26. 26

    for Russian-speaking developers, there is a perfect tool for local webserver denwer. it does everything by itself. I forgot what is editing vhost, and other config files on any changes. denwer does it by itself….

    0
  27. 27

    I’m afraid you’re mistaken, Schwarzenegger’s performance on batman & robin was oscar worthy

    0
  28. 28

    I certainly didn’t learn PHP in school.

    0
  29. 29

    It is very nice for those are very beginners

    0
  30. 30

    Plus you’ll save loads of time by combining plain old JavaScript with parts of the jQuery framework. I see people ask questions all the time that look something like “How do I do in jQuery?”, and the solution to their problem is basic JavaScript. The same goes with PHP and cakePHP, zend, Symfony, Codeignitor, or whichever your framework of choice is. It doesn’t make sense to try and learn how to use a framework without knowing what the framework is based upon.

    0
  31. 31

    That’s just ridiculous. It’s a myth that people really just read something and then convince themselves they’re an expert.

    1
  32. 32

    I agree. I use frameworks and then build my own PHP functions on top of that.

    0
  33. 33

    Good article, and I’d love to see more web programming based articles. I just can’t seem to find a good blog for web programming, so it’d be cool to see some more here. :-p.

    0
  34. 34

    Good introductionary article. I just wanted to point out that in real life / professional development most people hardly ever use “echo” to output variables. A particular bad practice is to include actual HTML in the echo string. The reason is that things then get messy and it will be really hard to seperate content from code, especially if you work with designers.

    Instead, most of the time a template engine like Smarty is used. A lighter alternative is to use the inline syntax. Sorry, this comment form wont let me post that syntax. Again, you do not include actual HTML in those brackets, only PHP.

    I can imagine that this goes too far for a beginner’s article, but I think it is important to avoid bad practices from the start.

    0
  35. 35

    So is telling people to cache by making writable files which you sadly see a lot out there. Write a post, we can link it here :)

    0
  36. 36

    Telling people in the first article how to connect to a database is probably the main cause for the SQL injection vulnerabilities we have on the web. See, I can do blanket statements, too :)

    And if you go to w3schools to learn PHP then I weep for the quality of your code. The PHP docs themselves are the main source of truth, w3schools is great for quick lookups but fails to mention any shortcomings or implementation details.

    0
  37. 37

    What’s the macosx editor in the screenshots? Thanks :)

    0
  38. 38

    I totally agree with you, but… If you for example read my JavaScript book you see that I exactly followed that process. The most sold JavaScript book at that time however was Dom Scripting which doesn’t follow this approach but instead concentrates on implementations. People learn differently and the idea of this was to show people quickly how to get data of the web and display it – not to learn PHP. If you read the second parapgraph this should be obvious.

    You can only teach people things when you have a foot in the door. Waving a massive manual around deters people, no matter how right we are…

    2
  39. 39

    I work for Yahoo, we don’t use frameworks for PHP (well, now we started using Symfony) – again, this is *not* about building PHP solutions of fully fledged CMS – this is about using web services.

    1
  40. 40

    Superb work. From the very beginning to use of web services and AJAX. Will use it as a quick reference. There s no need to dive too deep in PHP if you don’t want to. A versatile coder can just pick what they need for a particular scenario and this is a great example of it.
    Looking forward to see more articles like this, I addition to those which inspire, these help bringing life to a site.

    0
  41. 41

    Again, blanket statements. I work for Yahoo and we use echo in our templates all the time. Granted, we echo strings that went through a localisation engine. This is like writing a JavaScript article and people claiming that if you want to be professional you need to use jQuery – horses for courses.

    0
  42. 42

    TextMate – the one and only.

    0
  43. 43

    Sounds like some people are upset by anyone having an easier start than they did. Don’t worry, not too many people will read this and be as masterful as you in a day or two.

    1
  44. 44

    I don’t learn PHP at school. We don’t even learn HTML. Shit school.

    0
  45. 45

    I’m sure this would have been a great article if I was already a javascript coder. Right now I’m a designer who has just begun the road toward learning development. I was only able to follow you somewhat because of my limited experience with QBasic from, like, 15 years ago.

    I see what you were going for: an intro to php for those who already get coding but just haven’t worked in php. I think you met that goal just fine. But since there are probably a lot of designers out there who need to learn coding from square 1, it would be nice to see an article like that some time as well.

    0
  46. 46

    Great article. Thank you for the info. Haters gonna hate.

    0
  47. 47

    The mistake here is “MY practices == good practices”.

    Smarty and other template engines serve a perfectly decent purpose. So, however, does PHP, which does a pretty good job of being a template engine in it’s own right by being embeddable within HTML.

    And there’s a clear difference between what you’re talking about, echoing markup with variables, and, as a rough example:

    <a href="<?php echo $link->href; ?>"><?php echo $link->text; ?></a>

    Where you’re just using PHP as the template engine, filling in the gaps in the markup, no echoing any markup. And it’s markup which could be edited by a designer very quickly trained not to fiddle with the bits between the <?php ?>. And it avoids adding another layer of abstraction of a 3rd party template engine.

    But then it all comes down to how YOU develop fastest, and what level of performance is important to you.

    0
  48. 48

    The article seems OK…. but it seems to go from nice and basic to pretty advanced real quick. It’s much better than a lot of articles I have seen out there though.

    Either way, it’s probably a good idea to get familiar with some of the basic fundamentals of programming before just reading an article and starting to run code on any server that is accessible outside of your own network. (and MAMPP/XAMPP (or any default W/M/LAMP configuration) probably shouldn’t be accessed by the public either)

    Thanks for providing what will probably be a good building block to get people who might be interested going down the right path.

    0
  49. 49

    Good to see more programming articles on SM :)

    0
  50. 50

    Good presentation of PHP…

    But who’s the coder that mix PHP, Js and HTML ?
    Embedding both php (or any other language) with HTML is like to mix all the menu at the restauran : it could be the same, but it could be risky….

    A refresh about templates could be a good thing …

    0

↑ Back to top