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.
Related
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.
I have following html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fancy Website</title>
</head>
<body>
<div id="content_login">
<form method="post" action="app.php">
<table>
<thead>Please Login for more fancy Content!</thead>
<tr>
<td>Username</td>
</tr>
<tr>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td><input type="submit" name="login" value="Login"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
And this is my php script:
<?php
if(isset($_POST['login'])) {
echo "Hello " . $_GET["username"];
}
?>
Yeah simply nothing, but I only wanted to test, if a script would work when the Login Button is pressed. Surprise: It's not. I open index.html in my browser and the html part works properly, but if I press the Login Button the browser shows me this:
<?php
if(isset($_POST['login'])) {
echo "Hello " . $_GET["username"];
}
?>
I guess it's a syntax issue but I can't find it. Maybe you see it.
Thanks a lot!
My advice would be to use:
<?php
if (isset($_POST['login']))
{
$username = $_POST['username'];
if (!empty($username))
{
echo "hello $username";
} else {
echo "You must fill in the username!";
}
}
?>
To be honest, I would change index.html to index.php and place it into the top of that page so all errors etc are passed through one file.
you should change that $_GET["username"] to $_POST["username"] variable to work it correctly
<?php
if(isset($_POST['login'])) {
echo "Hello " . $_POST["username"];
}
?>
Do you have the php code in app.php? If you have then you have not enabled mod_php in Apache. I would recommend you to use wampserver (on windows) since that takes care of the basic apache/php configuration.
http://www.wampserver.com/en/
EDIT: You can not just execute your php code without having a webserver. Opening HTML files in your browser is client side and php is server side.
First I think you don't have apache server running to make your PHP code works correctly.
And you are sending the data using POST no GET, you must use the POST method to handle the data.
<?php
if(isset($_POST['login'])) {
echo "Hello " . $_POST["username"];
}
?>
Hi I have meet a problem here.
I need to log in an account here
but after i key in all the details and click Sign-In the page will redirect me back to the log in page. But actually the account is already logged in just that it cant redirect back to the Home Page after log in.
What problem is this? Im using Session.
and i put my session_start in connect.php(which is use to connect to database)
Below is The Code
<?php error_reporting(0) ?>
<?php
include_once 'connect.php';
//Code Refer to http://www.w3schools.com/php/func_http_setcookie.asp
if(isset($_SESSION['user'])!="")
{
header("Location: Home.php");
}
if(isset($_POST['btn-login']))
{
$username = mysql_real_escape_string($_POST['username']);
$upass = mysql_real_escape_string($_POST['password']);
$res=mysql_query("SELECT * FROM user WHERE u_username='$username'");
$row=mysql_fetch_array($res);
if($row['u_password']==md5($upass))
{
$_SESSION['user'] = $row['u_ID'];
header("Location: Home.php");
}
else
{
?>
<script>alert('wrong details');</script>
<?php
}
?>
<?php
$year = time() + 31536000;
setcookie('rememberme', $_POST['username'], $year);
if ($_POST['rememberme'])
{
setcookie ('rememberme',$_POST['username'], $year);
}
else
{
setcookie(rememberme, $past);
}
}
?>
<!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>Login</title>
<link rel="stylesheet" href="Style.css" type="text/css" />
</head>
<body>
<div id="header">
<div id="left">
<label>AngelService</label><br/>
<p>Royal Borough of Greenwich</p>
</div>
</div>
<center> Home Page | View Post | Post A Service</center>
<center>
<div id="login-form">
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="username" placeholder="Your Username" required value="<?php
echo $_COOKIE['rememberme']; ?>"/>
</td>
</tr>
<tr>
<td><input type="password" name="password" placeholder="Your Password" required />
</td>
</tr>
<tr>
<td><button type="submit" name="btn-login">Sign In</button></td>
</tr>
<tr>
<td>
<input type="checkbox" name="rememberme" value="rememberme" style="font- size:6px;"> Remember Me<br>
</td>
</tr>
<tr>
<td>
Sign Up Here</td>
</tr>
</table>
</form>
</div>
</center>
<div id="footer">
<div id="center" align="center">
<br/>
<p>Angel Services | Royal Borough of Greenwich | Created By UOG Student: Kuai Boon Ting</p>
</div>
</div>
</body>
</html>
You are missing action="Your redirection page" in form tag i.e.,
<form method="post" action="forexample-Home.php">
.....
</form>
There are several things you can do to improve your code. For starters, you do not need to close and open PHP tags directly after each other, like you have
<?php error_reporting(0) ?>
<?php
include_once 'connect.php';
could just be
<?php error_reporting(0);
include_once 'connect.php';
The statement if(isset($_SESSION['user'])!="") doesn't do exactly what you think it does. isset($_SESSION['user']) returns a boolean (true/false), so checking whether or not a boolean is empty won't work. You can do if (!empty($_SESSION['user'])) {... to check if it's set and if it's empty or not. Check out the documentation for isset() and documentation for empty().
For your actual problem though: Note also that your header(); functions cannot be called after any output is made to the browser (any whitespace, HTML or PHP echo). This would appear as a PHP Warning, which will be reported should you put error_reporting(-1); instead of ignoring all errors (as you currently are doing with having error_reporting set to 0).
The other answer suggested using the HTML action-attribute for the form, but in case the login is invalid, it's best to have it sent to the same page, and only redirect should the login be valid. This is called "validate and redirect".
These pointers below are just to improve your code, and not necessarily the cause of your problem.
If you want to set a cookie, it has to be done before any and all output is sent to the browser (see this post), so in case the if($row['u_password']==md5($upass)) statement fails, and it enters the else-brackets, your cookie will not be set.
You should stop using mysql_* functions if you can. They are deprecated, and will be removed in the future. Switch over to mysqli_* or PDO instead. (Check out this post).
Usage of md5 hashing is not that secure. If you have PHP 5.5.0 or higher, you should perhaps look into usage of password_hash and password_verify
After every header("Location: ...."); you should always put a exit;, so that the code stops executing after it's redirecting. (Check out this post).
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