How to echo variable before declaration? php - 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.

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

Using PHP variable inside HTML, in a PHP file

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>";
?>

PHP echo-ing a PHP code inside an echo

I'm quite new here. I'm trying to make a blog/journal site that allows users to post their own journal. I'm still quite reluctant on making it because I am really afraid of malicious code injections.
So here's a sample code:
<?php
$test = "<b>blah</b>"; //User input from SQL
echo "$test";
?>
What will come out is just the word "blah" in bold right? What I was trying to achieve was to echo "<b>blah</b>" instead. I don't want people to put some PHP codes that can actually mess up my whole web page. Please keep in mind that the variable $test is actually a MYSQL query, so that variable will be needed as an example. I know you can do echo '$test'; but it just comes out as "$test" instead. I feel like pulling my hair out I can't figure it out yet.
The second solution I know of is the htmlspecialchars(); function, but I want the strings to display as what I typed, not the converted ones...
Is there any way I can do that?
I think the OP wants the HTML itself to be output to the page, and not have the tags stripped. To achieve this, you can run the string first through htmlentities()
$test = '<b>blah</b>';
echo htmlentities($test);
This will output:
<b>blah</b>
Which will render in the page as
<b>blah</b>
Echo don't execute PHP code from string. This is impossible and this is not security hole in your code.
You can use a template engine like Twig for exemple.
If htmlspecialchars(); is not the one you are looking for, try the header() option.
header('Content-type: text/plain');
When you are gonna give <b>Hi</b> to a browser, it will be displayed in Bold and not the text be returned. But you can try this way, outputting it inside a <textarea></textarea>.
Or the other way is to use htmlentities():
<?php
$test = "<b>blah</b>"; //User input from SQL
echo htmlentities("$test");
?>

Including dynamic HTML with PHP

I have PHP variables to place within an included HTML file. What's the best way of executing this?
//contents of file1.php
$variable1 = "text 1";
$variable2 = "text 2"
$newContent = include('file2.php');
echo $newContent;
//contents of file2.php
<p>standard HTML with PHP... <strong><?=$variable1?></strong></p>
<p><?=$variable2?></p>
This general method is considered OK but the actual code here doesn't work. Do I use file_get_contents() or include(), how do I execute the PHP within the includes file to output the correct contents?
Should I be using something like HTML>>>
What you're doing is fine, and you'll find that most people use the same exact method. I personally wouldn't use PHP short tags (some hosts don't enable it), but that's a matter of preference.
Edit: As per your edit, it seems like you don't have short tags enabled. Check your ini (http://php.net/manual/en/ini.core.php). But you really shouldn't be using short tags, because as clownbaby mentions, PHP 6 will deprecate them. Even if you don't care about future proofing your code, they're still troublesome (which is evident because your code isn't working). Switch to <?php echo $variable1; ?> and you'll be fine.
I think your code is fine, even most frameworks use it...
regarding the use of short tags, some servers do not allow it, so here is a workaround I use:
if ((bool) #ini_get('short_open_tag') === FALSE){
echo eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents("path/to/file2.php"))));
}else{
$newContent = include("path/to/file2.php");
echo $newContent;
}
$newContent = include('file2.php');
echo $newContent;
You shouldn't need to echo anything here. Just including the PHP file should execute any code inside it and spit out the interpolated template to the page. Whilst there is such a thing as returning a value from include, it's a rarely used feature you can generally ignore.
As ekhaled said, you may need to enable short tags or replace them with the always-supported <?php ... ?> processing-instruction-style syntax.
However, it's important to htmlspecialchars every text string when including it in HTML, or you've got a potential XSS security hole.
<?php
function h($text) {
echo(htmlspecialchars($text, ENT_QUOTES));
}
?>
...
<p>standard HTML with PHP... <strong><?php h($variable1) ?></strong></p>
<p><?php h($variable2) ?></p>

Categories