March 27, 2012

Adding A Dynamic Link In Php

Question by Iain Simpson

I have been using the following to add a dynamic link on a page I am writing, it works ok and appears how it should on the page but I cant help but think that I am going a bit backwards with the way its written as it looks messy. What is the correct way to write it, as if I put it all in one line it doesn’t work ?..

echo '<a href="./customer-files/';
        echo $customerID;
        echo '/';
        echo $filename->getFilename();
        echo '">';
              echo $filename->getFilename();
    echo '</a>';

Answer by Quentin

I’d approach it like this:

$safe_customer_id = htmlspecialchars(urlencode($customerID));
$safe_filename = htmlspecialchars(urlencode($filename->getFilename()));
$safe_label = htmlspecialchars($filename->getFilename());
echo "<a href="./customer-files/$safe_customer_id/$safe_filename">$safe_label</a>";

Answer by Starx

Concatenation is your friend. Use a . to combine multiple string expression into one.

echo '<a href="./customer-files/'.$customerID.'/'.$filename->getFilename().'">'.$filename->getFilename()/'</a>';

Even better way would be

$filename = $filename -> getFilename(); //cache the filename
echo "<a href='/$customerId/$filename'>$filename</a>";
  // ^ On this echo NOTICE that variables can be DIRECTLY placed inside Double qoutes.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!