Securimage can't validate form - php

I tried using Securimage but it the form always post to another page even if I enter wrong captcha. How to validate the captcha first then only submit the form to the posted page? The form keeps redirecting me to the posted page eventhoguht the capcha is not validated. Please advice.
<?php session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form action = "login.php" method = "post">
<p>
<label for="ct_name">Name*:</label>
<?php echo #$_SESSION['ctform']['name_error'] ?>
<input type="text" name="ct_name" size="35" value="<?php echo htmlspecialchars(#$_SESSION['ctform']['ct_name']) ?>" />
</p>
<p>
<?php
// show captcha HTML using Securimage::getCaptchaHtml()
include_once 'genius_gadget/../securimage/securimage.php';
$options = array();
$options['input_name'] = 'ct_captcha'; // change name of input element for form post
echo Securimage::getCaptchaHtml($options);
?>
</p>
<input name="btnSubmit" type="submit" id="btnSubmit">
</form>
<?php
if(isset($_POST['btnSubmit'])){
if ($_POST['ct_name'] <> "") {
require_once 'genius_gadget/../securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($captcha) == false) {
echo 'Incorrect security code entered';
}
}
else{
echo "Success";
}
}
?>

Tidied up the code... Tested on PHP 5.3.29
<?php // login.php
session_start();
// 1) Move the check logic before the login page display
// 2) Moved the options to the start - easy to see the input_name
// 3) fixed 'undefined variable $captcha message as incorrect input name used.
// 4) Always need the 'securimage.pph' script so move it to top of the file
// 5) Change the include path as it ignores the first directory
// 6) Always need a 'Secureimage' object so create it at the start.
// 7) Added HTML closing tags
// 8) Ensure that the input name value comes from $_POST not the $_SESSION.
// 9) Changed the 'ct_name' if test to cause an error if not entered.
// 10) Ensure that if captcha is valid the the 'success' path is executed
include_once '/securimage/securimage.php';
$options = array();
$options['input_name'] = 'ct_captcha'; // change name of input element for form post
$securimage = new Securimage($options);
if(isset($_POST['btnSubmit'])){
if ($_POST['ct_name'] <> "") {
if ($securimage->check($_POST['ct_captcha']) == false) {
echo 'Incorrect security code entered';
}
else{
echo "Success";
exit;
}
}
else {
echo 'Name not entered';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form action = "login.php" method = "post">
<p>
<label for="ct_name">Name*:</label>
<?php echo #$_SESSION['ctform']['name_error'] ?>
<input type="text" name="ct_name" size="35" value="<?php echo htmlspecialchars(#$_POST['ct_name']) ?>" />
</p>
<p>
<?php
// show captcha HTML using Securimage::getCaptchaHtml()
echo Securimage::getCaptchaHtml($options);
?>
</p>
<input name="btnSubmit" type="submit" id="btnSubmit">
</form>
</body>
</html>

Related

PHP Session not recognizing variable when heading to another page

So I'm making a Login - Successful Login page with PHP, and using MySQL Database. My code successfully checked the Username and Password and only allowed me to head to the next page once they are correct.
However, I cannot print out the Username on Successful Login page. So I'm not sure if my session is running properly or not.
login.php
<!DOCTYPE HTML>
<html>
<?php
session_start();
?>
<head>
<title>Login</title>
</head>
<body>
<!--<form action ="SuccessfulLogin.php" method = "get"> --> // If I put this in my code, the whole program stops checking Username and Password, and just put me to the next page
<?php
//define variables and set to empty values
$nameErr = $loginErr = "";
$Username = $website = $Password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Username"])) {
$nameErr = "Name is required";
} else {
$Username = test_input($_POST["Username"]);
}
if (empty($_POST["Password"])) {
$passErr = "Password is required";
} else {
$Password = test_input($_POST["Password"]);
}
//continues to target page if all validation is passed
if ( $unameErr ==""&& $passErr ==""){
// check if exists in database
$dbc=mysqli_connect('localhost','testuser','password','Project')
or die("Could not Connect!\n");
$hashpass=hash('sha256',$Password);
$sql="SELECT * from Members WHERE Username ='$Username' AND Password='$hashpass';";
$result =mysqli_Query($dbc,$sql) or die (" Error querying database");
$a=mysqli_num_rows($result);
if ($a===0){
$loginErr="Invalid username or password";
}else{
$_SESSION["Username"]=$Username;
header('Location: /SuccessfulLogin.php');
}
}
}
// clears spaces etc to prep data for testing
function test_input($data){
$data=trim ($data); // gets rid of extra spaces befor and after
$data=stripslashes($data); //gets rid of any slashes
$data=htmlspecialchars($data); //converts any symbols usch as < and > to special characters
return $data;
}
?>
<h2 style="color:yellow" align="center"> Login </h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" align="center" style="color:#40ff00">
User Name: <input type="text" name="Username" value="<?php echo $Username;?>"/>
<span class="error">* <?php echo $unameErr;?></span>
<br/><br/>
Password:
<input type="text" name="Password" value=""/>
<span class="error">* <?php echo $passErr;?></span>
<br/><br/>
<span class="error">* <?php echo $loginErr;?></span>
<input type="submit" name="submit" value="Login"/> 
</form>
<!--</form>--> // closing tag of form action SuccessfulLogin.php
</html>
SuccessfulLogin.php
<!doctype html>
<html>
<?php
session_start();
$Username=$_GET['Username'];
$_SESSION['Username']=$Username;
?>
<head>
<meta charset="utf-8">
<title>Login Form</title>
<link rel="stylesheet" href="RegisterLogin.css">
</head>
<body>
<!--<form action ="MemberMenu.php" method = "get">-->
<h2><?php echo "User $Username LOGGED IN"; ?></h2> // Doesn't print out the $Username
<p align="center"> Click here to be redirected to the menu page </p>
<!--</form>-->
</footer>
</body>
</html>
you need to check session isset or not.
Change
<?php
session_start();
$Username=$_GET['Username'];
$_SESSION['Username']=$Username;
?>
With
<?php
session_start();
if (isset($_SESSION['Username'])) {
$Username=$_SESSION['Username'];
echo $Username;
}
?>
You're using $_GET["Username"] which will be empty in this example, and then setting $_SESSION["Username"] to the empty variable.
Also this is a very odd way to do user auth.
Change this line of code
<?php
session_start();
$Username=$_SESSION['Username'];
$_SESSION['Username']=$Username;
?>
Into:
<?php
session_start();
$Username=$_SESSION['Username'];
?>
Read more about PHP session here

Previous data auto insert when browser reloading in PHP

I have some data input area.Here is my file.
Here is my db.php:
<?php
$username = "root";
$password = "";
try {
$db = new PDO('mysql:host=localhost;dbname=task', $username, $password);
echo "Connection Successfull";
} catch (PDOException $e) {
die("Error: Database connection");
}
?>
And my index.php is:
<?php
include "db.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>This is title</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="wrap1">
<form method="POST" action="">
<input type="text" name="name" required> Username</br></br>
<input type="email" name="email" required> Email</br></br>
<input type="text" name="website" required> Website</br></br>
<input type="submit" value="Submit">
</form>
</div>
<?php
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if(empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
}
else{
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
?>
</body>
</html>
When i first go to index.php page then it's showing some notice.
Notice: Undefined index: name in
C:\xampp\htdocs\techmasters\begin\index.php on line 21
Notice: Undefined index: email in
C:\xampp\htdocs\techmasters\begin\index.php on line 22
Notice: Undefined index: website in
C:\xampp\htdocs\techmasters\begin\index.php on line 23
but if i input any data then it going to be inserted fine.My problem is that if i reload the browser then previous inserted data going to inserted again.How can i solve this problem?
Thanks in advanced.
Its because, you are not checking whether form is submitted or not.
On every page request, data is getting inserted, add a check.
<?php
if (isset($_POST['name']) && ! empty($_POST['name'])) {
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if (empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
}
else{
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
$_POST = NULL;
}
?>
This will ensure that database insert will be done only in case of form submit.
EDIT:
If you submit a form to same page and then reload the page, it will
ask you to resubmit the form. Either change method to get and check
for duplicity or submit the form to another file (move form submit
code to other file and set it as form action).
When you reload the page it's asking for form re-submission. When you click on resend then it will post all data again and inserted in database. To overcome this issue you can use jquery.
Try this code :
html file :
<!DOCTYPE html>
<html>
<head>
<title>This is title</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="wrap1">
<form method="POST" id="frm" action="">
<input type="text" name="name" required> Username</br></br>
<input type="email" name="email" required> Email</br></br>
<input type="text" name="website" required> Website</br></br>
<input type="submit" class="sub" value="Submit">
</form>
</div>
<script>
$(".sub").click(function (e) {
e.preventDefault();
$.post("test.php",$("#frm").serialize(),function(data){
if(data == "Inserted!") {
//You can reload your page here
} else {
//Display error message.
}
});
});
</script>
</body>
</html>
You php code (test.php) :
<?php
include "db.php";
if(isset($_POST['name']) && $_POST['name'] != "") {
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if(empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
} else {
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
exit;
}
?>
Don't forget to add jquery file in your html.

I Need Tips to make my PHP password work

I have trouble with these codes:
password.php:
<html>
<head>
<title>Password!</title>
<meta charset="UTF-8">
</head>
<body>
<ul>
<form action="check.php" method="POST">
<li><input type="password" name="no1" placeholder="enter your password"></li>
<li><input type="submit" value="GO!"></li>
</form>
</ul>
</body>
Here is password2.php:
<html>
<head>
<title>Password!</title>
<meta charset="UTF-8">
</head>
<body>
<ul>
<form action="check.php" method="POST">
<li><input type="password" name="name" placeholder="verify your password"></li>
<li><input type="submit" value="GO!"></li>
</form>
</ul>
</body>
And here is check.php:
<?php
$enter = $_POST['no1'];
if (empty($enter)) {
echo "Please enter password!";
}
if (!(empty($enter))) {
echo "Your password is $enter";
}
?>
<html>
<body>
<p>Move on!</p>
</body>
</html>
<?php
$check = $_POST['name'];
if ($check == $enter) {
echo "Acces Granted";
}
if (!($check == $enter)) {
echo "Acces denied!";
}
?>
The troubles I have are:
check.php doesn't recognise "name" from password2.php
And I can't verify the password
Because $_POST variable is not persistent between requests it would not work. You can store the value from first form in the $_SESSION variable and retrieve it from session.
More info about php sessions here
Leave everything as it is in your question except check.php, here is the modified one:
<?php
//starting the session in PHP
session_start();
$enter = null;
// this is all the logic you need for retrieving `no1` from POST or SESSION
if (isset($_POST['no1'])){
$enter = $_POST['no1'];
$_SESSION['no1'] = $enter;
}elseif(isset($_SESSION['no1'])){
$enter = $_SESSION['no1'];
}
if (empty($enter)) {
echo "Please enter password!";
}
if (!(empty($enter))) {
echo "Your password is $enter";
}
?>
<html>
<body>
<p>Move on!</p>
</body>
</html>
<?php
$check = $_POST['name'];
if ($check == $enter) {
echo "Acces Granted";
// you can comment the next line if you are debugging,
// but after that you should destroy de session so you don't have a password as plain text
session_destroy();
}
if (!($check == $enter)) {
echo "Acces denied!";
}
?>

PHP login wont work, and no errors is show [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I have been struggling with this error for some time now.
I have created a profile site, If I run it localy there is no problem to login and get redirect to the profile page.
But at soon I upload it, nothing happends when i press the login . I just get an empty page ... But if i open the page source I can se that its reading my init.inc.php file. but nothing more than the comment code is readed..
And since i wont get any error message I really dont know whats the problem.
aaa hope you get what Im trying to say :)
This is my login page
<?php
include 'core/inc/init.inc.php';
if ($_SERVER['HTTP_HOST'] != 'localhost') // running in remote server
$server = 'pixeltouch2.mysql.domeneshop.no';
else // running locally
$server = 'pixeltouch2.mysql.domeneshop.no';
mysql_connect($server, "LOGIN", "pass") or die(mysql_error());
mysql_select_db("pixeltouch2") or die(mysql_error()) ;
$errors = array();
if (isset($_POST['username'], $_POST['password'])){
if(empty($_POST['username'])){
$errors[] = 'The username cannot be empty.';
}
if(empty($_POST['password'])){
$errors[] = 'The password cannot be empty.';
}
//Log in
if (valid_credentials($_POST['username'], $_POST['password']) == false ){
$errors[] = 'Username / Password incorrect.';
}
if (empty($errors)){
$_SESSION['username'] = htmlentities($_POST['username']);
$_SESSION['uid'] = fetch_user_id($_SESSION['username']);
header("Location: profile.php?uid=" . $_SESSION['uid']);
die();
echo $_SESSION['uid'];
}
}
?>
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Pixeltouch</title>
<link rel="stylesheet" type="text/css" href="ext/style.css" />
</head>
<body>
<div id="page-wrap">
<div id="main-content">
<br/>
<?php include_once('template/head.inc.php');
?>
<div id="menu">
<?php include_once('template/nav.inc.php');
?>
</div>
<!-- SKRIVBOX-->
<div>
<?php
if(empty($errors) == false){
?>
<ul>
<?php
foreach ($errors as $error) {
echo "<li>$error</li>";
}
?>
</ul>
<?php
}else{
echo 'Need an account ? Register here';
}
?>
</div>
<br/>
<form method="post" action="" >
<p>
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="<?php if (isset($_POST['username'])) echo htmlentities($_POST['username']); ?>" />
</p>
<p>
<label for="password">Password: </label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="submit" value="Login" />
</p>
</form>
<!-- SKRIVBOX END-->
</div>
<?php include_once('template/foot.inc.php');
?>
</div>
</body>
</html>
And my init.inc.php file
<?php
session_start();
/*
mysql_connect("pixeltouch2.mysql.domeneshop.no", "LOGIN", "PASS") or die(mysql_error()) ;
mysql_select_db("pixeltouch2") or die(mysql_error()) ;
*/
if($_SERVER['HTTP_HOST'] != 'pixeltouch2.mysql.domeneshop.no')// running in remote server
$server = 'pixeltouch2.mysql.domeneshop.no';
else // running locally
$server = 'pixeltouch2.mysql.domeneshop.no';
mysql_connect($server, "login", "pass") or die(mysql_error());
mysql_select_db("pixeltouch2") or die(mysql_error()) ;
$path = dirname(__FILE__);
include("{$path}/user.inc.php");
?>
<!--Registration/Login (START)-->
<?php
$exceptions = array('register', 'login', 'user_list', 'profile', 'edit_profile', 'upload');
$page = substr(end(explode('/', $_SERVER['SCRIPT_NAME'])), 0, -4);
if(in_array($page, $exceptions) == false){
if (isset($_SESSION['username']) == false){
header('Location: login.php');
die();
}
}
?>
<!--Registration/Login (END)-->
<!--User Profile (START)-->
<?php
$_SESSION['uid'] = 1;
?>
<!--User Profile (END)-->
Error LOG
Warning: Cannot modify header information - headers already sent by (output started at /home/3/p/pixeltouch/www/book/core/inc/init.inc.php:2) in /home/3/p/pixeltouch/www/book/login.php on line 32
When I look # line 32 I its my header("Location: profile.php?uid=" . $_SESSION['uid']);
die();
echo $_SESSION['uid'];
So its something about the session, is there another way to write the code so it work ?
Well the error says it right there. You are already sending output to the browser, and by saying "output" it means anything sent to the browser that are not http headers.
So look in your file for:
echo/print statements before your header location statement.
whitespaces or newline charachters before your <?php tags (even in included files).
Using the byte-order mark (BOM) at the beginning of a page.
So.. looking at your code samples I see (The + sign indicates spaces)
++++<?php
session_start();
You need to correct that use
<?php
session_start();
// No spaces at the beginning
Or even in this part
// You close the php tag
?>++++++++++
++++<!--Registration/Login (START)-->+++++++
<?php
$exceptions = array('register', 'login', 'user_list', 'profile', 'edit_profile', 'upload');
You dont need to do that, and you are sending a html comment.
To avoid such problems you could always use output buffering to ensure no output gets sent before the headers.

How do I clear the page content after a form is submitted?

I currently have this code in my project:
require_once('mysql.inc.php');
session_start();
if (!isset($_SESSION['username']) && !isset($_SESSION['uid']))
{
login_sequence();
}
else
{
login_check($_SESSION['username'], $_SESSION['uid']);
}
function login_sequence()
{
echo '<p>' . $pretext . '</p><form method="post" action="" /><label for="password">Password: </label><input type="password" name="password" id="password" /><input type="submit" value="Log In" /><input type="hidden" name="submitted" /></form>';
if (isset($_POST['submitted']))
{
$pword = hash('sha256', $_POST['password']);
$query = "SELECT pword FROM users WHERE user = 'guest'";
$result = mysql_query($query);
$return = mysql_fetch_assoc($result);
if ($return['pword'] == $pword)
{
pageout();
}
else
{
echo 'You entered the wrong password, if you are not a member, please leave.';
}
}
}
function login_check($username, $uid)
{
}
function pageout()
{
echo('
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="" />
</head>
<body>
<div id="header">
<p>WOOT</P>
</div>
<div id="">
</div>
<div id="navigation">
</div>
<div id="footer">
</div>
</body>
</html>
');
}
?>
There is a single "Guest" password stored in a database, it accesses the database and checks the password entered by the user against the one stored in the database. I want to have it so after the form is submitted and the information is correct, on the same page the form disappears and the page appears. How do I do it? How do I get rid of the form to make room for the new page?
header(location ...) on success, or a page display conditional on log in settings
simply do
at the end of your form and at the php code do this
if(!isset($_POST['s'])){
?>
your form here
<?php
}
else //form handle
I would make structure look slightly different:
//First
if (!isset($_POST['submitted'])) {
//include your form only
} else {
//Check if user submitted correct password
//If password is correct
if ($return['pword'] == $pword) {
pageout();
//OR write pageout code on different page and call header("Location: Yourpage.php");
} else {
//Include form or inform user about password mismatch
}
}
edit. Also if you use header("Location:") function make sure you're not echoing or including anything that outputs data. This will cause Headers already sent error.

Categories