Tiffany
Tiffany

Reputation: 237

Concatenating HTML and PHP to make an image link

I'm trying to make an image into a link using PHP and HTML. The main idea is to grab user's images and screen names from Twitter, then make the image into a clickable link to their profile by building the URL and adding their screen name on the end. But I get a error message:

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';' in C:\wamp\www\fyp\tweeter3.php on line 71.

This is line 71 (it's part of a foreach loop):

<?php echo "<a href = ".$url"><img src = ".$userImage." class = ".$class."></a>"; ?>

There's a syntax error in there I just can't pinpoint. These are my variables:

$userScreenName = $user -> screen_name;
$userImage = $user -> profile_image_url;
$class = "myImgClass";
$url = "https://twitter.com/".$userScreenName;

Can you spot the error?

Upvotes: 2

Views: 26866

Answers (6)

Om Dhoju
Om Dhoju

Reputation: 1

It is not a good practise to concatenate html string with the php variables. This leads to possible injection vector (XSS). To avoid possible XSS (DOM OR STORED) please filter the variables as string. Specially if the value is from user input. eg.

<?php echo "<a href = '".filter_var($url, FILTER_SANITIZE_STRING)."'

Upvotes: 0

Jocelyn
Jocelyn

Reputation: 11393

In my opinion, the simplest and most readable way to do is:

<?php echo "<a href = '$url'><img src = '$userImage' class = '$class'></a>"; ?>

There is only one long text, and no concatenation is used. It reduces the possibility to have an error caused by a missing double quote or missing dot. All PHP variables will be replaced automatically by their values.

You could also use printf to have all the variables outside of the string:

<?php printf('<a href = "%s"><img src = "%s" class = "%s"></a>', $url, $userImage, $class); ?>

Upvotes: 1

Jean
Jean

Reputation: 7673

You are missing a dot after $url and the HTML quotes to generate valid code:

<?php echo "<a href = '".$url."'><img src = '".$userImage."' class = '".$class."'></a>"; ?>

Without the quotes you get:

<a href = the url><img src = user image class = the class></a>

With the quotes:

 <a href = 'the url'><img src = 'user image' class = 'the class'></a>

Upvotes: 5

blamonet
blamonet

Reputation: 660

Try this instead:

<?php 
echo "<a href = \"".$url."\"><img src = \"".$userImage."\" class = \"".$class."\"></a>";
?>

Upvotes: 2

insertusernamehere
insertusernamehere

Reputation: 51

after $url you need to have a period.

Upvotes: 2

RichieHindle
RichieHindle

Reputation: 281505

Missing . after $url:

<?php echo "<a href = ".$url"><img...

Upvotes: 4

Related Questions