PHP sessions with HTML - php

I have a website which uses PHP and HTML pages, I want to create a session which stores a username from the login page. But the login pages are php and the next pages are html.
Is this a problem or can I just add a small statement of php into the html page saying
<?PHP session_start();
$_session['loginid']=$_post['username'];
?>
Or am I doing it wrong?
This is the first time i've used sessions and they confuse me a little.
thanks for any help.

If you have access to your apache configuration, or a simple .htaccess file, you can tell Apache to handle php code inside of an .html file. You can do this by creating an .htaccess file (remember the . (dot) as the first character in that filename) on the document root of the site (probably public_html/) and putting this into it:
# Add this to public_html/.htaccess file
AddHandler application/x-httpd-php .html
AddHandler application/x-httpd-php .htm
You should be able to reload the html page and your PHP code (from Michael Matthews answer) will run great.

You are trying to share a PHP session variable with a page that is of type text/html. As you suggested you must make the HTML page a PHP page for this to work and add a little snippet of PHP somewhere to display the user name.
Change your HTML page to PHP. At the top of the page add something like this:
<?php
session_start(); // must be before any output
$username = $_SESSION['username']; // or whatever you called it
// check that $username is valid here (safe to display)
?>
html here
Hello <?= $username ?>!

As the sessions are handled by PHP, it needs PHP to maintain the state. You need at least session_start() to use the session variables stored in $_SESSION.

You can't put php into .html files without playing around with your server's configuration files. You should only put php into .php files.
If you have a lot of .html files, you can simply rename them to .php files. It's okay to put pure html into something.php. So, you should make sure that all of your files end with .php, and then you can put any session logic you want into them.

Related

Setting $_SESSION variable but something doesn't work

I am sure this is something really simple but I can't figure out what's wrong.
I have set up my html, php, and js file to work together but am having trouble with setting my own session variable and checking it across files.
I have made sure that both the HTML and PHP files contain the include for my session.php file (the file just handles session_start if not already set).
To sum it up, my HTML file has a function (userSelection aka fxn1). This function passes a value to another function (showGameInfo aka fxn2), and my .js file handles fxn2. Then, fxn2 sends it to the php file which spits out the information to display. Everything works fine until I try to define my own variable. I did this inside fxn1 in the html file. Then, I tried to echo the $_SESSION['test'] value in the php file. This is the line I added to fxn1:
<?php $_SESSION['test'] = 1 ?>;
Am I missing something really simple here? My php file shows the SESSION is set. Please let me know what might be wrong.
FXN1 is in my HTML file like this:
<script>
function userSelection(val) {
<?php $_SESSION['test'] = 1; ?>
showGameInfo(val);
}
</script>
If I take out the SESSION['test'] line in the html, the php file simply says the variable test is undefined, and displays the rest as it should.
So that tells me it's wrong in the HTML somehow..but why?
Edit1: I have included session.php in my html and php file. session.php contains this:
<?php
if (!isset($_SESSION))
session_start();
?>
Is that incorrect? It's at the top of the html. And this is how it is included in the php file as well, and my php file shows isset($_SESSION) to be true, so I assume it's correct.
""FXN1 is in my HTML file like this:" - define that. As in .html file? – Fred -ii-"
"#Fred-ii-, yes it is in my main .html file, defined as so. – Gredenko"
First you need to start the session and for the .html file, change that to .php or instruct your system to treat those as php.
PHP does not parse directives with .html as a default.
You should also check to see if the session array is set with isset().
Start your session first using
session_start();
Then only you can work with sessions.
<script>
function userSelection(val) {
<?php
session_start();//starts your session
$_SESSION['test'] = 1;//sets session variable ?>
showGameInfo(val);
}
</script>
For more see manual PHP Sessions
session_start(); must be on any page needing to define or recall session variables and must be before defining or calling the variables.
From the PHP manual (emphasis added):
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
Also, if you want run PHP in an HTML file, you would need to add this to a .htaccess file in your folder
AddType application/x-httpd-php .htm .html

How to disable direct entry to a html?

Say I have two html files called html1 and html2. html1 contains an embedded swf file.
Now what I want is that the user can not go to html2 directly via url. He has to click it through the link in the swf in html1. Is there a way to achieve this?
If not possible in html, is it possible with php?
Thanks
EDIT:
After answer from John, I went ahead and tried his advice, but I can never access the file2.php, even if I have been to file1.php before. It keeps redirecting me back to file1.php, even when it should not.
My code from file1.php
//file1.php
<?php
session_start();
$_SESSION['enableAccessTill']=strtotime("+5 minutes");
?>
Here is file2.php
//file2.php
<?php
session_start();
if(!isset($_SESSION['enableAccessTil'])||$_SESSION['enableAccessTil']<time())
{
header("Location: indexFLA.php");
exit;
}
?>
what am I possibly doing wrong?
found it, it was due to a misspelling - "enableAccessTil" and "enableAccessTill"
professional solution:
create protected directory and make .htaccess file in directory and copy all embedded and partial files into directory.
this directory not accessible whit get url.
but you can include file whit php include and require method.
.htaccess content:
deny from all
This wont be possible in just plain html.
An easy way to do this is php is by setting a session variable in file 1, and test in file 2 it the users has been to file 1.
file1:
<?php
session_start();
$_SESSION['enableAccessTill'] = strtotime("+5 minutes"); //set the time here till when the user has access
[...]
file2
<?php
session_start();
if(!isset( $_SESSION['enableAccessTill'] ) || $_SESSION['enableAccessTill'] < time() ){ //If time is expired
header("Location: file1.php"); //redirect user to the first file
exit;
}
[...] //continue your script here.
Things with referrer check do usually fail (some browsers/firewalls blocking that variable).
Based on the options you described, it would sound most reasonable to make the html2 a php script and check that the referrer is the html1 file. The script should display the normal html1 content if that is the case, or an error message otherwise.
A sneaky user could still get around this if they knew what was going on, but it should be fine for the majority of your audience.
Possible with php.
At index.php you must write
<?php
define('START', true);
include 'file.php';
At file.php need write
<?php defined('START) or die('Direct access!!'); ?>
<embed> your swf file embed
This way you will prevent direct access
You could do it with PHP by using session variables. Start the session in html1. Check for the session in html2. If it exists, display html2. If it does not, don't display html2. In either case, destroy the session in html2.
well is posible with html you has two options one is cookies and the other is local storage in html5
localStorage.hasClick = true;
alert(localStorage.hasClick);
http://www.html5rocks.com/en/features/storage
but obviously the straightforward solution is php / c# / ruby / etc...
//when I said html i refer to use only client side html/javascript

How to to add php-statements in an html file?

I tried to add the command <?php session_start(); ?> before the first line of an index.html - file. Aside from that, the file only contains html statements.
When I noticed that the php-code was not getting interpreted, I changed the ending of the file to index.php, which solved that issue.
Now I am wondering whether what I did is an ugly hack or actually an accepted practice? Is it ok to add a php-prefix to a file that is otherwise html?
Also, I am sadly still getting the following error:
session_start() [function.session-start]: Cannot send session cache limiter - headers already sent . In case my above practice is fine, what causes this error?
What you did is what you're meant to do.
Filesystem-based webservers, such as Apache and IIS (for the most part) interpret a requested file based on its file extension and process it accordingly. When a user requests a .html file then the server will return the raw bytes of the file, whereas if the user requested a .php file then it will run it through the PHP module or CGI program which generates the desired output.
You can configure your webserver (assuming you're not on a shared hosting service) to always process .html files with PHP, but it's better to hide implementation details in your URIs and use URL Rewriting instead (something Apache and IIS7+ have full support for).
With respect to the session_start() error you're getting - that's because session_start has to be called before anything is output to the client, which means that the <?php session_start() ?> part has to be at the very start of your document with no plaintext or blank-lines before it. You can have some PHP code before the call, but be sure that the PHP code is not sending any responses or headers.
Keep in mind that .php Files should parse through both PHP & HTML Tags. Placing a tag at the begining of the document is a common practice.
Also like #markus-tharkun mentioned - it really depends on what you are trying to do with the PHP code. If you just wanted to put a Timestamp in a Header of your HTML Doc it could be as simple as the following:
<h2>
<?php echo date('l jS \of F Y h:i:s A'); //Prints Date inside the H2 Tag ?>
</h2>
Once again, i could put this code anywhere inside my Tag and it would print out the current date using PHP. PHP can play interesting tricks with scope therefore it should always be paid close attention to.

PHP include content from a separate php file

A search form in "search.php" is on the vendor's server and it has been set up so my site can display it. The URL is: http://mysite.com/search.php.
The search result page is on the vendor's server also in a separate file called "result.php". It has also been configured so the URL looks like this: http://mysite.com/result.php.
I would like to insert the "search.php" form in the "result.php" file so users don't have to swtich back and forth between the pages.
I tried:
<?php
include 'http://mysite.com/search.php';
?>
It didn't work, and then I realized that I need to set "allow_url_fopen" to yes to use URL in the include statement. This is NOT something I want to do as I read other posts here there is security issue involved.
I'm not sure you can include another server's php file, allow_url_fopen and allow_url_include are to get the file output of the designated url, i mean, the final result, you won't be able to use the variables or functions from that script.
try using file_get_contents(), or if you are displaying final results anyway, you could just use an iFrame
You can just do
<?php
include $_SERVER['DOCUMENT_ROOT']"./search.php";
?>
You can try
include __dir__ . "/search.php";

Include File - session error

For a small comments widget.
I'm trying to include that widget into any .php file at wish- in the most practical way for the user with just:
<?php include "comments.php"; ?>
I'm trying to create an admin-login-panel right into the widget, to offer the logged admin to delete the posts (and more other options).
The problem is: i have now to start to use the $_SESSION, to prevent the admin having to login over and over again at each change / page-refresh.
But, using sessions inside the widget I can only see header and session WARNINGS ...olready started... ....and so on.
Is NOT an option to force the user to put into his pages top 'session_starts', I'd like to keep things simple. Just php-include the widget.
Can I still keep trying with php sessions or should I try something else?
Thanks in advance for any suggestion.
Alright, with what information you have given us, this is what your problem is: PHP Sessions uses a special cookie that is sent in a header. So you must perform a session_start(); before any other content it sent to the browser, so it can set the cookie in the header. So unfortunately, it looks like you will have to start a session outside of their including of a widget.
Why is starting the session outside of the widget not an option? Do you not have control over the other PHP pages?
It might be possible to configure your site to auto-start the session on each page.
You can typically accomplish this by modifying a PHP configuration value for the directory via a .htaccess file like so:
<IfModule mod_php5.c>
php_flag session.auto_start on
</IfModule>
Also I would recommend referrencing the root path of your website in the include, so you can use that comment include statement on any page without having to add a bunch of '../../../' to the path.
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/header.php");
?>

Categories