Jump to content

Recommended Posts

Hi all,

I hope you can help. I am trying to write php code so that a different image is displayed in my site header depending on the date. All year round is one image, but at Christmas a festive version is shown instead. Here is my code;

<?php 
    // Normal (6 Jan - 31 Nov)
    if ((date('m') == 06) && (date('d') >= 01) || (date('m') == 11) && (date('d') <= 31)) {
    echo "<img src="image/site/site-header.png">;
    }    
    // Christmas (1 Dec-5 Jan)    
    else if ((date('m') == 12) && (date('d') == 01)) || (date('m') == 01) && (date('d') <= 05)) {
    echo "<img src="image/site/site-header-christmas.png">;
    }
?>

However, I am getting this error message; Parse error: syntax error, unexpected 'image' (T_STRING), expecting ';' or ',' in /homepages/29/d1007800584/htdocs/page/site-header-test.php on line 4

Sorry, I am very much a beginner so please forgive my ignorance / stupidity - what am I doing wrong here?

the syntax error(s) are due to missing quotes on the end of each string and reusing the same type of quote inside the strings.

you are building and echoing literal strings. the initial and final quotes on each string must be the same type and be a matching pair. you are missing the final quote on each string. the > at the end are part the <img ... > tag and belong inside the string, e.g. echo "<img ...>";. any quotes that are within a string must either be the 'opposite' type, single vs double, or they must be escaped so that they don't match the initial quote, which terminates the string. the initial and final quotes around the src="..." attribute should either be changed to single-quotes or escaped with \ characters. i prefer less typing, so i would use single-quotes.

next, your conditional logic only needs - if( normal case){ echo normal output } else { echo special output }.

lastly, your conditional comparisons need some help. you need to test if the 'm' and 'd' part of the date is greater than or equal a lower value AND less then or equal to a higher value. also, for testing purposes, you need to be able to manually set the value being tested, so this value should be built in a variable, which will be a string, e.g. '0106' for jan 6th. as long as the fields making up a string are the same width, and from left to right, most significant to least significant, you can directly compare strings, e.g. if('0106' <= $some_variable ... i'll let you cogitate on how to create and test the conditional logic needed.

16 hours ago, Ocean_Voyager said:

if ((date('m') == 06) && (date('d') >= 01) || (date('m') == 11) && (date('d') <= 31))

Just a word of warning - get out of the habit of prefixing numeric values with leading zeroes. 

That tells PHP that the value is Octal, not Decimal.  Try running any PHP code using the "numbers" 08 or 09

 

https://www.php.net/manual/en/language.types.integer.php
"To use octal notation, precede the number with a 0 (zero). As of PHP 8.1.0, octal notation can also be preceded with 0o or 0O."

Regards, 
   Phill W. 

 

The first thing I would note about what you have is that it should only have a single condition, because you only have one holiday.  If the holiday period is not matched, you will want your default header.

These are the types of tasks that you should start to see as better supported with a function.

It's also a best practice not to mix your logic with markup.  In other words, just have a function that returns one thing, which in your case would be the path to the correct header image.

Ideally you should put this type of code into a Function.  Here's an example of what you could do:

 

<?php
function getSiteHeaderImgFromDate($timeStamp=null) {
    
    // Get month and day from today
    [$m, $d] = explode('-', date('n-j', $timeStamp));

    // Check for Christmas Holiday Range
    if ($m == 12 || ($m == 1 && $d <= 5)) {
        return 'image/site/site-header-christmas.png';
    } else {
        return 'image/site/site-header.png';
    }
}

 

Ideally, you would have a small library file of these functions, that you would require_once() at the top of your Scripts.  

One thing you might notice is that the function requires a $timeStamp parameter.  This was done in order to make a function like this testable.  If you call the PHP function date() without a timestamp parameter, it will always return the current date, making it impossible to test your condition section.  You won't really know if the conditions work without modifying the function source while testing.  Another alternative would be to create a unit test for this function that "mocks" the php built-in data() function, but that is a entire subject in itself I'm not going to get into right now.  I'll just leave it, that there are libraries you can use like Mockery that can be useful with a problem like this.

So for your code, I designed this to be testable by passing a unix timestamp which is what the date() function actually requires.  If you don't pass it, it just defaults to the current timestamp.

So this allows you to simulate other dates using the php mktime() function.  Here are some tests of the function to validate it works.

echo getSiteHeaderImgFromDate(mktime(0, 0, 0, 12, 1, 2000)) . PHP_EOL;
echo getSiteHeaderImgFromDate(mktime(0, 0, 0, 1, 5, 2000)) . PHP_EOL;

echo getSiteHeaderImgFromDate(mktime(0, 0, 0, 1, 6, 2000)) . PHP_EOL;
echo getSiteHeaderImgFromDate() . PHP_EOL;

 

The results are:  

image/site/site-header-christmas.png
image/site/site-header-christmas.png
image/site/site-header.png
image/site/site-header.png

 

So how SHOULD you use this function?

Again, Ideally you have the function in a PHP script (along with any other useful functions you might write.  One idea would be to call this script something like "site_helpers.php".   For this example I'll assume you are doing this in an index.php script....

 

<?php require_once('site_helpers.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
	<header>
		<img class="header__img" src="<?= getSiteHeaderImgFromDate(); ?>">
	</header>
</body>
</html>

 

So hopefully, this illustrates some ideas for you:

  • Using Functions
  • Designing a function to be testable
  • Collecting functions into scripts allowing re-use across different pages.
  • Separating your Markup from PHP code.
  • Using PHP alternative syntax/tags.  You should also use it for intermingling control structures in your HTML markup, when that is needed.  See https://www.php.net/manual/en/control-structures.alternative-syntax.php

 

 

 

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.