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).
Related
How would one go about showing PHP code on user end. Sort of like w3School does?
Having lets say a grey area div, and then showing the code in there without activating it?
You can use html entities <?php in the html it will be rendered as <?php
You can use htmlspecialchars to encode your code to use html entities.
Use <pre> or <code> tags to wrap your code.
Take a look at http://php.net/manual/en/function.highlight-string.php to further see how you can make the code look pretty.
Since passing a large block of code to highlight_string() can be messy, you may want to look at output buffering in combination with highlight_string to output colorized php code.
Something like:
<?php
ob_start();
?>
phpinfo();
echo "this echo statement isn't executed";
<?php
$code = ob_get_clean();
highlight_string($code);
?>
Simply you can use following code to display php code on webpage.
highlight_string("<?php print('This is php code.'); ?>");
It will give output like
<?php print('This is php code.'); ?>
The first step is to not wrap that code in PHP tags. So instead of this:
<?
var sample = "code";
?>
You would have this:
var sample = "code";
It's not the code itself which triggers the server-side compile from the PHP engine, it's the tags which indicate to that engine what blocks of the file are code and what are not. Anything that's not code is essentially treated as a string and output to the page as-is for the browser to interpret.
Once you're outputting the code, it's then a matter of formatting it. The old standard is to wrap it in pre tags to get rid of HTML-ish formatting:
<pre>
var sample = "code";
</pre>
You can also apply CSS style to the pre tags (or any other tags you want to use for displaying code, such as div) as you see fit.
There are also very useful code syntax highlighting plugins and tools to make the code a lot "prettier". Google-code-prettify often comes highly recommended.
Typically this is done by showing code within <pre> or <code> tags.
You can use this template........
######################################################################
echo "<h2><br>Source Code of ".basename((string)__FILE__) . "</h2><hr>";
show_source(__FILE__);
echo "<hr>";
echo "<h2>Output of ".basename((string)__FILE__) . "<hr></h2>";
#######################################################################
It will show the source code and output following.
use the header function of php, this will rea
<?php
header("content-type: text/plain");
?>
The PHP code will just be a string that you can echo or print onto the page, no different than any other data you want PHP to display for you. If you want to keep the formatting (ex. the indentation), put it inside a <pre><code> block.
Ex:
$php_code = '<?php $foo = bar; ?>';
echo "<pre><code>$php_code</code></pre>";
I have a php variable $username and following script:
<?php
echo ''.$username.'';
?>
If $username contains something <b it bolds text. How can I prevent that?
Use htmlspecialchars
echo ''.htmlspecialchars($username).'';
See documentation: http://php.net/manual/en/function.htmlspecialchars.php
echo ''.htmlentities($username).'';
like that:
<?php
echo ''.htmlspecialchars($username).'';
?>
http://php.net/manual/fr/function.htmlspecialchars.php
the echo in PHP returns the HTML of whatever you tell it should. So if you use e.g.
echo "This is my text which should be displayed as it is <b>";
the browser will translate it into the according HTML Text (every browser has built in mechanics to "repair" malformed HTML), which will be
<b>This is my text which should be displayed as it is</b>
This is not only wrong, but also a security risk. Imagine someone uses an extremely long name which would translate into javascript once the browser renders it. Your server would turn into a spambot machine.
To prevent this from happening, you have to use the according php function, which is htmlspecialchars() (or htmlentities();
So your code will be:
echo ''.htmlspecialchars($username).''
and it will display the name as intended.
You need to strip (remove) HTML tags from the string.
echo '' . strip_tags($username) . '';
http://php.net/manual/en/function.strip-tags.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 ;)
I'm trying to create a block of PHP code within HTML such that when the user loads the page, it displays their IP address and time/date as the user in an email address.
I'm using apache on fedora21, and have enabled PHP (tested with phpinfo() function in the same HTML file).
Here is the code I'm trying to execute:
<? echo '<a href="mailto:'.$REMOTE_ADDR.'_'.date('y-m-j').'-#example.com" title="There is no spoon">For stupid spambots'; ?>
It just prints For stupid spambots'; ?> without printing the generated email address.
<? echo 'For stupid spambots'; ?>
Need to close <a href at first, and if you want to return IP its $_SERVER['REMOTE_ADDR'] not $REMOTE_ADDR except you define that variable before.
Judging from the fact that you can see closing ?>, I deduce that your PHP code doesn't run at all and is interpreted like regular HTML.
There might be several reasons why (badly configured Apache being one of them), but my prime suspect is that you have disabled short PHP tags. Try using <?php instead of <?.
You used the syntax of an html anchor wrong. Consider this:
<?php
$address = sprintf('%s_%s-#example.com', $_SERVER['REMOTE_ADDR'], date('y-m-j'));
echo sprintf('%3$s: %1$s',
$address,
'There is no spoon',
'For stupid spambots');
?>
You have to print the address into the visible text content of the anchor definition if you want it to be visible. You only but the "For stupid spambots" string in there which is what got displayed.
( Note that I just used the sprintf() calls to keep the lines short and readable. Obviously this also works with traditional string concatenation. )
This is the way I am currently doing it.
<?php
//show footer
echo "<script type='text/javascript'>\n";
echo "alert('Congrats');\n";
echo "</script>";
?>
Is there a better way than just to echo it?
Just put your JavaScript code outside PHP tags:
<?php
// your PHP code goes here
?>
// your javascript function out of the PHP tag.
function f() {
alert('congrats');
}
of course
?>
alert('Congrats');
<?
If you really have to execute the js by printing it from the PHP, it would at least be cleaner if you had your js functionality stored in functions in some file and then called them by printing the calls.
I recommend reserving PHP files just for PHP code and keeping your frontend code (HTML/CSS/javascript) in separate template files.
Last time I checked, mixing the presentation layer & backend code into same file was popular about 12 years ago.
Your file hierarchy for a project could look like this:
- my_project
- lib
- PHP files here
- templates
- HTML templates here
- public <- this is your document root for web server
- index.php <- just a dispatcher
- js
- images
- css
Use HEREDOCS, or break out of PHP mode into "html" mode. If the Javascript is entirely static, or has a few parts that need to have some PHP value included, drop into html mode ('?>' out of php). This will allow any decent text editor to realize that you're doing HTML and Javascript, and syntax highlight as appropriate. The following are all equivalent, but decide for yourself which is more readable:
'pure php':
<?php
echo '<script>';
echo ' var x = [' . $somePHPvar . '];';
echo ' alert(x);';
echo '<script>';
?>
'heredoc' syntax:
<?php
echo <<<EOF
<script>
var x = [{$somePHPvar}];
alert(x);
</script>
EOF;
?>
'html mode':
<?php ?>
<script>
var x = [<?php echo $somePHPVar ?>];
alert(x);
</script>
plusses/minuses for each:
pure php: you can stay in PHP mode, and your echo + $vars will be highlighted as PHP code, but the html/javascript you're echoing will be treated as plain text and colored as such (ie: all the same color)
heredoc syntax: You stay in PHP mode, but gain the benefit of not having to escape any quotes (' and ") in your code, so any html will look cleaner. Most editors will recognize PHP vars in the heredoc block and color them appropriately, but the rest of the text will be treated as text, so javascript/html look the same. Also, you cannot insert function calls into the text. You have to do those BEFORE starting the heredoc and store the results in a var, which can be inserted. The HEREDOC can also be use to assign long text blocks into a variable directly.
'html mode': The editor will see/recognize your html, javascript, AND php and color them appropriately. But this is at the cost of having to sprinkle php open/close tags anywhere you need to fill in some value dynamically. On the plus side, you can directly insert function call results (htmlspecialchars(), urlecncode(), html_strip_tags(), etc...) without having to store the values in an intermediate var. It also makes for harder-to-maintain code as your PHP is now sprinkled randomly throughough the html/javascript code.
It all boils down to what's easiest for the particular code you're working on.
You can use the model-view-controller pattern for outputting JavaScript.
You can have a "view" file where most of your JS is stored:
myJavascript.js.php:
alert('hello bob');
alert('hello <?php echo $name; ?>');
alert('whats up?');
Your controller, jsController.php:
$name = "Jane";