Attempting to use variables that are stored within cell data - php

I am facing a problem that doesn't allow variables retrieved from cell data to appear as the declared variable on my web page. I will post an example below ;
email.db - Below represents the cell data for column email_body
email_body = Hi, $name
$name = $row['name'];
$messagebody = $row["email_body"];
$message = "
<html>
<body>
<p>".$messagebody."</p>
</body>
</html>
;
"
As you can see I'm attempting to make $row['name'] appear within $messagebody (which is text stored in a DB). The issue i'm having is that the above code will display $messagebody, but the $name variable will display as plain text and will ignore the variable.
Your help is appreciated,
Thanks.

Daniel - I think you might not have the exact right idea about how variables are rendered inside of PHP strings.
However, there is a function called sprintf that might be the tool to do what you're attempting to do!
sprintf (string $format [, mixed $... ])
The first $format argument in your case would be 'Hi, %s' - the %s being a stand-in for another string, $name. The function would then return 'Hi, Bobby', were $name set to bobby. (And name was passed as the second arg.)
// Re-set the data inside of `email_body` to 'Hi, %s';
// "%s" is a placeholder that hints that a string should be placed there
$name = $row['name'];
$messagebody = sprintf($row["email_body"], $name);
$message = "<html>
<body>
<p>".$messagebody."</p>
</body>
</html>";

You are attempting to evaluate PHP code in a string. That is generally unsafe. Instead of that, you can replace the placeholders (e.g. $name) with the actual values.
Example:
$messagebody = "Hi, $name!"
$compiledmessagebody = preg_replace('/\$name/', 'Daniel V.', $messagebody);
$message = "
<html>
<head><title></title><head>
<body>
<p>".$compiledmessagebody."</p>
</body>
</html>
";
EDIT: actually, it would be better to use a templating engine to do the above and much more out of the box. Pug goes nicely with PHP https://www.phug-lang.com/

I would use HEREDOC syntax:
$name = $row['name'];
$messagebody = $row['email_body'];
$message = <<<HTML
<html>
<body>
<p>$messagebody</p>
</body>
</html>
HTML;
That way you don't have to worry about breaking out of strings and multi-line strings appear much neater.
Technically, you don't need to break out of a double quoted string when using a simple variable like you were doing.
With HEREDOC syntax the last HTML; needs to be pushed all the way to the left. In this case I am using HTML as an identifier, but you can rename the identifier to something else.

Related

Create variable with multiple lines of html in php

In perl I can qq[] to put multiple lines of html into a variable as shown below.
PERL
my $rank = 1;
my $name = 'John';
sub writeMsg
{
$test = qq[
<h1>User Ranking</h1>
<p>$name is ranked number $rank</p>
<p>lots more info to go in here</p>
];
return $test;
}
print writeMsg($rank, $name);
In php I can't seem to find a way to do this?
The soloution I have below returns the same result but it is already a lot harder to read and keep the syntax right,
PHP
$rank=1;
$name = 'John';
function writeMsg($rank, $name) {
$test = '<h1>User Ranking</h1>' . $name . ' is ranked number ' . $rank ' <p>lots more info to go in here</p>';
return $test;
}
print writeMsg($rank, $name);
Is there a way to do this in php? I am familiar with doing something similar in a foreach with the below syntax but haven't been able to come up with a good way to do this for a variable?
<?php foreach ($get_tests as $test): ?>
<?php endforeach; ?>
You just need to use " instead of '
$test= "
<h1>User Ranking</h1>
<p>$name is ranked number $rank</p>
<p>lots more info to go in here</p>
";
You can use the heredoc (http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc):
<?php
$str = <<<"EOD"
<p>Example of string</p>
<b>spanning multiple lines</b>
<p>using nowdoc syntax.</p>
EOD;
echo $str;
Edit: make sure to use double quotes

how to escape html / special strings in javascript

I have a php / javascript scrip which needs to print some text. unfortunately it seems that the js breaks down if the string has special characters such '
Below is a snippet from the script. $messageContent and $subject are the strings with html tags. (actually "'" characters) .
echo '
<script language="javascript">
function SelectRedirect(){
switch(document.getElementById(\'s1\').value)
{
';
echo '
case "?vrj_name='.$vrj_name.'":
window.location="?vrj_name='.$vrj_name.'&messageContent='.$messageContent_vrj.'&from_email='.$from_email.'&email='.$email.'&subject='.$subject.'";
break;
';
}
I added a function in php to replace "'" with "\'" and it works (the js executes successfully ) but I can't get ride of them when I display them in the webpage .
The best way to do this is to encode the values using json_encode. Here is a simple example:
<?php
$name = "Jason's Bakery";
?>
<script>
var name = <?php echo json_encode($name); ?>;
DoSomethingWithName(name);
</script>
This can be used for integers, strings, and other values. Keep in mind that it will add quotes as needed, so you need to assemble and encode a "whole value at once". In your example of using the URLs, you need to use the PHP urlencode() function to encode them FIRST, and then pass it through json_encode to convert to a javascript value. And if you are placing that inside of an HTML attribute, like onclick, you need to further pass it through htmlspecialchars(..., ENT_QUOTES) and then place it in double quotes.
http://php.net/manual/en/function.json-encode.php
So for example, you need to build a URL in PHP and then use it in javascript...
<?php
$name = "Jason's \"Awesome\" Bakery";
$url = "http://site.com/page.php?name=" . urlencode($name);
?>
<script>
var name = <?php echo json_encode($name); ?>;
DoSomethingWithName(name);
</script>
<input type="button" onclick="<?php echo htmlspecialchars('window.location = ' . json_encode($url) . ';', ENT_QUOTES); ?>" value="Click Me" />
Which results in something like this:
<script>
var name = "Jason's \"Awesome\" Bakery";
DoSomethingWithName(name);
</script>
<input type="button" onclick="window.location = "http:\/\/site.com\/page.php?name=Jason%27s+%22Awesome%22+Bakery";" value="Click Me" />
Needless to say, you do not want to do without these:
http://php.net/manual/en/function.json-encode.php
http://www.php.net/manual/en/function.urlencode.php
http://www.php.net/manual/en/function.htmlspecialchars.php
Due to respects of readability and future maintainability, I'd like to point out a few things which may help you out.
First, I see you're generating HTML elements in a PHP string. This isn't inherently bad, but when your string wraps across 2 or more lines, it becomes increasingly difficult to manage. Instead, you may want to think about escaping PHP for outputting HTML portions, and re-entering PHP for logical portions. You can escape PHP and enter HTML within if statements, function declarations etc, so there's really no good reason not to. Look at the following example (this solution also escapes the strings in an appropriate manner where its value can contain single quotes, double quotes or line breaks):
<?php
function urlFriendly($input) {
return urlencode($input);
}
function jsFriendly($input, $urlFriendly = True) {
$output = htmlentities($input, ENT_QUOTES);
// Double quotes in PHP translate "\n" to a newline.
// Single quotes in PHP keep the literal value.
$output = str_replace("\r\n", '\n', $output); // Windows support
$output = str_replace("\n", '\n', $output); // Linux support
if($urlFriendly) { // Encode for use in URLs
$output = urlFriendly($output);
}
return $output;
}
$vrj_name = 'vrj';
$messageContent_vrj = 'message content';
$from_email = 'from email';
$email = 'email';
$subject = 'subject line';
?>
<script type="text/javascript">
function SelectRedirect() {
switch(document.getElementById('s1').value) {
case '?vrj_name=<?php print jsFriendly($vrj_name);?>':
var toloc = '?vrj_name=<?php print jsFriendly($vrj_name);?>';
toloc += '&messageContent=<?php print jsFriendly($messageContent_vrj);?>'';
toloc += '&from_email=<?php print jsFriendly($from_email);?>';
toloc += '&email=<?php print jsFriendly($email);?>';
toloc += '&subject=<?php print jsFriendly($subject);?>';
window.location = toloc;
break;
}
</script>
just like that
$escaped_string = addslashes($unescaped_string);
either before
$messageContent = addslashes($messageContent);
$subject = addslashes($subject);
or even inline
echo '
case "?vrj_name='.$vrj_name.'":
window.location="?vrj_name='.$vrj_name.'&messageContent='.addslashes($messageContent).'&from_email='.$from_email.'&email='.$email.'&subject='.addslashes($subject).'";
break;
';

how to write variables value with file_put_contents()?

Have been trying to figure this out all day assuming its just a small error.....
I'm trying to use the file_put_content to put a variables value into another php file..
Code below will explain:
File that writes the data into the php:
<?php
require ('conf_2135432135435135412312534.php');
$F_name =$_POST['F__name'];
$L_name =$_POST['L__name'];
$E_mail =$_POST['Email'];
$GDI_user =$_POST['GDIusername'];
$ip=$_SERVER['REMOTE_ADDR'];
$C_date = date("F j, Y, g:i a");
mysql_connect($hostname,$username,$password) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$sql = "INSERT INTO $usertable (F_name, L_name, Email, GDI_username, Registration_IP, Date_registered) VALUES ('$F_name', '$L_name', '$E_mail', '$GDI_user', '$ip', '$C_date')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
$get_id = mysql_query("SELECT * FROM $usertable WHERE ". "GDI_username = '$GDI_user'");
while($id_check = mysql_fetch_array($get_id)) {
$UNQ_ID = $id_check["Unique_id"];
}
$src = "/home/files/1/741/html/WP/Default_files";
$dest = "/home/files/1/741/html/WP/$GDI_user";
echo "$GDI_user/config.php";
shell_exec("cp -r $src $dest");
file_put_contents("/home/files/1/741/html/WP/$GDI_user/config.php",'<?
$affiliate_reference = "$UNQ_ID";
echo $UNQ_ID;
?>');
?>
^^Short explanation of what that code does:^^
1.) Takes info from a html form
2.) INSERTS the data into a DB
3.) Fetches a Unique_id number from the DB
4.) Makes a copy of a folder with all the contents in it (Default_files)
5.) The duplicate folder is given a name of what was entered into the HTML form
6.) Writes into a file contained in the duplicate folder (config.php)
What the output (config.php) SHOULD contain:
<?
$affiliate_reference = "2154216354154"; //<<<thats just an example number
echo 2154216354154;
?>
Instead, This is what's showing up:
<?
$affiliate_reference = "$UNQ_ID";
echo $UNQ_ID;
?>
completely lost here. Any help would be much appreciated.
You're using ' to define the string, this means that the value will be left unparsed. The trick here, though, is that you want $UNQ_ID parsed, but you want $affiliate_reference left as is. This means you have to escape or manually concatenate
I would use this instead:
'<?
$affiliate_reference = "'.$UNQ_ID.'";
echo '.$UNQ_ID.';
?>'
Notice, I am using the single quote for the majority of the string. This is purposeful, you don't want the $affiliate_reference to be output. You only want $UNQ_ID turned into its string equivalent. Your other option is to use " and escape the $:
"<?
\$affiliate_reference = "'.$UNQ_ID.'";
echo '.$UNQ_ID.';
?>"
Note the \ to escape $ in front of $affiliate_reference.
I generally prefer the first way, color syntax highlighters will make that very obvious (even notice how SO handles it), while the second example causes highlighters to glaze over the whole thing. It is a preference, but it is an important one.
Of course, there is always the silly:
$a = '$';
followed by
"<?
${a}affiliate_reference = "'.$UNQ_ID.'";
echo '.$UNQ_ID.';
?>"
Use that only with people you don't like.
Change the single quotes surrounding the string you are writing to the file to doubles quotes. So:
file_put_contents("/home/files/1/741/html/WP/$GDI_user/config.php",'<?
$affiliate_reference = "$UNQ_ID";
echo $UNQ_ID;
?>');
...becomes...
file_put_contents("/home/files/1/741/html/WP/$GDI_user/config.php","<?php\n\n $affiliate_reference = '$UNQ_ID';\n echo $UNQ_ID;\n\n?>");
A couple of thoughts on this operation
Don't use PHP short tags - use <?php instead of <? as short tags are not supported everwhere and are disabled by default on new PHP installations
Don't put new-line literals in the middle of quoted strings, use HEREDOC syntax if you want to do that. It's best to avoid this if possible as it can lead to cross-platform compatibility issues. Use \r, \n, \r\n and the PHP_EOL constant instead.
Read this thoroughly so you know exactly what you can and can't do, and where.
The problem is that you are using single quotes, so the variables are not shown.
Change:
file_put_contents("/home/files/1/741/html/WP/$GDI_user/config.php",'<?
$affiliate_reference = "$UNQ_ID";
echo $UNQ_ID;
?>');
to:
file_put_contents("/home/files/1/741/html/WP/$GDI_user/config.php","<?
$affiliate_reference = '$UNQ_ID';
echo $UNQ_ID;
?>");
Note that I have changed the double quotes for $affiliate_reference to single quotes. If you need double quotes, you can escape them:
$affiliate_reference = \"$UNQ_ID\";
There are a few things wrong with this code. First, to address your problem, single quotes do not expand variables. That is the difference between single quotes and double.
After cursory inspection, I would recommend the following additional changes:
1) Sanitize your input prior to inserting into the database, you can use mysql_real_escape_string for this.
2) Use copy inside of a function that recurses the directory in order to copy it. This allows proper error handling. At a minimum, sanitize $GDI_user (via basename or some other method to prevent ..)
You're using single quotes. You cannot embed variable's values into a single-quoted string. Use concatenation, double-quotes, or heredoc.
http://php.net/string
And I think leading zeros in a number might cause problems, but I'm not sure. Plus it's always safe to use addslashes in situations like this.
$escaped_UNQ_ID = addslashes($UNQ_ID);
file_put_contents("/home/files/1/741/html/WP/$GDI_user/config.php", "<?php
\$affiliate_reference = \"$escaped_UNQ_ID\";
echo \$affiliate_reference;
?>");

Printing varchar php variable inside the javascript function

I am trying to print a variable value within the javascript function. If the variable is an integer ($myInteger) it works fine, but when I want to access text ($myText) it gives an error.
<?php $myText = 'some text';
$myInteger = '220';
?>
<script type="text/javascript">
<?php print("var myInteger = " . $myInteger . " ;\n");?> //works fine
<?php print("var myText = " . $myText . " ;\n");?> //doens't work
</script>
Can anyone explain to me why this happens and how to change it?
The problem with your code from the question is that the generated Javascript code will be missing quotes around the string.
You could add quotes to the output manually, as follows:
print("var myText = '". $myText. "';\n");
However, note that this will break if the string itself contains quotes (or new-line characters, or a few others), so you need to escape it.
This can be dealt with using the addslashes() function, among others, but this may still have issues.
A better approach would be to use PHP's built-in JSON functionality, which is designed specifically for generating Javascript variables, so it will do all the escaping for you correctly.
The function you're looking for is json_encode(). You'd use it as follows:
print("var myText = ". json_encode($myText). ";\n");
This will work with any variable type -- integer, string, or even an array.
Hope that helps.
Without more code we don't really know what you're trying to do or what error you're getting (or from where even), but if I had to guess:
If you are putting a string of text into a javascript variable, you probably need to quote it.
<?php print("var myText = '" . $myText . "' ;\n");?>
---^^^-------------^^^----
// Or even better:
<?php print("var myText = '$myText' ;\n");?>
ADDENDUM Per the comment below, don't use this if you expect your $myText to contain quotes.

Changing Text in PHP

I haven't found anytihng in Google or the PHP manual, believe it or not. I would've thought there would be a string operation for something like this, maybe there is and I'm just uber blind today...
I have a php page, and when the button gets clicked, I would like to change a string of text on that page with something else.
So I was wondering if I could set the id="" attrib of the <p> to id="something" and then in my php code do something like this:
<?php
$something = "this will replace existing text in the something paragraph...";
?>
Can somebody please point me in the right direction? As the above did not work.
Thank you :)
UPDATE
I was able to get it working using the following sample:
Place this code above the <html> tag:
<?php
$existing = "default message here";
$something = "message displayed if form filled out.";
$ne = $_REQUEST["name"];
if ($ne == null) {
$output = $existing;
} else {
$output = $something;
}
?>
And place the following where ever your message is to be displayed:
<?php echo $output ?>
As far as I can get from your very fuzzy question, usually you don't need string manipulation if you have source data - you just substitute one data with another, this way:
<?php
$existing = "existing text";
$something = "this will replace existing text in the something paragraph...";
if (empty($_GET['button'])) {
$output = $existing;
} else {
$output = $something;
}
?>
<html>
<and stuff>
<p><?php echo $output ?></p>
</html>
but why not to ask a question bringing a real example of what you need? instead of foggy explanations in terms you aren't good with?
If you want to change the content of the paragraph without reloading the page you will need to use JavaScript. Give the paragraph an id.<p id='something'>Some text here</p> and then use innerHTML to replace it's contents. document.getElementById('something').innerHTML='Some new text'.
If you are reloading the page then you can use PHP. One way would be to put a marker in the HTML and then use str_replace() to insert the new text. eg <p><!-- marker --></p> in the HTML and $html_string = str_replace('<!-- marker -->', 'New Text', $html_string) assuming $html_string contains the HTML to output.
If you are looking for string manipulation and conversion you can simply use the str_replace function in php.
Please check this: str_replace()
If you're using a form (which I'm assuming you do) just check if the variable is set (check the $_POST array) and use a conditional statement. If the condition is false then display the default text, otherwise display something else.

Categories