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
Related
I know similar questions have been asked, but unfortunately I didn't manage to solve the problem after going through them.
Assuming this situation: In one.php I'm retrieving some data from an input field and saving it as a variable and later on I require two.php
one.php
$rejon = $_POST['rejon'];
require 'two.php';
two.php
--here I would like to use $rejon ---
When I try to use $rejon in two.php, it doesn't work (I try to insert it into a database to be exact). On the other hand, if I don't require the two.php but instead paste the code into one.php, it works.
I don't understand why this happens. W3schools claims that "The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement." - http://www.w3schools.com/php/php_includes.asp
but it doesn't seem to work like a copy as manualy copying gives other results (variable $rejon is accesible).
1) What exactly does require do and what are its limitations?
2) Most importantly - how do I retrieve that $rejon variable in two.php?
Works for me:
$ cat one.php
<?php
$rejon = 'this value came from POST';
require 'two.php';
$ cat two.php
<?php
echo $rejon . PHP_EOL;
$ php one.php
this value came from POST
The W3Schools description is, unsurprisingly, misleading. Nothing is copied. The contents of the file are read, evaluated, and inserted at the point of the require. With respect to variables, the PHP manual says this:
When a file is included, the code it contains inherits the variable
scope of the line on which the include occurs. Any variables available
at that line in the calling file will be available within the called
file, from that point forward. However, all functions and classes
defined in the included file have the global scope.
Which is why my example above works as it does.
To diagnose this issue, continue to simplify your code to reduce it to the simplest possible example. If you're trying to use $rejon in a function inside of two, then you need to make the variable global. Like:
global $rejon;
$rejon = $_POST['rejon'];
// now you have $GLOBALS['rejon'] everywhere
Side note, $_SESSION should not be necessary unless you're crossing a page refresh boundary.
You can do this by the following two ways
1.Using Session
You can store the data in the session and than you can use it in the another file two.php
one.php
<?php
session_start();
$rejon = $_POST['rejon'];
$_SESSION['rejon'] = $rejon;
?>
two.php
<?php
session_start();
echo $_SESSION['rejon'];
?>
2. Including that file
I have found that you are including the file two.php in your script. If you are including this file than you can directly use the variable $rejon
two.php
<?php
echo $rejon;
?>
You can use sessions http://php.net/manual/en/book.session.php or a constant http://php.net/manual/en/language.constants.php.
Utkarsh already provided some examples for sessions.
To define a constant you use the define() function.
define('CONSTANT_NAME', CONSTANT_VALUE);
As long as your constant is defined and included (if in another file) before you use it you can then call CONSTANT_NAME in your code to get the value.
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
In my php code there is a section which needs to be retrieved from another php file.
I tried accomplishing this by:
include "teams.php?id=".$matchid;
and in the teams.php
$matchid = $_GET['id'];
echo "MATCH ID IS ".$matchid;
The problem is when i open teams.php?id=".$matchid directly it displays the match id fine
however the include doesn't work - i checked the source code of the original page - no code is being inserted. Is there a way to do what i want? I need to get php code from another file whilst passing 2 variables onto that file
Problem
The problem is related to what $_GET really contains:
An associative array of variables passed to the current script via the URL parameters. (...)
And you do not pass $matchid to the script through URL... And you should not in this case.
Solution
But there is a way. PHP does not separate global variables among files, so variables available in one file are available also in the one included:
in file no. 1:
// Assume $matchid is defined
include "teams.php";
in file no. 2 (the one included):
// No need to redefine $matchid - it was defined in the first file
echo "MATCH ID IS ".$matchid;
Also make sure you add <?php at the beginning of the file (the closing tag is not required). Otherwise it will be treated as text and not executed.
The problem is that you aren't loading that page in the browser when you call the include function, so the variable you are appending is not being processed as a URL query param. You are really just taking everything inside teams.php and dumping it into the other file (the one including teams.php) at that position.
If you want to effectively pass something into teams.php then just declare a variable before the include.
Check out http://php.net/manual/en/function.include.php and all will become clear.
That's not how include's work. When you include a file, it's code is executed as if it was written in the same file it's being included in. So teams.php will have the variable $matchid when the including file has that variable, no need to pass it in. Also the way you called the include was incorrect. Doing what you did causes php to look for a file in the current directory called 'teams.php?id=0' (replace 0 with the $matchid value). This file does not exist, 'teams.php' exists, not the URI. It is possible to specify a url by prefixing it with 'http://' however the result would work with the code in teams.php as it would expect to be able to read the php source.
You can do like this include "include "teams.php?id={$matchid}"; and
$matchid = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_STRING);
echo "MATCH ID IS {$matchid}";
If You will use this code, you will be safe from Injects too!
I hope you will apreciate this.
I'm currently working on a site where I'm trying to make use of the session variables.
I have a controller script (index.php) that begins with session_start(); and has two different HTML files included within if statements. Everything works all groovy when I go to /quote/index.php, the session variables that I've set are echoed on the page as expected, however if I remove 'index.php*' from the URL so it points to just /quote the page loads however none of the session variables show up.
I'm not using session_destroy anywhere in my scripts and the session variables aren't echoing '0' so I'm fairly sure they aren't being unset, it seems as though they are just ignored without the filename in the URL!
Any insight as to why this is occuring would be awesome,
Thanks
/quote/index.php (with extraneous bits removed):
<?php
session_start();
if (isset($_GET['form']))
{
include 'form.html.php';
exit();
}
if (isset($_GET['fetchquote']))
{
$width = mysqli_real_escape_string($link, $_POST['width']);
$height = mysqli_real_escape_string($link, $_POST['height']);
$_SESSION['height'] = $height;
$_SESSION['width'] = $width;
}
include 'quote.html.php';
?>
The session variables are echoed in quote.html.php
what are the two file names?
seems that one of the file that you are including is named index.html and resides in the mysite.com/quote/ itself. And if I am not wrong, if in a directory there are index.html and index.php then the index.html is loaded by default unless the file is explicitly specified in the url. So it seems in your case when you are not specifying the index.php explicitly,the index.html is being loaded.Of course this is the case only if there is an index.html there in the directory.
Make sure you are also using session_start() at the top of the PHP pages where you want to echo the session variable. And make sure index.php is the only index in your root.
You are checking if an option is set via the GET method. Where is your form using the GET method?
Post your entire script and you'll get much better answers.
This has probably something to do with the validity scope of the session ID cookie. Because if the cookie path is set to /quote/, the cookie will only be available in /quote/ and beyond.
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.