User Tools

Site Tools


en:web_development:media:php

Web Development Lesson 6 - Media

PHP Arrays

Objective

In this activity we'll use PHP to generate the list of photos in our album.

Setup

  • We'll continue using the 'media.php' and 'style.css' files from the previous activities. Here they are again if you need them.

media.php

<?php
    $page = "media";
    include("header.php");
    include("menu.php");
?>
    <main>
        <img src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg" alt="tree at sunset" title="this was the first image listed on Google when I checked">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec enim sem, efficitur et fringilla et, pretium at turpis. Nunc interdum, dolor vitae aliquam accumsan, lacus sapien varius tortor, fringilla lobortis turpis tortor et ante. In hac habitasse platea dictumst. Nullam elementum blandit tincidunt. Sed semper finibus massa, non mollis nulla mollis et. Nunc lectus metus, tempor nec dui ut, pharetra eleifend massa. Ut tempus porta metus, eget aliquet ligula tempor hendrerit. Curabitur vestibulum elit in commodo viverra. Nullam est orci, suscipit vitae tincidunt porta, lacinia sed nulla. Quisque ex eros, consectetur id metus sit amet, molestie tempor risus. In facilisis consequat eros in convallis. Nulla nec imperdiet nibh. Suspendisse consequat sit amet mi in imperdiet. Nullam eget aliquet metus. Vestibulum non fermentum eros. Cras sodales, nisl eget congue interdum, massa nulla porta lectus, quis suscipit est ipsum sit amet ante.</p>
        <p>Morbi gravida malesuada odio, sed pretium libero aliquam vitae. Suspendisse potenti. Nunc eget leo vulputate, dictum eros non, gravida lorem. In id nunc id orci ornare porttitor. Maecenas id laoreet risus. Aenean lacinia dignissim volutpat. Morbi et ligula ac purus gravida aliquet. Integer feugiat sapien ac porttitor iaculis.</p>
        <video src="http://it.bibliotecasmedellin.gov.co/bibliolabs/numeros/1.mp4" controls muted loop autoplay></video>
        <p>Phasellus pretium sit amet tellus ac tincidunt. Curabitur in ligula massa. Vivamus in urna suscipit, vehicula velit et, mollis purus. Aliquam sed risus vel urna tristique aliquam. Etiam egestas lectus arcu, quis lobortis diam luctus in. Vivamus id diam metus. Nulla bibendum dolor sit amet egestas semper. Praesent facilisis pellentesque condimentum.</p>
        <p>Mauris ac sapien justo. Curabitur a feugiat velit. Donec non mi ac turpis faucibus hendrerit. Nulla luctus est lectus, nec rhoncus nisi eleifend ac. Nullam iaculis mi eget faucibus mattis. Nullam nec cursus nisi. Donec vel nunc ac felis sodales tincidunt sed condimentum mauris.</p>
        <p>Praesent lobortis dictum purus, convallis dapibus velit malesuada non. Sed sit amet magna sagittis, maximus odio in, mattis erat. Phasellus ultricies risus turpis, vitae tempor diam finibus eu. Sed luctus augue purus, eget consectetur sapien egestas et. Sed eget tristique mauris. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum rhoncus vehicula pellentesque. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Aenean placerat arcu vitae nisi vehicula semper. Cras sit amet risus dolor.</p>
        <audio src="https://freesound.org/data/previews/611/611814_13567802-lq.mp3" controls loop></audio>
        <input type="button" value="Play Audio" onclick="playPauseAudio()">
        <div id="album">
                <img src="https://images.pexels.com/photos/674010/pexels-photo-674010.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
                <img src="https://images.ctfassets.net/hrltx12pl8hq/61DiwECVps74bWazF88Cy9/2cc9411d050b8ca50530cf97b3e51c96/Image_Cover.jpg?fit=fill&w=480&h=270" />
                <img src="https://images.ctfassets.net/hrltx12pl8hq/3MbF54EhWUhsXunc5Keueb/60774fbbff86e6bf6776f1e17a8016b4/04-nature_721703848.jpg?fit=fill&w=480&h=270" />
                <img src="https://cdn.pixabay.com/photo/2021/08/25/20/42/field-6574455__340.jpg" />
                <img src="https://www.gettyimages.es/gi-resources/images/500px/983794168.jpg" />
                <img src="https://media.istockphoto.com/photos/concept-of-an-open-magic-book-open-pages-with-water-and-land-and-picture-id1279460648?b=1&k=20&m=1279460648&s=170667a&w=0&h=uZa830sWo8hlFN0Y7FnQ14giNC0Z2EBNuTMuNJeJhQg=" />
        </div>
    </main>
<?php
    include("footer.php");
?>

style.css

ol {
    color: blue;
  }
  
  ol ol {
    font-weight: 700;
  }

ul {
  list-style-type: none;
}

td, th {
  border-width: 1px;
  border-style: solid;
}

td {
  padding: 10px;
}

table {
  border-collapse: collapse;
}

header {
  background-color:indianred;
  border:darkred solid 2px;
  height: 100px;
  position: absolute;
  left: 16%;
  right: 0px;
  top: 0px;
}

nav {
  background-color: burlywood;
  border:yellow solid 2px;
  position: fixed;
  top: 0px;
  bottom: 0px;
  width: 16%;
  left: 0px;
}

main {
  background-color: lightgree;
  border: darkgreen solid 2px;
  position: absolute;
  top: 100px;
  left: 16%;
  right: 0px;
  bottom: 80px;
  overflow: scroll;
  padding: 20px;
}

footer {
  background-color: lightskyblue;
  border: darkblue solid 2px;
  position: absolute;
  bottom: 0px;
  height: 80px;
  left: 16%;
  right: 0px;
}

.content {
  background-color:coral;
  border:orangered solid 2px;
  height: 400px;
  padding: 40px;
  margin: 20px;
  display: inline-block;
  width: 300px;
}

img {
  float: left;
  max-height: 250px;
  border: solid 2px green;
  margin: 20px 20px 20px 0px;
  padding: 10px;
  border-radius: 30px;
}

#album {
  display: flex;
  justify-content:space-between;
  flex-wrap: wrap;
}

video {
  max-height: 250px;
  float: right;
  clear: left;
  margin: 20px 0px 20px 20px;
  padding: 10px;
}

audio {
  margin: 20px 20px 20px 0px;
  padding: 10px 10px 10px 0px;
}

input[type=button] {
  display: block;
}

p {
  font-size:10px;
}
  • Since we're going to start using PHP code in 'media.php', it will help to have the colors and automatic completion working for PHP rather than for HTML.
  • Click on the word 'HTML' in the bottom right of the Visual Studio window, then change it to 'PHP'.

PHP Arrays

  • We've seen how to use arrays to create a list or table in Javascript, which runs on the user's PC.
  • In a real web application, the data will be obtained by a server and it's usually easier to generate the code on the server too.
  • Arrays operate very similarly in PHP as in Javascript except in the way they're initiated. Add the following code at the end of the first PHP block in 'media.php'.
    $photos = array("https://images.pexels.com/photos/674010/pexels-photo-674010.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
    "https://images.ctfassets.net/hrltx12pl8hq/61DiwECVps74bWazF88Cy9/2cc9411d050b8ca50530cf97b3e51c96/Image_Cover.jpg?fit=fill&w=480&h=270",
    "https://images.ctfassets.net/hrltx12pl8hq/3MbF54EhWUhsXunc5Keueb/60774fbbff86e6bf6776f1e17a8016b4/04-nature_721703848.jpg?fit=fill&w=480&h=270",
    "https://cdn.pixabay.com/photo/2021/08/25/20/42/field-6574455__340.jpg",
    "https://www.gettyimages.es/gi-resources/images/500px/983794168.jpg",
    "https://media.istockphoto.com/photos/concept-of-an-open-magic-book-open-pages-with-water-and-land-and-picture-id1279460648?b=1&k=20&m=1279460648&s=170667a&w=0&h=uZa830sWo8hlFN0Y7FnQ14giNC0Z2EBNuTMuNJeJhQg=");
  • Feel free to replace these with the links to the images you chose earlier.
  • This may look different to Javascript, but the structure is basically the same.
  • $photos is our variable which we will use to refer to the array.
  • We identify the content as an array using array().
  • Each element of the array is a link and they are separated by , .

Tool: Putty

  • Before we go any further, let's take a look at an important tool for debugging PHP - logs.
  • The logs are stored on the server, so we'll need to use another tool like Putty to access the command line. These instructions will be updated with details on how to use that, but for now you'll need to ask for help.
  • Once you've logged on to the server, enter the following text into the command line to see the most recent logs.
tail -f -n 50 /var/log/apache2/error.log
  • Use this if you don't see what you expect to see on the screen.
  • Unfortunately, since your classmates will also be generating errors that go to the same logs, you'll need to be quick to identify your own errors.
  • We can be more targeted with any logs we generate though, and we'll prefix them with your name, such as follows. Add this to your PHP code (after changing my name to yours).
  error_log('MURRAY this is a log.');
  • Refresh your page to generate the log.
  • Now, in the server command line, enter the following line.
cat /var/log/apache2/error.log | grep 'MURRAY'
  • Change my name to yours and use this to see the code you're generating.
  • Of course, it's also possible to show your text on the screen, and that works well in early development, but when you're in (or close to) a live environment, you need make sure your debug text never appears to users, so it's safer to display them in the logs.

PHP For Loop

  • Recall that in Javascript, we used a for loop to display each line of the array.
  • We can do the same in PHP.
  • First, comment out all images in the 'album' div by selecting that text and pressing Ctrl-/. Notice that in HTML, code is commented out by placing <!-- in front and --> after the code to be commented.
  • Now add the following code after the <div id="album"> tag.
<?php
    for($i = 0; $i < 6; $i++) {

    }
?>
  • This should look very familiar. The only difference to Javascript is that our PHP variable begins with '$'.
  • Now we want to check that we are looping correctly, so we'll use an error log.
  • Add the following code inside the {} of your for loop (replacing my name with yours).
        error_log('MURRAY ' . $i);
  • If you refresh your page now then check your logs (cat /var/log/apache2/error.log | grep 'MURRAY'), you should see six lines with your name, each having a number from 0 to 5 as expected.
  • Note that . is used to connect strings together.
  • Now let's modify that line to show the image link.
        error_log('MURRAY ' . $photos[$i]);
  • Refresh your page and check the logs again. You should see six lines with your name and the six different image links (or however many images you have added to your $photos array.

PHP Strings

  • Before we go any further, let's take a closer look at strings in PHP, which are very similar to strings in Javascript.
  • Let's start with some simple text. Add this just before your for loop.
    echo 'This is text.';
  • Refresh your page and see this text appears where your album should be.
  • You might already have noticed one major difference between Javascript and PHP. In Javascript, to make your text appear in the document, you need to attach it to a particular element. In PHP, your text is entered wherever it appears in the flow of HTML code. In fact, it becomes part of the HTML code.
  • Try this. Update your 'echo' code to the following.
    echo '<img src="https://images.pexels.com/photos/674010/pexels-photo-674010.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">';
  • Now we've added HTML code for an image, so if you refresh your page you will see the first photo appear.
  • Notice that use of " and ' . ' surrounds the entire string, while " surrounds only the src value. We must be very careful not to mix them up. If, for example, we have echo '<img src='https: ... '>'; then the echo command would think the string ended at src=' and throw an error at 'http' because it's not recognised as PHP code.
  • We want to change the image link to the data from our array, so we can break the code up as follows.
    echo '<img src="' . $photos[0] . '">';
  • Here we are replacing the image link with the first item in the photos array, and joining the parts of the string with . .
  • This works, but there is a cleaner way. Place the following code inside the for loop.
    echo 'This is photo number $i.';
  • When you refresh your page you should see this sentence 6 times exactly as is. That's not what we want. Let's change it a bit.
    echo "This is photo number $i.";
  • Now when you refresh your page you should see the sentence 6 times with the numbers 0 to 5, which is much better.
  • So wrapping the string in " instead of ' allowed the echo command to interpret $i as a variable and display the value instead of the exact text.
  • Let's try that with the array item.
    echo "This is the photo string $photos[$i].";
  • Refresh the page and see that we now see the string.
  • Let's change this to the HTML for our image.
    echo "<img src='$photos[$i]'>";
  • Refresh the page and you should now see your photos displayed properly.
  • We could stop here, but I want to take it one step further.
  • In your page, right click and select 'View Page Source'.
  • Notice how most of the page is readable, but the code generated by PHP (the list of images inside <div id="album"> is one long string. Let's fix that.
    echo "\t\t\t<img src='$photos[$i]'>\n";
  • Refresh your page and check the source code again. Now it's much better.
  • We've added \t which inserts a tab and \n which inserts a new line. This only works when we're using double quotes ( " ).
  • Now you're ready to practise.

Next: Named Arrays

en/web_development/media/php.txt · Last modified: 2023/08/16 09:33 (external edit)