I want to generate a random key for the user to use during registration. The code compares the generated key with the user input but the key gets regenerated when the user submits the form, so they are never the same. I tried to protect the generator function by checking if it was already generated but it didn't work. Then, I tried to use session as well, which didn't work either. Here's the code which always produces "fail" rather than "success":
Edit: I made some corrections according to your comments.
<?php
session_start();
$_SESSION['key'] = randomKey();
$key1 = $_SESSION['key'];
error_reporting(E_ALL);
ini_set('display_errors', 1);
function randomKey() {
if (empty($_SESSION['key'])) {
$key = uniqid();
$_SESSION['key'] = $key;
return $key;
} else {
return $_SESSION['key'];
}
}
if(isset($_POST['submit']))
{
$input = $_POST['inputKey'];
if (strcmp($input,$_SESSION['key']) == 0) {
echo 'success';
} else {
echo 'fail';
}
}
?>
<html>
<head>
</head>
<body>
<form method="POST" action="">
<table border="0">
<tr>
<td>Your key:</td>
<td>
<b>
<?php echo $key1; ?></b>
</td>
</tr>
<tr>
<td>Enter your key:</td><td><input type="text" name="inputKey"></td>
</tr>
<tr>
<td><input id="button" type="submit" name="submit" value="Sign-Up"></td>
</tr>
</table>
</form>
</body>
</html>
You stated in comments that there was now a headers sent warning.
The following link will help you figure out why that is.
Warning: Cannot modify header information - headers already sent by ERROR
However, I did find a slight bug in your code.
Even upon success, your code will produce the same key when the page is reloaded; where "randomness" would literally be "thrown out the window", since that is what the whole purpose is with your usage of the unique function.
You need to destroy the session on success.
Here is what your code should look like and using session_destroy():
if(isset($_POST['submit']))
{
$input = $_POST['inputKey'];
if (strcmp($input,$_SESSION['key']) == 0) {
echo 'success';
session_destroy();
} else {
echo 'fail';
}
}
Reference:
http://php.net/manual/en/function.session-destroy.php
Once you've corrected the problem with the headers being sent, consider redirecting somewhere (or the same page for that matter), after succession.
You can do this with a header, but you cannot echo and use a header at the same time, so remember that.
Reference:
http://php.net/manual/en/function.header.php
and be sure to add an exit; after the header (as stated in the manual), otherwise your code may want to continue to execute and if you have more code below it.
Sorry, for the delay. I think I've found a workaround. I just posted the form to another page which grabs and controls the information. That way, the random code isn't regenerated. So, I have two pages instead of one.
test1.php:
<?php
$key = randomKey();
function randomKey() {
$i = 0;
do {
$key = uniqid();
return $key;
} while ($i > 0);
}
?>
<html>
<head>
</head>
<body>
<form method="POST" action="randomkey2.php">
<table border="0">
<tr>
<td>Your key:</td>
<td>
<b>
<?php echo $key?></b><input type="hidden" name="keyHidden" value="<?php echo $key;?>" />
</td>
</tr>
<tr>
<td>Enter your key:</td><td><input type="text" name="inputKey"></td>
</tr>
<tr>
<td><input id="button" type="submit" name="submit" value="Sign-Up"></td>
</tr>
</table>
</form>
</body>
</html>
test2.php:
<?php
$input = $_POST['inputKey'];
$key = $_POST['keyHidden'];
$control = strpos($key, $input);
if($control !== false)
{
echo 'success';
} else {
echo 'fail';
}
?>
This way, I also don't have to use session globals. Well, this may look a bit odd but the process is normally a bit more complicated and it requires to give some instructions. So, subdividing the process isn't a problem for me and it works. I'm sorry if I've wasted your time, I've just started to fiddle with PHP. Thank you for your corrections and suggestions.
Related
I want to learn how to keep value after a post request.
In my code, I have these variables:
myvar
myans
result
myvar is a random val between 0-5. I will get myans from my input if myans == myvar, then result will be true (else it will be false).
I see myvar before I submit my ans just for trying, but although I see the var when I send it, what I see it is sometimes false and sometimes true. What am I missing?
example.php:
<?php
session_start();
if (!isset($_COOKIE['result'])) {
setcookie("result","EMPTY");
}
setcookie("myvar",rand(0,5));
if (!empty($_POST)) {
if ($_POST['myans'] == $_COOKIE['myvar']) {
setcookie("result","TRUE");
}
else {
setcookie("result","FALSE");
}
}
?>
<html>
<head>
<title>Example</title>
</head>
<body>
<form method="post" action="">
<?php echo $_COOKIE['myvar'] ?>
<input type="text" name="myans">
<input type="submit" value="Send">
<?php echo $_COOKIE['result'] ?>
</form>
</body>
</html>
The problem you were having was caused by your random number generator making creating a new number before comparing to the original. I made some changes to only set "myvar" if it's empty. this will only set it once, but at least you can see your code working as intended. I recommend you plan out what exactly what functionality you want before adding to it.
I also switched you out from the "$_COOKIE" var to "$_SESSION" vars. They are hidden from the client, and by php default last about 24 minutes if not refreshed. I don't know what you plan on using this for, but using cookies allows the end user to manipulate that info. If this is not a concern for you, by all means just uncomment the "setcookie()" lines.
<?php
session_start();
if (!isset($_SESSION['result'])) {
//setcookie("result","EMPTY");
$_SESSION["result"] = "EMPTY";
}
//setcookie("myvar",rand(0,5));
if(empty($_SESSION["myvar"])){
$_SESSION["myvar"] = rand(0,5);
}
//
if (!empty($_POST)) {
if ($_POST['myans'] == $_SESSION['myvar']) {
//setcookie("result","TRUE");
$_SESSION["result"] = "TRUE";
} else {
//setcookie("result","FALSE");
$_SESSION["result"] = "FALSE";
}
}
?>
<html>
<head>
<title>Example</title>
</head>
<body>
<form method="post" action="">
<?php echo isset($_SESSION['myvar']) ? $_SESSION['myvar'] : ""; ?>
<input type="text" name="myans">
<input type="submit" value="Send">
<?php echo isset($_SESSION['result']) ? $_SESSION['result'] : ""; ?>
</form>
</body>
</html>
The following code is supposed to check accoroding to the superglobals and output one text field for username. Instead it gives out 3. I checked the code thoroughly, but cannot seem to find any error. I am relatively new to PHP, if someone could guide me.
<? session_start();
// for demo, else these would be in some database
define("USER", "abcde");
define("PASS", "zxcvb");
if (isset($_POST["user"]) && isset($_POST["pass"]))
{
if ($_POST["user"] == USER && $_POST["pass"] == PASS)
{
$_SESSION["authenticated"] = true;
setcookie("user", $_POST["user"], time() + 7 * 24 * 60 * 60);
$host = $_SERVER["HTTP_HOST"];
$path = rtrim(dirname($_SERVER["PHP_SELF"]), "/\\");
header("Location: http://$host$path/home.php");
exit;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Log In</title>
</head>
<body>
<form action="<?= $_SERVER["PHP_SELF"] ?>" method="post">
<table>
<tr>
<td>Username:</td>
<td>
<? if (isset($_POST["user"])): ?>
<input name="user" type="text" value="<?= htmlspecialchars($_POST["user"]) ?>">
<? elseif (isset($_COOKIE["user"])): ?>
<input name="user" type="text" value="<?= htmlspecialchars($_COOKIE["user"]) ?>">
<? else: ?>
<input name="user" type="text" value="">
<? endif ?>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input name="pass" type="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Log In"></td>
</tr>
</table>
</form>
</body>
</html>
You are using short tags (<?) rather than formal tags, which may not be enabled in your php.ini
If you have access to change the php.ini, change short_open_tag = Off or short_open_tag = 0 to short_open_tag = On or short_open_tag = 1 respectively.
Alternatively, add the line <?php ini_set('short_open_tag','1'); ?> at the beginning of the file, but this is less than ideal, and would be better by changing all <? to <?php
Not possible. if will not execute multiple paths, e.g:
php > if (1==1) { echo 'foo'; } else if (1==1) { echo 'bar'; }
foo
php >
even though both conditions evaluate to true, only the FIRST matched condition has its code executed, and then the if is done.
If you get all three fields, then most like your PHP is misconfigured and NONE of the php is being executed, and you're getting the raw php output. Since browsers ignore/hide unknown tags, the PHP code is simply not rendered and you see all of the non-php code. e.g. check your browser's "view source", and you'll see the php code there, which means you've got major problems on the server.
To execute PHP on localhosts, like XAMP and WAMP, you must use <?php at the beginning of the document, or it will output the script like a <p> element in HTML.
I think your server does not support short tags.
You should try to replace <? by <?php
See this documentation to know more about that.
You can of course allow short tags but it is really not recommended.
for some reason when I click login it dose not work gives me a error, its the button click event related to the form. ive got a url.
When click login you are meant to be able to login but it dose not work.
im quite new to using this level of php so any help would be wonderful/
http://stuweb.cms.gre.ac.uk/~ob219/logsystem/
password is password
and user beep
Code for index
<?php
session_start();
$errorMessage = '';
if (!empty($_POST['user_name']) && !empty($_POST['user_password']){
include 'library/connect.php';
$user_name = $_POST['user_name'];
$user_password = $_POST['user_password'];
$sql = "SELECT user_id FROM Login WHERE user_name = '$user_name' AND user_password = '$user_password'";
$result = mysql_query($sql) or die('Query failed. ' . mysql_error());
$row = mysql_fetch_array($result);
if (mysql_num_rows($result) == 1) {
$_SESSION['user_logged_in'] = true;
$_SESSION['id'] = "$row[user_id]";
header("Location: user.php");
}
else {
$errorMessage = 'Sorry, wrong username / password';
}
include 'library/close.php';
}
?>
<html>
<head>
<title>login</title>
</head>
<body>
<?php
if ($errorMessage != '') {
?>
<p align="center"><strong><font color="998000"><?php echo $errorMessage; ?></font></strong></p>
<?php
}
?>
<p align="center"><b>Passwords and user names stored in database with personalised message</b></p>
<form name="formLogin" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table width="400" border="1" align="center" cellpadding="2" cellspacing="2">
<tr>
<td width="150">User name</td>
<td><input name="user_name" type="text" id="user_name"></td>
</tr>
<tr>
<td width="150">Password</td>
<td><input name="user_password" type="password" id="user_password"></td>
</tr>
<tr>
<td width="150"></td>
<td><input name="btnLogin" type="submit" id="btnLogin" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
The string you are posting to is literally:
<?php echo $_SERVER['PHP_SELF']; ?>
If you just want to post to the same page, you can just leave out the action element from the form. (Is it a good practice to use an empty URL for a HTML form's action attribute? (action=""))
After further searching into what is going on, I figured it out!
You are using
http://stuweb.cms.gre.ac.uk/~ob219/logsystem/index.html
you need to change your file to (.php)
http://stuweb.cms.gre.ac.uk/~ob219/logsystem/index.php
Also yes you do have apache installed! See here
Your PHP isn't being processed. It's just being printed inline with the HTML. Since you have
open and close php statements, my guess is that you may have this file saved as index.html and don't have Apache set to parse HTML as PHP.
View your page source to confirm.
Try saving your file as index.php. You may also need to add this to a .htaccess file in the same folder:
DirectoryIndex index.php
Few corrections:
Firstly as #Advocation said leave out the action element empty if you want to post in the same page.
Your missing brackets in if statement.
Change this:
if (!empty($_POST['user_name']) && !empty($_POST['user_password']){
To:
if ((!empty($_POST['user_name']) && !empty($_POST['user_password'])){
Use php isset() function to check whether the variables are set or not and use htmlspecialchars($_SERVER["PHP_SELF"]) to prevent $_SERVER["PHP_SELF"] exploitation.
Besides to prevent sql injection, you should use PDO or Mysqli and you can use session_id() function and can bind IP address to prevent session hijacking.
$ip = getenv ( "REMOTE_ADDR" );
Like quasivivo said, none of your php is being processed by your server, I posted a picture to show you what is going on. Are you sure you have apache installed? and not ASP?
As you can see, all your script isn't processed by your server! This is a major problem, make sure you don't have any passwords variables, because anyone can see them. like for example:
$db_password = 'ilovelamp';
It is working in my server correction the lines
if (!empty($_POST['user_name']) && !empty($_POST['user_password']))
You have forgotten to close if condition ")"
i have this code,why my header location not working?
its a form of updating and editing and deleting some pages in my control panel...and i have an index.php file in the same folder of form.php...any help please?()i tryed to put the header after the editing and deleting...and still go to the form page not the index...
<?php
include "../../includes/site_includes.php";
//send
if ((isset($_POST["send"])) && ($_POST["send"] == 1)) {
$pageid = $_POST["page_id"];
$pagetitle = $_POST["page_title"];
$nameinmenu = $_POST["page_menu_name"];
$nameinurl = $_POST["page_name_url"];
$link = $_POST["page_link"];
$picture = $_POST["page_pic"];
$desc = $_POST["page_desc"];
$content = $_POST["page_content"];
}
if ((isset($_POST["act"])) && ($_POST["act"] == "add")) {
$sql = insertpage();
if ($result = $mysqli->prepare($sql)) {
$result->bind_param("sssssss", $pagetitle, $nameinmenu, $nameinurl, $link, $picture, $desc, $content);
$result->execute();
$result->store_result();
$rows = $result->num_rows;
}
}
////edit
if ((isset($_GET["act"])) && ($_GET["act"] == "edit")) {
$sql = getfrompages();
if ($result = $mysqli->prepare($sql)) {
$rekza = $_GET["id"];
$result->bind_param("i", $rekza);
$result->execute();
$result->store_result();
$rowsZ = $result->num_rows;
}
if ($rowsZ > 0) {
$row = fetch($result);
$pageid = $row[0]["page_id"];
$pagetitle = $row[0]["page_title"];
$nameinmenu = $row[0]["page_menu_name"];
$nameinurl = $row[0]["page_name_url"];
$link = $row[0]["page_link"];
$picture = $row[0]["page_pic"];
$desc = $row[0]["page_desc"];
$content = $row[0]["page_content"];
}
}
if ((isset($_GET["act"])) && ($_GET["act"] == "delete")) {
$thedelid = $_GET["id"];
$sql2 = delpage();
if ($result2 = $mysqli->prepare($sql2)) {
$result2->bind_param("i", $thedelid);
$result2->execute();
$result2->store_result();
$rowsZ2 = $result2->num_rows;
}
}
header('location: index.php');
exit();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> pages add </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
</head>
<body>
<form method="post" action="">
<table>
<tr>
<td style="font-weight:bold;">title</td>
<td><input type="text" name="page_title" value="<?=$pagetitle?>" /></td>
</tr>
<tr>
<td style="font-weight:bold;">name in menu</td>
<td><input type="text" name="page_menu_name" value="<?=$nameinmenu?>" /></td>
</tr>
<tr>
<td style="font-weight:bold;">name in url</td>
<td><input type="text" name="page_name_url" value="<?=$nameinurl?>" /></td>
</tr>
<tr>
<td style="font-weight:bold;">link</td>
<td><input type="text" name="page_link" value="<?=$link?>" /></td>
</tr>
<tr>
<td style="font-weight:bold;">picture</td>
<td><input type="text" name="page_pic" value="<?=$picture?>" /></td>
</tr>
<tr>
<td style="font-weight:bold;">description</td>
<td><textarea name="page_desc"><?=$desc?></textarea></td>
</tr>
<tr>
<td style="font-weight:bold;">content</td>
<td><textarea name="page_content"><?=$content?></textarea></td>
</tr>
<tr>
<td colspan="2">
<input type="hidden" name="send" value="1" />
<input type="hidden" name="act" value="<?=$_GET["act"]?>" />
<input type="hidden" name="page_id" value="<?=$pageid?>" />
<input type="submit" value="add" /></td>
</tr>
</table>
</form>
</body>
</html>
solved:
with # Mihai Iorga code i added ob_start();
That is because you have an output:
?>
<?php
results in blank line output.
header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP
Combine all your PHP codes and make sure you don't have any spaces at the beginning of the file.
also after header('location: index.php'); add exit(); if you have any other scripts bellow.
Also move your redirect header after the last if.
If there is content, then you can also redirect by injecting javascript:
<?php
echo "<script>window.location.href='target.php';</script>";
exit;
?>
Try adding ob_start(); at the top of the code i.e. before the include statement.
just use ob_start(); before include function it will help
Remove Space
Correct : header("Location: home.php"); or header("Location:home.php");
Incorrect : header("Location :home.php");
Remove space between Location and : --> header("Location(remove space): home.php");
The function ob_start() will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. So browser will not receive any output and the header will work.Also we should make sure that header() is used on the top of the code.
ob_start();
should be added in the line 1 itself.
like in below example
<?php
ob_start(); // needs to be added here
?>
<!DOCTYPE html>
<html lang="en">
// your code goes here
</html>
<?php
if(isset($_POST['submit']))
{
//code to save data in db goes here
}
header('location:index.php?msg=sav');
?>
adding it below html also doesnt work. like below
<!DOCTYPE html>
<html lang="en">
// your code goes here
</html>
<?php
ob_start(); // it doesnt work even if you add here
if(isset($_POST['submit']))
{
//code to save data in db goes here
}
header('location:index.php?msg=sav');
?>
I use following code and it works fine for me.
if(!isset($_SESSION['user'])) {
ob_start();
header("Location: https://sitename.com/login.php");
exit();
} else {
// my further code
}
I had same application on my localhost and on a shared server. On my localhost the redirects worked fine while on this shared server didn't. I checked the phpinfo and I saw what caused this:
While on my localhost I had this:
So I asked the system admin to increase that value and after he did that, everything worked fine.
for me just add ob_start(); at the start of the file.
It took me some time to figure this out: My php-file was encoded in UTF-8. And the BOM prevented header location to work properly. In Notepad++ I set the file encoding to "UTF-8 without BOM" and the problem was gone.
Check if below are enabled
bz, mbstring, intl, ioncube_loader and Json extension.
It should be Location not location:
header('Location: index.php');
In my case i created new config file with function 'ob_start()' and added this to my .gitignore file.
I use this
header("Location:comments.php");
And it solve out..
In your HTML code, you are using a form and setting action to "", which I understand takes precedence over a header within the form.
I found rather using the action element within the form instead of header Location is one option. I assume you want different options on the link, thus the variable.
<?php $nextLink = "index.php"; ?>
<form method="post" action="<?php echo $nextLink; ?>">
I suggest placing the variable outside a $_POST to start testing with.
In my case, it was extra spaces after ?>
Removed the spaces, and voila it worked.
in my case i just added ob_start(); before include anything and it worked !
Create config.php and put the code it will work
Good day!
I am a newbie in php..
I made a form using html where I can input the grade of the student.
Then a php page to know if they pass or not.
My problem is how can i send back the reply on the html page. Example how can I send the You Failed status on my html page under the form.
My code is as follows:
<HTML>
<BODY>
Please enter your grade (0-100 only):
<FORM ACTION="grade2.php" METHOD="POST">
<table border = "1">
<tr>
<td>Grade</td>
<td><input type="text" name="grade" /></td>
</tr>
</table>
<INPUT type="submit" name="submit" value="grade">
</BODY>
</HTML>
<?php
$grade = $_POST['grade'];
IF ($grade>=0 && $grade<=50){
print "You failed";
} ELSE IF ($grade<=60){
print "You Passed! But Study Harder!";
} ELSE IF ($grade<=70){
print "Nice";
} ELSE IF ($grade<=80) {
print "Great Job";
} ELSE IF ($grade<=90){
print "Excellent";
} ELSE IF ($grade<=100){
print "God Like!";
} ELSE {
print "Invalid Grade!";
}
?>
Just use one PHP page containing both the form and message. For example (assuming your file is grade.php)
<form action="grade.php" method="post">
<!-- form elements, etc -->
</form>
<?php
if (isset($_POST['grade'])) {
$grade = (double) $_POST['grade'];
// if statements, print message, etc
}
?>
The only issue I see that may prevent it from showing up now is that the print statements are outside the <body> tags.
Move
</BODY>
</HTML>
to the very end of the file
There's two ways that you can use.
You can echo the script filename:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Or just leave the action field blank. The page will then re-load on itself.
<form action="" method="post">
At the top of your script, test for the presence of POST variables on the reload:
if (isset($_POST['submit'])) {
And that's it.
If you mean send as in email, use the mail() function.
If you mean just print the result to the screen, use echo.
<?php
$grade = $_POST['grade'];
IF ($grade>=0 && $grade<=50){
echo "You failed";
} ELSE IF ($grade<=60){
echo "You Passed! But Study Harder!";
} ELSE IF ($grade<=70){
echo "Nice";
} ELSE IF ($grade<=80) {
echo "Great Job";
} ELSE IF ($grade<=90){
echo "Excellent";
} ELSE IF ($grade<=100){
echo "God Like!";
} ELSE {
echo "Invalid Grade!";
}
?>
Also, i'm not sure if this is a standard or not (I usually don't see it that way), but having all caps in your IF / ELSE statements really annoys me for some reason.