Getting a variable from a link PHP - 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 ;)

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

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 - how to hide the HTML part when no session_start();

thank you in advance , i wanted to stop not logged_in visiters from reaching some pages
i know i can just do that by cheking values in SESSION_ and and showing the HTML part with
<?php echo '<html>...</html>'; ?>
but i have a very long html content with both '' & "" text delimiters because it's not only HTML there is some JavaScripts, so i'm looking for another methode rather than printing the code with ECHO , and in this case i can't mixt PHP and HTML code . i there any solution or another idea to secure page from non member to see it,
and can i use this code to take them back to hope page (? :
<?php header("Refresh: 0;url=http://index.php/"); ?>
is it secure ?
so i'm looking for another methode rather than printing the code with
ECHO ,
use [heredocs] style or print all HTML outside php tag:
1- [heredocs]
echo <<<HEREDOCS
any string here ' or "
HEREDOCS;
note: notations should be at beginning of each line and ends with line break without any space or indent.
2- separation logic
<?php
//here is php
//close php
?>
<html>
<head>
</head>
<body>
<p>This will also be ignored by PHP and displayed by the browser.</p>
....
</body>
<?php
//php again
?>
When you echo out code that uses both ' and ", you escape the characters that match your opening and closing tags, like so:
echo '<p class="someclass">This can\'t be the end.</p>';
or
echo "<p class=\"someclass\">This can't be the end.</p>";
If you're worried about the " & ' text parameter,you should just use text editor such as sublime to to replace all " to '
and for " in textarea you can replace with "
then do
echo " <a href='#' value='{$var1}'>double quote mean "</a>some other massive code ";
thus you can just use a <?php and ?> from the beginning of page till the end of the page
What you can probably do is perform the check for the session variable at the start of the file and if the user is not logged in, use a header('Location: index.php'); followed by an exit();. If you do need to send headers based on logic that appears after the echo statements and changing the order of the statements is not doable, use output buffering.
Also, instead of including the HTML and Javascript within your code file, consider using a template engine, using include, or a combination of file_get_contents and echo (and possibly a string replace if you are using content placeholders). Heredocs and Nowdocs will make it easier to include single-quotes and double-quotes within strings.
Edit: If all you want to show unauthenticated users is an error message, you can redirect them to an error page, or use the PHP die(''); statement (which is like a combination of an echo and an exit).

Show an Image if a PHP argument proves true

I barely know how to use PHP and I can't seem to make my code show an image if a condition proves true. This is the code:
<?php
$search=get_search_query();
$first=$search[0];
if ($first=="#"){
}
?>
I tried writing this thinking it would work and it didn't:
echo "<html>";
echo "<img src='http://chusmix.com/Imagenes/grupos/lujan.jpg'>";
Also I tried a code I found which started with the function: header() but it caused a tremendously long error, which said something like header already defined.
Thanks
You have used 'double quotes' incorrectly in the echo statement.
Try the following:
echo "<img src='http://chusmix.com/Imagenes/grupos/lujan.jpg' alt='Preview not available' />"
Regards,
Mahendra Liya.
You should var_dump($first) to know what it contains
check if the condition is really getting true
and also put single quote inside the double quote.
if ($first=="#"){
echo 'yes it is true';
echo "<img src='http://chusmix.com/Imagenes/grupos/lujan.jpg'>";
}
close the img tag
The part of the query string starting with # (so-called "hash") is not being sent to the server. That is, if your page is called like myblog.com/foo?bar=baz#quux, you php script will only receive myblog.com/foo?bar=baz. You need javascript if you want to handle urls with hashes.

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