简体   繁体   中英

Check if PDF file with matching name exists, link to it

I am working on a real estate website. We are drawing in real estate listings using MLS numbers and some of these listings have PDF brochures. I would like to check if a brochure exists for a listing - the PDF file is "mls#.pdf", with the MLS # matching the listing. If there is a PDF, I want to link to that. Otherwise the link should go to the MLS page for that listing.

I have tried this code below, but I don't know how to set it to search for/link to the filename that matches the listing. (The second echo is clearly wrong too, I don't know how to go back and forth from php in that way).

<?php
$inc_file = "pdf/$MLS_ACCT.pdf";
if (file_exists($inc_file)) {
echo '<a href="pdf/$MLS_ACCT.pdf">Click here for Brochure - Open PDF at 100%</a>';}
else {
echo '<a href="property-search-results.php?MLS_ACCT=<?php echo $MLS_ACCT ;?>" target="_top">Further Details >></a>'; }
?>

Your code that checks whether the file exists looks good. Here's a rundown of how PHP parses variables in strings:

There are several ways to use variables in strings:

$name = "Jeff";

// parsing in double quotes
$string = "My name is $name";

// you can also use curly braces for better readability
$string = "My name is {$name}";

// or you can concatenate
$string = "My name is " . $name;

In single quotes, only the concatenation method works. You should do something like this:

echo '<a href="pdf/' . $MLS_ACCT . '.pdf">Click here for Brochure - Open PDF at 100%</a>';

and you should have the variable printing correctly.

Finally, in your last echo statement, you have <?php ?> in your string. That will print literally - you only use those when you're switching to PHP from pure HTML. Instead, use the same string concatenation method described above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM