PHP String Concatenate issue - php

Output of below PHP string is not correct. It's displaying additional ( "> ) at end. Please help that what wrong I am doing?
$part2 = HTMLentities('<input type="hidden" name="custom" value="<?php print($_SESSION["muser"]."-".$_SESSION["mpass"]);?>">');
print $part2;
Thanks, KRA

If you're already in PHP mode, you should just use string concatenation instead of <?php ?> syntax; this example splits up the html creation and the escaping part.
$html = '<input type="hidden" name="custom" value="' . htmlspecialchars($_SESSION["muser"] . "-" . $_SESSION["mpass"]) . '">';
$part2 = htmlentities($html);
print $part2;

It is because there is an additional > at the end.
Try this:
$part2 = HTMLentities('<input type="hidden" name="custom" value="<?php print($_SESSION["muser"]."-".$_SESSION["mpass"]);?>"');
print $part2;

I think this is more of what you're looking for:
$part = '<input type="hidden" name="custom" value="' . htmlentities($_SESSION['user'] . '-' . $_SESSION['mpass']) . '" />';
You've got a lot of poor PHP syntax in your example.
We use <?php tags to escape out of HTML into PHP. When you have a PHP file, one way you could think about it is that you really have an HTML document - but one that you can add <?php tags to write PHP code in. In you're example you are trying to print HTML from within PHP, which can get admittedly complex. You are already in a PHP block, so you don't need to use the opening <?php tag.
When concatenating strings to store in a variable, you don't need to use the print function. The print function is used to write text to the screen. You can just use the variables name as in the example I wrote to combine the strings.
htmlentities is used to render any HTML in your string into text. We use htmlentities to keep unknown (user-entered) data from modifying our HTML. It would be a good idea to use htmlentities on the $_SESSION variables like I did above to make sure they don't break our input tag with invalid HTML. Using it on the entire string would just print your HTML as if it were raw text.
Here's a way to write it from outside of a PHP block:
<?php
// initial PHP code
?>
<input type="hidden" name="custom" value="<?php echo htmlentities($_SESSION['user'] . '-' . $_SESSION['mpass']) ?>" />
<?php
// continue PHP code
?>

Related

Removing unwanted characters from name tag with php

I have the following code snippet:
echo "<label><input type='checkbox' class='selector' name='{$data['ColA']}'>" .preg_replace('/[^0-9]+/','', $data['ColA'])."</label>";
Here I'd like to use preg_replace in "name" tag as well. How can I make it work? I tried the same code in name tag but it doesn't work. Thanks.
The output of this code is like this:
<label>
<input type='checkbox' class='selector' name='7b'>7</label>
I need to remove "b" from 7 in name tag too.
Using functions inside of this syntax with {} is not really a good idea and may lead to some issues you can avoid in the most simple way, just terminate the string, concatenate it with your function output and the rest of the string, like so:
echo "<label><input type='checkbox' class='selector' name='" . preg_replace('/[^0-9]+/','', $data['ColA']) . "'>" . preg_replace('/[^0-9]+/','', $data['ColA'])."</label>";
So in general:
echo "Something: " . a_function($variable) . ", the rest of the string.";
Edit: and one thing I'd forget about, depending on what your data is, you may want to use htmlspecialchars function on in before inserting it anywhere into your HTML DOM, if it's user-provided data, in order to avoid XSS attack.

php echo href from mysql issue

Ok, so I have the php echo working and pulling specific url's from the mysql database but this string that I got from an example is adding in single quotes to my href. So instead of being localhost/newdesign/about.php it is localhost/newdesign/'about.php'.
here is the code:
<p>
<?php
echo '' . $row['url'] . '';
?>
</p>
Thank You
It would be simpler if you use <?php echo only around the variables, not the literal HTML parts as well. It also looks like part of the onclick got lost when you were copying to SO.
<p><?php echo $row['url'] ?></p>
No need for the 2nd apostrophe.
"' . $row['url'] . '"

MISGUIDED - htmlentities does not work

UPDATE
(I could just delete this question - but I might as well leave it as a reminder to everyone that sometimes the error is somewhere else than where we look...)
I am very sorry that I made you ponder this question: the reason for the "Actual result" was in a completely different location and has nothing to do with htmlentities.
Thanks to everyone who tried to help.
Why is this code not working in my PHP 5.4.32 site?
Code:
$returnValue = htmlentities(urldecode('//echo \'<textarea name="comments" id="comments">$theData</textarea>\';'), ENT_QUOTES, 'UTF-8');
echo '<textarea>' . $returnValue . '</textarea>';
Expected result:
A textarea with the exact string
//echo '<textarea name="comments" id="comments">$theData</textarea>';
Actual result:
A textarea with the exact string
//echo '<textarea name="comments" id="comments">$theData
(the "" in the original string actually closes the html textarea.)
In the same way, scripts can be injected (which is the reason why I originally used the htmlentities).
The very strange thing:
If I simply add the above example code to the beginning of my php file, it works as expected. So there must be some reason why it does not work further down the page. And I have no clue, see no possible reason in the code.
What's wrong?
btw: using htmlspecialchars doesn't change the effect.
Dollar sign $ isn't interpreted in single quotes.
Choose and use one of these:
echo '<textarea name="comments" id="comments">' . $theData . '</textarea>';
echo "<textarea name='comments' id='comments'>$theData</textarea>";
echo "<textarea name='comments' id='comments'>" . $theData . "</textarea>";
echo "<textarea name=\"comments\" id=\"comments\">$theData</textarea>";
You shouldn't use urldecode() in this case. urldecode() will give you the original value of an url-encoded string (in PHP the return value of urlencode()). You're not working with url-encoded strings here.
The following should give you the expected result:
$returnValue = htmlentities('//echo \'<textarea name="comments" id="comments">$theData</textarea>\';', ENT_QUOTES, 'UTF-8');
echo '<textarea>' . $returnValue . '</textarea>';
There is nothing wrong with this code. Works perfectly - the error was somewhere else in my php file...

How should I echo a PHP string variable that contains special characters?

I'm trying to populate a form with some data that contains special characters (e.g. single quote, double quote,<,>,?,","".~,,!##$%^&*()_+}{":?<<>,./;'[.] etc) :
<input type="text" name="message" size="200" maxlength="200"
value =<?php echo $message;?>>
However, $message, which comes from a MySQL table, isn't displayed correctly - any HTML output that should be in $message is broken.
How do I do this properly?
This will prevent your tags from being broken by the echo:
<?php echo htmlentities($message); ?>
If you want to display it
echo htmlspecialchars($messge, ENT_QUOTES, 'UTF-8');
That's what I usually do.
Since the answers are difference:
htmlentities-vs-htmlspecialchars is worth checking out.
I normally use the following code, see htmlspecialchars
<?php echo htmlspecialchars($videoId, ENT_QUOTES | ENT_HTML5); ?>
whats wrong with using a constant ?
<?php
define(foo,'<,>,?,","".~,,!##$%^&*()_+}{":?<<>,./;');
$foo2="'[.]";
echo constant('foo').$foo2;
?>
you need to put the '[.]' into a variable, as a constant will break on a ' (single quote).

Adding A Dynamic Link In 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.

Categories