Using PHP variable inside HTML, in a PHP file - php

I've been trying to get this to work for a while now, and have yet to find a solution online that works. I'm still fairly new to PHP so forgive me if the question is dumb.
I'm using a PHP document to read data from a text file. That PHP document is called as a script to the HTML document which actually displays all the information on the webpage.
So to my understanding, I have to use echo "document.write("")"; to output stuff, which works fine.
However, when I try using variables, it doesn't seem to work. For example I'm trying to do:
<?php
$test = "Hello";
echo "document.write("$test")" ?>
Am I missing something?

The specific reason your code is not working is your use of quotes. You can't enclose double-quotes within double quotes unless you escape them first - like this:
echo "document.write(\"$test\")" ?>
However, there is a deeper problem here. You don't need the Javascript at all. You could just do:
echo $test;
Lastly, document.write() has all sorts of unwanted side effects. If really do need that then you probably want to manipulate the DOM in Javascript directly, but that's a different question.

Just use echo to do what you want:
<?php
$test = "Hello";
echo $test;
?>
Value of $test will be outputted to the html.

document.write only works in JavaScript, try just use echo

If you want document.write to add the value of the $test variable in JavaScript, you are almost on the right track, but need to escape your quotation marks:
echo "document.write(\"$test\")";

because document.write(); is for javascript,to use variable just use variable name only in echo

I don't what you are trying to do, if you want to just output a text into a php usse echo
Your wrote it's incorrect
<?php
$test = "Hello";
echo "document.write("$test")";
?>
Correct way
<?php
$test = "Hello";
echo $test;
?>

I think you need quotes around the string in the document.write :
<script>
<?php
$test = "Hello";
echo "document.write('" .$test ."');";
?>
</script>
Which becomes :
<script>
document.write('Hello');
</script>
Which in turn displays this on the page :
Hello

If you want output into HTML then you can simply use echo function of PHP.
<?php
$test = "Hello";
echo "<script>document.write('" .$test ."')</script>";
?>

Related

PHP: php variable in html link (<a>)

Please help me with this problem.
<?php echo $userRow2['description']; ?>
It seems that the PHP variable is incompatible with html link :(
so I want to know what is the proper method.
TIA...
echo those variables there like the following.
<?php echo $userRow2['description']; ?>
Please use a template engine for these kinds of things...
Use one of:
smarty
twig
mustache
php-view
These will brighten up your day and remove the complexity out of your html files
You can also pass all your GET params in an associative array, and use:
http_build_query($params)
so:
or in your way:
<?php echo $userRow2['description']; ?>
You can also build html/php mix with heredoc:
http://www.hackingwithphp.com/2/6/3/heredoc
it seems that the php variable is incompatible with html link
Well, PHP runs server-side. HTML is client-side. So there's no way for client-side code to interpret PHP variables.
You need to enclose server-side code in <?php ?> tags in order for it to execute on the server (like you already do elsewhere). Otherwise the server just treats it as any other HTML and returns it to the browser. Something like this:
<?php echo $userRow2['description']; ?>
As you can see, that gets a bit messy. But you can put the whole thing in one echo statement:
echo "$userRow2[description]";
Notice how the double-quotes needed to be escaped in that one, but since the whole thing was a double-quoted string the variables contained therein would expand to their values.
There are readability pros and cons either way, so it's up to you how you want to present it.
you should use this
<?php echo $userRow2['description']; ?>
or
<?=$userRow2['description']?>
You can also use Here Doc Syntax
<?php
//test variables
$inst_id = 1;
$description = "Test 1";
$eof = <<<EOF
$description
EOF;
//test output
echo $eof;
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Getting a variable from a link PHP

I have two files, one called test3.php, and another called test4.php. I'm trying to echo the variable in the link of the file test4.php, but it's echoing unexpected results. Please take a look.
In the file called test3.php:
<?php
$text = "Good morning.";
header('Location:test4.php?text=$text');
?>
In the file called test4.php:
<?php
$text = $_GET['text'];
echo "$text";
?>
Expected echo result:
"Good morning."
Actual echo result:
$text
I don't understand why it's echoing out $text, instead of "Good morning." One thing that came to mind is that you can't actually set variables when you're using a header, so if that's the case please let me know. Thank you.
Variables do not get parsed in single quotes
header('Location:test4.php?text=$text');
therefore, you need to use double quotes
header("Location:test4.php?text=$text");
References:
https://php.net/language.types.string
https://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
What is the difference between single-quoted and double-quoted strings in PHP?
Plus, it's best to add exit; after header, in order to stop further execution, should you have more code below that (or decide to in the future).
http://php.net/manual/en/function.header.php
and using a full http:// call, as per the manual
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
Footnotes, about header, and as per the manual:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
However you wrote, and I'm using this literally:
Expected echo result:
"Good morning."
If you want to echo just that "Good morning." having the text in double quotes, then you will need to change the following in your test4.php file:
echo "$text";
to, and escaping the " using \
echo "\"$text\"";
use
header("Location:test4.php?text=".$text);
In test4.php:
<?php
$text = $_GET['text'];
echo "$text";
?>
When you quote "$text", you are echoing af string.
What you will want to do, is echo the variable: $text.
So:
<?php
$text = $_GET['text'];
echo $text;
?>
...Without the quotes.. :)
And also, the: header('Location:test4.php?text=$text'); is a bitch, if you use it below a lot of code...
Safe yourself some trouble, and use:
echo "<script type='text/javascript'>window.location.href = 'test4.php?text=".$text."';</script>";
instead ;)

write php inside javascript alert

I write PHP inside JS in the following way
alert(<?php echo __("Error-login") ?>);
echo__("Error-login") correlates with an xml to translate in two languages ​​with symfony, but now it does not work.
How do I fix this?
You are missing quotes in the alert() call.
alert('<?php echo __("Error-login") ?>');
Your line becomes
alert(Error-login);
As you can see, you are missing the quotes:
alert('Error-login');
If somebody uses quotes in the translation, this will also generate an error:
alert('Error's are here');
So you need to escape single quotes before you pass it to Javascript.
try this
<?php echo '<script language="javascript">confirm("Do you want this?")</script>;'; ?>

How to echo variable before declaration? php

I need to echo a var in a page but the value is declared later after being included in the page.
Is there any way to echo a var before I declare it? or some way to include the page withought running any of the code and just getting the var?
No language is obviously able to output a value, before it exists.
If you want to do something like..
echo $var;
$var = "Hello world";
Then the answer is no. PHP is an interpreted language which runs downwards, not every which way.
The simplest, best and most sensible option is to fix your logic so everything happens in a logical order.
Failing that. Store your data in a variable instead of outputting it. Include a placeholder where you want the variable to be. Then do a search and replace on that placeholder once you have the data you need.
You can build a template-like solution. Put something like ##var## in the page, use ob_start() at the beginning of the page, define your $var whereever, then, at the end of the page, use echo str_replace('##var##', $var, ob_get_clean());.
Example:
<?php ob_start() ?>
<p>##test##</p>
<?php $test = "this is a test paragraph" ?>
<?php echo str_replace("##test##", $test, ob_get_clean()) ?>
Check out ob_start(), and ob_get_clean().
There is a way to use JavaScript with PHP for this kind of echos.
$echo = document.getElementById('dispaly_div').innerHTML = "$variable";
One way is to use functions.
For example:
function printvar($string) {
echo $string;
}
printvar("Hello World!");
This is tested and works.

Do I need to escape this?

It might be a bit unusual, but I need to echo <?php. However, I think that PHP treats it as an actual <?php and starts executing code instead of treating it as a string. How can I escape <?php and ?> so they can be treated as strings? There was nothing in the manual about this.
Thanks, I know this is a bit unusual.
just use htmlentities function
<?php echo "<?php echo \"hello\" ?>" ?>
prints out <?php echo "hello" ?>
Check out PHP's sourcecode of functions on how they print out data.
http://in2.php.net/source.php?url=/manual/en/function.htmlentities.php
You can use the < and > html entities (to replace '<' and '>'). These are only handled in the browser, so PHP would not attempt to run that code.
In HTML,
<?php
Or in PHP:
echo htmlentities('<?php');
If this is your code:
<?php
echo '<?php';
?>
And you run that as a web page, you will see nothing. But not because PHP is not echoing your string <?php, but because the browser sees < and thinks that's the start of a tag, and tags are not displayed. It's obviously an error, but that's what the browser is doing.
To get around this, escape the < part, use htmlentities():
<?php
echo htmlentities('<?php');
?>
Which when it gets echoed, will result in HTML source of:
<php
Which when displayed in the browser shows:
<?php
If they are echoed in a string they will not be executed.
echo '<?php ?>'; // prints <?php ?>
echo "<?php ?>"; // prints <?php ?>
No, you do not have to do anything special.

Categories