Adding A Dynamic Link In Php - php

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>';

Try with
echo "{$filename->getFilename()}";
Here there is the documentation with a lot of examples of how to concatenate output.

I'd approach it like this:
$safe_customer_id = htmlspecialchars(urlencode($customerID));
$safe_filename = htmlspecialchars(urlencode($filename->getFilename()));
$safe_label = htmlspecialchars($filename->getFilename());
echo "$safe_label";

I would go with this:
$fn = $filename->getFilename();
$link = $customerID . '/' . $fn;
echo ''.$fn.'';

If you're using a template layer, it is even better to break out into PHP only when you need to:
<a href="./customer-files/<?php
echo $customerID . '/' . $filename->getFilename()
?>">
<?php echo $filename->getFilename() ?>
</a>
This way, your IDE will correctly highlight your HTML as well as your PHP. I've also ensured that all PHP is in single-line blobs, which is the best approach for templates (lengthy statements should be banished to a controller/script).

Concatenation is your friend. Use a . to combine multiple string expression into one.
echo ''.$filename->getFilename()/'';
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.

Related

PHP script inside of string?

Is this possible?
What I am trying to accomplish:
Create a html template in the form of a string
Inside the string, add a script, something like include 'php/countries.php';
Echo entire string to html page
Everything but the 2nd step works. I would like to see a php file echo the question being asked, onto the html page, including an echo from another php file.
EXAMPLE
echo "<div id=\"first\"><?php include \'countries.php\'; ?></div>";
I have tried the above, as well as the below:
EXAMPLE
echo "<div id=\"first\">".include 'countries.php'."</div>";
Would this require eval?
Any and all help is appreciated.
Seems a bit silly, but you could do the following:
echo "<div id=\"first\">" . file_get_contents('countries.php') . "</div>";
Or...
echo "<div id=\"first\">";
include "countries.php";
echo "</div>";
Or...
$externalfile = compileexternal('countries.php');
function compileexternal($file) {
ob_start();
require $file;
return ob_get_clean();
}
echo "<div id=\"first\">" . $externalfile . "</div>";
If none of these are what you need, please update the question. There are a dozen ways.
You can use
eval()
But it is not a good practice.
You can use a regular expression.
For example, your string could be;
<div id="first">{{countries.php}}</div>
You'd then do;
$string = "<div id='first'>{{test2.php}}</div>";
echo preg_replace_callback("/(\{\{.+\}\})/", function($matches) {
include_once( str_replace(array("{", "}"), "", $matches[0]));
}, $string);
Check the file exists if( file_exists() )
Check the file can be included (we don't want to include ../../../../../etc/passwd

PHP - Echoing a variable in color

Im new to learning PHP as you might have guessed. I have the contents of a .txt file echoed but I would like it to stand out more, so I figured I would make it a different colour.
My code without colour:
<?php
$file = fopen("instructions.txt", "r") or exit("Unable to open file");
while(!feof($file))
{
echo fgets($file);
}
fclose($file);
?>
I have researched this and seen suggestions to others to use a div style, however this didn't work for me, it gave me red errors all the way down the page instead! I think its because I'm using 'fgets' not just a variable? Is there a way to colour the echo red?
The code I tried but doesn't work:
echo "<div style=\"color: red;\">fgets($file)</div>";
(In general) You need to separate the actual PHP code from the literal portions of your strings. One way is to use the string concatenation operator .. E.g.
echo "<div style=\"color: red;\">" . fgets($file) . "</div>";
String Operators
Other answer already told that you can't use a function call in a double quoted string. Let additionally mention that for formatting only tasks a <span> element is better suited than a <div> element.
Like this: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span
You should try:
<div style="color: red;"><?= fgets($file);?></div>
Note: <?= is an short hand method for <?php echo fgets($file);?>
This version does not need to escape double quotes:
echo '<div style="color:red;">' . fgets($file) . '</div>';
You can do this with the concatenate operator . as has already been mentioned but IMO it's cleaner to use sprintf like this:
echo sprintf("<div style='color: red;'>%s</div>", fgets($file));
This method comes into it's own if you have two sets of text that you want to insert a string in different places eg:
echo sprintf("<div style='color: red;'>%s</div><div style='color: blue;'>%s</div>", fgets($file), fgets($file2));

Incorporating php variable into url with href attribute

I am trying to create the necessary url from this code however it is working and I am struggling to find out why.
$linkere = $row['message'];
echo '<a href="me.php?message=<?php echo rawurlencode($linkere); ?>">'
Currently this code is producing the url: me.php?message= . But, I would like it to create the url: me.php?message=hello for example.
Thanks for helping!
You are passing $linkere to rawurlencode(). The variable is actually named $linker.
$linker = $row['message'];
echo '<a href="me.php?message=<?php echo rawurlencode($linker); ?>">'
You have alot of syntax problems here.
first, you need to use Concatenation message='.rawurlencode($linker).'"
second your variable do not exist, it should be $linker.
Second close the tag and insert the text, in this case i used Test.
$linker = $row['message'];
echo 'Test';
Can you try this,
$linker = $row['message'];
echo 'YOUR LINK TEXT HERE';
You don't need the <? ?> and echo in your echo, it should just be:
$linkere = $row['message'];
echo 'Test';
Otherwise you are turning php on and off again to echo something within an already open instance of php in which you are already echoing.

render php variable comming from database

what I want to do is want to save php variable in database (suppose {$baseUrl} ) and I am getting the data on php page with echo command and on the same page I have defined $baseUrl='/public'. I want to get the value for the base url but I'm getting simply {$baseUrl} not '/public'
in db I have <img src="{$baseUrl}/img.jpg" />
on page I have
$baseUrl = "/public";
echo $content
it is giving <img src="{$baseUrl}/img.jpg /">
how can I get <img src="/public/img.jpg" />
Of course. Strings are strings, not PHP code. You'll have to replace it yourself, e.g.:
<?php
$baseUrl = '/public';
$string = '<img src="{$baseUrl}/img.jpg" />';
$replacements = array(
'{$baseUrl}' => $baseUrl,
);
echo strtr($string, $replacements);
I think what you want to do is a string replace. The variable pointer ($baseUrl) is a string that comes from the database. If you echo it, it is still just a string. What you need to do is something like this:
<?php
echo str_replace('$baseUrl', $baseUrl, $varFromDB);
?>
Or do I understand your question wrong?
With
str_replace($content, '{$baseUrl}', $baseUrl)
.
I am guessing that you are using the wrong quotes:
echo '<img src="{$baseURL}/img.jpg" />';
rather than
echo "<img src='{$baseURL}/img.jpg'/>";
You want the $baseUrl variable to be evaluated? You have to put the variable outside of the string definition:
echo '<img src="' . $baseUrl . '/img.jpg" />';
or put it between double quotes (strings enclosed in double quotes are parsed by PHP):
echo "<img src=\"{$baseUrl}/img.jpg\" />";
Based on your comments, you need this solution:
$content = str_replace("{$baseUrl}", $baseUrl, $content);
You may want to use the eval() function...
This is not a good idea, but it would achieve what you want.

Where is the problem in this PHP code?

There is a problem in this code I can not detected
<?php echo "<a href ='$rows['Link']'> .$rows['UploadName']</a> "; ?>
Do you find you have a solution???
Thank you very much.
My guess is that your problem is that it isn't writing out the data in $rows['Link'] ... if that is the case, then your solution is to change it to {$rows['Link']} ... actually, you'll probably want to change both, since it looks like you started doing string concatenation and then switched halfway through.
So:
<?php echo "<a href ='$rows['Link']'> .$rows['UploadName']</a> "; ?>
becomes:
<?php echo "<a href ='{$rows['Link']}'>{$rows['UploadName']}</a> "; ?>
See: The PHP Manual on Variable Parsing in strings
It should be:
<?php echo "<a href ='{$rows['Link']}'>{$rows['UploadName']}</a>"; ?>
Or:
<?php echo "<a href ='{$rows['Link']}'>" . $rows['UploadName'] . "</a>"; ?>
There's a problem in parsing variables in the string. Use curl braces:
<?php echo "<a href ='{$rows['Link']}'> .{$rows['UploadName']}</a> "; ?>
Take a look to this php.net page, under "variable parsing".
More alternatives:
<?php echo '' . $rows['UploadName'] . ''; ?>
or
<?=('' . $rows['UploadName'] . '')?>
Another alternative (that I tend to prefer, given I know that both 'Link' and 'UploadName' are valid indices of $row.
<?=$rows['UploadName']?>
I'm not sure what that does for readability for most people, but on color-coded IDEs, it tends to help, because the HTML isn't just seen as one giant ugly single-colored string.

Categories