I have Opera 12.15 on XP with cookies enabled running on XAMPP and localhost. There is no .htaccess.
1) I can't understand why the following session variable does not persist in Opera whilst it does in the other mainstream browsers. With Opera only, if you revisit the page (via a link) after the Form has been accepted, the session variable has gone and the Form is displayed again. It's okay (i.e. the variable persists) if I just refresh the page.
2) I also have a secondary question, as you can see below I have opened a php tag and started an 'if' statement, then closed the php tag, entered some html, opened a new php tag, closed the 'if' and finally closed the second php tag. Is this valid code, I was originally taught to echo the html within the 'if' and just have one set of php tags? The former is easier and works, I saw it used elsewhere.
Thanks in advance.
<?php
// Turn on error reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Opera Session Variable</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
// create a test variable to confirm other session variables outside of Form are persisting
$_SESSION['test'] = 'Test';
// function to print session variables
function print_array( $_SESSION )
{
echo '<pre>$_SESSION<br />' . "\n";
print_r($_SESSION);
echo "</pre>\n";
}
// process the submitted form
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if (isset($_POST['formaccept'])) {
$_SESSION['formaccepted'] = $_POST['formaccept'];
}
}
// print the session variables
print_array( $_SESSION );
// only display the form if it has not previously been accepted in this session
if (!isset($_SESSION['formaccepted'])) {
?>
<p><b>This parargraph should only display if the form has not been accepted in the current session.</b></p>
<br />
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" name="formaccept" value="Accept" />
</form>
<?php
}
?>
</body>
</html>
Must be the way opera handles the cache, I can't see any error with your code.
As for your second question, that syntax works but is not usually recommended, since it makes the layout dirty being full of snippets.
Related
So I'm trying to learn html+php but it seems like I've hit a wall. If I use the GET method in my html form, parameters are sent to my php file just fine, but if I try to do the same using the POST method no parameters are sent.
#Edit: I've taken down the initial code sample displayed here as I found out its not a problem specific to that code. Instead I'm posting a basic form and a basic php script that have the same problem:
HTML FILE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="testingForm.php" method="POST">
INPUT: <input type="text" id="iTesting" name="nTesting"/><br/>
<input type="submit" value="SUBMIT"/>
</form>
</body>
</html>
PHP FILE:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title></title>
</head>
<body>
<?php
/* THIS WORKS: */
/*if (isset($_GET["nTesting"]))
echo "It is working! ".$_GET["nTesting"];
else
echo "It is NOT working! input: ".$_GET["nTesting"];
echo "<br/>".$_SERVER['REQUEST_METHOD']."<br/>";
echo "<br/>".var_dump($_GET);//*/
/* THIS DOESN'T: */
if (isset($_POST["nTesting"]))
echo "It is working! ".$_POST["nTesting"];
else
echo "It is NOT working! input: ".$_POST["nTesting"];
echo "<br/>".$_SERVER['REQUEST_METHOD']."<br/>";
echo "<br/>".var_dump($_POST);//*/
?>
</body>
</html>
As stated before, if I change the form method to GET, I get no problem at all. However, data doesn't seem to be sent when using POST method.
This is the output using the GET method:
It is working! input: test
GET
array(1) { ["nTesting"]=> string(4) "test" }
This is the output using the POST method:
It is NOT working! input:
POST
array(0) { }
Also, using the developers tool I can see there is a parameter nTesting:test in the formData section of the network tab. Yet, nothing is displayed.
If you're using Chrome
Go to index.html
Press f12. Developer tools will show up
Click Network
Tick Preserve Log and Disable Cache (I usually just do it that way)
From index.html click the submit button (do not close dev tools)
Go back to developer tools click 'teste.php'
Click headers, then expand general. You will see 'Request Method'. It should be POST
After working with #MuriloRM we ended up with the fundamental bug with PHPStorm
Please vote up the resolution of the issue
https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000097930-Can-not-use-POST-method-in-PhpStorm
I am trying to change the page when the user hits the login button. When the login button is hit currently the page just refreshed the user is not redirected to the new page. I created the session before any of the code for the page. I am wondering if it has to do with the location of my header command.
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login</title>
</head>
<body>
<form action="" method="post">
<br>Name: <input type="text" name="NameTextBox"><br>
<br>What grade are you currently in?: <input type="number" name="GradeTextBox"><br>
<br><button name="Login" type="submit">Login</button></br>
</form>
<?php
if (isset($_POST["Login"])) {
$_SESSION["start"] = $_SERVER['REQUEST_TIME'];
//echo "This session is beginning at ".$_SESSION["start"]."<br /><br />";
}
if(isset($_POST["Login"])){
if($NameTextBox = "Phydeaux"){
//echo"Good Name!";
PassLogin();
}
elseif($NameTextBox = "Rover"){
//echo"Good Name!";
PassLogin();
}
elseif($NameTextBox = "Spot"){
//echo"Good Name!";
PassLogin();
}
else{
echo"You cannot login!";
}
}
function PassLogin()
{
//print '<script type="text/javascript">';
//print 'alert("Running PassLogin Function")';
//print '</script>';
$_SESSION["ReadingGrade"] = "Fail";
$_SESSION["WritingGrade"] = "Fail";
$_SESSION["MathGrade"] = "Fail";
$_SESSION["Grade"] = $GradeTextBox;
$_SESSION["Name"] = $NameTextBox;
Header('Location: Reading.php');
}
if (isset($_POST["Login"])){
//echo "Login has been pressed";
}
?>
</body>
</html>
There are several synthax and technical problems with this code. In addition to what AlexP said, you must observe that you cannot send the headers when you have already sent some output. The headers must be sent before any output, what is the same reason you had to put your session_start() in the beginning.
That being said, you should also make the login script before the HTML part, where your session_start() is, so your redirect header to Reading.php can work too. Or you can workaround that by placing a ob_start() in the beginning of the page, it will buffer the output preventing it from being sent before the script ends, this way you can call a header() wherever you like.
And talking about the header, the function is header(), not Header(). There is no native function named Header() in PHP. Function names are case sensitive.
In addition, you shouldn't use action="" in your <form>. Just suppress this attribute to make it post to the same page, it will make your code work don't matter what your php file name is. If you use action="" it will post to the index.php instead of login.php.
I also noticed you are using Reading.php (with capital letter) and login.php. I suggest you normalize all your file names to lower case, because if not you can have problems when porting this code to other systems. To Windows, Reading, reading, READING and ReAdInG are the same thing, to Linux it is not.
You cannot modify the header information having already output your HTML. Move your HTML underneath the PHP header call.
The documentation says:
header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP
Also, you are assigning the string value when you use $NameTextBox = "Phydeaux", rather than conditionally checking it.
You should use the == double equals instead
if(isset($_POST["Login"])){
$NameTextBox = $_POST['NameTextBox']; // $NameTextBox is now the posted value
if($NameTextBox == "Phydeaux"){ // double equals checks the value of the variable
<form action="" method="post">
Where will go your posts?
I will offer you this:
1- Write your PHP codes another page and named is "login.php"
2- Write your form action: <form action="login.php" method="post">
Consider the following situation. User submits a form which contains a file input field. Then, after processing the upload, server redirects browser to the address containing #hash-part. If the browser is IE7/8, it will discard the part after hash mark (including the # itself). Moreover, it will do this irrespective of whether actual file upload took place or user just left the file field empty. The following code illustrates it.
<? if (isset($_POST['sent'])) {
header("Location: " . basename($_SERVER['PHP_SELF']) . "#test");
die();
}
?><!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="sent" value="1" />
<input type="file" name="test" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
After form is submitted, IE 7/8 shows the same address in the address bar as before while other browsers (and IE 9/10) get properly redirected to the index.php#test. When the file input is replaced with text input, the problem is gone.
Is it a bug or some kind of security measure? Is there a workaround?
I ended up using double redirect on IE 7/8. I replaced
header("Location: " . basename($_SERVER['PHP_SELF']) . "#test");
with
if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/(^|[^a-zA-Z])(MSIE|msie) [678]($|[^\d])/', $_SERVER['HTTP_USER_AGENT'])) // If IE 6, 7 or 8
header("Location: redirect.php?to=" . urlencode(basename($_SERVER['PHP_SELF']) . "#test"));
else // For sane browsers
header("Location: " . basename($_SERVER['PHP_SELF']) . "#test");
and created a simple redirection script redirect.php:
<? if (isset($_GET['to']))
header('Location: ' . $_GET['to']);
Thats an odditiy of internet explroer I had to deal with when implementing an oauth flow with javascript.
It appears that it is possible to work around the problem by placing a trailing slash directly in front of the hashtag. so instead of file.php#werewwer make file.php/#werwer
However I do not know why... I think its a bug.
The hashtag is intendeed to never be trasmitted to the server. It is client side only. I think IE just removes it early...
Another possibility is to use a meta redirect instead of a header redirect. That seems to work. You can also append to the url using javascript... Dont know whether this is suitable in your use case.
I'm currently working on a site that has a log-in (username and password) - The password protection is done by the operating system within the web server at folder level called a Realm within the OS. For now this will have to do, until we figure out a proper PHP log in system.
The code below, is based on a previous question on the stack overflow.
I'm using 3 files (See code snippets at the bottom).
The process is:
- Click Log In button on index.php
- Enter username and password to access authenticate index file.
- Click log out button, which references the logout.php file - it SHOULD clear the cache and return the user to the top level index.
It doesn't 'destroy the session' in the sense that you're not asked to re-enter the password when prompted to, which is essentially what I want to happen.
My minimal knowledge of php leaves me a little bit stumped here.
index.php (top level file with log in button)
<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test</title>
</head>
<body>
Log In Btn
</body>
</html>
authenticate/index.php (This folder is password protected - contains the index file with the log out button which links to the logout.php file)
<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Log out</title>
</head>
<body>
Log Out Btn
</body>
</html>
authenticate/logout.php
<?php
session_start(); //to ensure you are using same session
session_destroy(); //destroy the session
header("location:/index.php"); //to redirect back to "index.php" after logging out
exit();
?>
The folder being password protected has nothing to do with PHP!
The method being used is called "Basic Authentication". There are no cross-browser ways to "logout" from it, except to ask the user to close and then open their browser...
Here's how you you could do it in PHP instead (fully remove your Apache basic auth in .htaccess or wherever it is first):
login.php:
<?php
session_start();
//change 'valid_username' and 'valid_password' to your desired "correct" username and password
if (! empty($_POST) && $_POST['user'] === 'valid_username' && $_POST['pass'] === 'valid_password')
{
$_SESSION['logged_in'] = true;
header('Location: /index.php');
}
else
{
?>
<form method="POST">
Username: <input name="user" type="text"><br>
Password: <input name="pass" type="text"><br><br>
<input type="submit" value="submit">
</form>
<?php
}
index.php
<?php
session_start();
if (! empty($_SESSION['logged_in']))
{
?>
<p>here is my super-secret content</p>
<a href='logout.php'>Click here to log out</a>
<?php
}
else
{
echo 'You are not logged in. Click here to log in.';
}
logout.php:
<?php
session_start();
session_destroy();
echo 'You have been logged out. Go back';
Obviously this is a very basic implementation. You'd expect the usernames and passwords to be in a database, not as a hardcoded comparison. I'm just trying to give you an idea of how to do the session thing.
Hope this helps you understand what's going on.
First give the link of logout.php page in that logout button.In that page make the code which is given below:
Here is the code:
<?php
session_start();
session_destroy();
?>
When the session has started, the session for the last/current user has been started, so don't need to declare the username. It will be deleted automatically by the session_destroy method.
if(isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header('location:login.php');
}
The if block of the Global array $_GET check if the logout var is set in the url
Then, the session destroy function is called
And then, the global session array value username is removed/deleted the header function will redirect you back to login page
if(isset($_POST['logoutButtonName'])) {
session_destroy();
unset($_SESSION['nameOfSessionToBeDestroyed']);
header('location:login.php');
}
Header should then redirect you to your desired page
If you can get this simple SESSION VARIABLES example to work, I'll hug you!
I can't get Session Variables to work at all on my site. I'm running php5, on Windows 7, using Chrome browser.
Here's the send page:
<?php
session_start();
$red='red';
$blue='blue';
$green='green';
$SESSVARS=array($red,$blue,$green);
$_SESSION['USERVARS']= $SESSVARS;
?>
<p>Set Sessionvars</p>
<form action="SessVarCheck.php" method="post">
<input name="Submit" type="submit">
</form>
Here's the result page:
<?php
session_start();
echo "val 1:".$_SESSION['USERVARS'][0];
echo "val 2:". $_SESSION['USERVARS'][1];
echo "val 3:". $_SESSION['USERVARS'][2];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SessVarCheck.php</title>
</head>
<body>
The Result page
</body>
</html>
I get empty on all three echos.
Any ideas would be welcome!
Make sure that the call to session_start() happens before any page contents are output, on both pages. (See "Note" section here)
(I assume you may already know about this, but given that I don't see a "<html>" on the send page I thought there might be more to that script. Also, I don't know how sensitive this requirement is - just the spaces before the php tag might be enough to be a problem.)
Try a few things:
1) do a var_dump($_SESSION) on your results page, to see what the raw contents of the session are
2) Verify that the sessions are working correctly. Add echo "SessionID: " . session_id(); to both scripts, somewhere AFTER the session_start() calls. If you don't get the same session ID on each page, you're getting a new session each time and it's most likely a cookie problem.