I'm trying to learn PHP and i'm doing my first login connection page to my Active Directory, i've already done those two pages:
form.php:
<HTML>
<body>
<form action="ADconnect" method="post">
<p>Votre login : <input type="text" name="login"/></p>
<p>Votre password : <input type="password" name="password"/></p>
<p><input type="submit" value="OK"></p>
</form>
</body>
</HTML>
ADconnect.php:
<?php
//check var
$check_password = $_POST['password'];
$check_dn= $_POST['login'];
//display of check var
echo $check_password;
echo "<br>";
echo $check_dn;
echo "<br>";
//AD's connexion var
$AD_con = ldap_connect("ADname") or die("could not connect to AD");
$AD_dn = "CN=".ldap_connect('$_POST['login']').",OU=XXX,OU=XXX,DC=XXX,DC=XXX";
$AD_password = ldap_connect('$_POST['password']');
echo $AD_dn;
echo "<br>";
//what i've tried to convert the AD's var:
//convert of $AD_con and $AD_password
//$AD_dn1 = strval($AD_dn);
//$AD_password1 = strval($AD_password);
//display of the converts
//echo $AD_dn1;
//echo $AD_password1;
//connect function
if (isset($_POST['login']) && $_POST['password'] == 0){
if (ldap_bind($AD_con, $AD_dn, $AD_password)){
include 'frontpage.php';
}
else{
echo "invalid user/pass or other error";
}
}
else
echo "var aren't correctly collect";
?>
I have an error when i'm trying to test those two pages and that's what i get:
pitword
Pit wasntme
CN=Resource id #7,OU=XXX,OU=XXX,DC=XXX,DC=XXX
A PHP Error was encountered
Severity: Warning
Message: ldap_bind() expects parameter 3 to be string, resource given
Filename: pages/ADconnect.php
Line Number: 30
Backtrace:
File: C:\wamp64\www\test\application\views\pages\ADconnect.php
Line: 30
Function: ldap_bind
File: C:\wamp64\www\test\application\controllers\pages.php
Line: 10
Function: view
File: C:\wamp64\www\test\index.php
Line: 315
Function: require_once
invalid user/pass or other error
So the values of my fields login and password are correctly recovered from one page to the other, and i've tested the connect function with plain text to see if the problem was coming from this. But i've reached my AD server.
The problem seems to be that when i'm using the ldap_connect() function, the values of my variables $AD_dn and $AD_password are changed into "resource #7" and "resource #8". Normally it have to display "pit wasntme" for $AD_dn and "pitpass" $AD_password for the connect function.
By reading the error, i've understood that i've to convert them into strings, because it is what the ldap_bind needs for the second and third parameters. Which i've tried with what i've found on the net (i've put it in my comments below my last echo ""), but the result is still the same.
If anyone can give a tip or an explanation on what i am doing wrong or on how can i recovers correctly (in the good format) my entered values sent by my form, it will be great.
Thanks to take time for reading this thread.
Ok thanks to whoever have try to help me but i've found the solution: i was using ldap_connect() on the $_POST['login'] and $_POST['password'] but if i remove this function all works correctly!
Related
I'm programming a simple password checker with a html form, where you input the code and this code is compared as hash to another hashed code in the database. If the password matches, the index.php file shows a few divs, which otherwise are completely hidden from the user.
I've tried things like:
$input = "";
<center>
<form action="" method="GET">
CODE:<br>
<input type="text" name="code" value="">
<br><br>
<input type="submit" value="Submit">
</form>
</center>
<?php
$checker = new Checker();
$input = $_GET['code'];
//echo "<style>.Main_Content{ visibility:hidden;}</style>";
if ($checker->compareWords($input, 'Beginners')) {
echo "success Beginners<br>";
include 'Beginners_Video.php';
echo "<style>.Main_Content{ visibility:show;}</style>";
}
else {
echo "false Beginners<br>";
}
?>
Fatal error: Uncaught TypeError: Argument 1 passed to
Checker::compareWords() must be of the type string, null given, called
in D:\www\www91\members\members.php on line 64 and defined in
D:\www\www91\members\checker.php:23 Stack trace: #0
D:\www\www91\members\members.php(64): Checker->compareWords(NULL,
'Beginners') #1 {main} thrown in D:\www\www91\members\checker.php on
line 23
The result should be no error and just the whole thing hidden, or the output "False Beginners. Nothing else"
I know that i'm just stupid and that the answer is probably really simple. I've tried and I can't figure it out.
Thanks for your help.
Your code should work once you filled in and submitted the form, but there is no check handling the case where $_GET['code'] is unset or empty. Change your if statement to
if (!empty($input) && $checker->compareWords($input, 'Beginners')) {
in order to check for this first. If !empty($input) is false, the next condition won't be checked at all, so there won't be an error message and it will jump to the else clause directly.
On a side note: You should think about whether GET is the right method for what you're trying to achieve or whether POST would be better. With GET, The codes users enter might get saved in the browser's history and be visible to others using the same computer. Also, for passwords use type="password" for the input instead of displaying it in cleartext.
And one more thing: the <center> tag is deprecated and you should use CSS instead for layout.
At the very beginning you should check if something is passed in code parameter, using the isset() method. If $_GET['code'] is empty it will return null and this is why you get must be of the type string, null given.
<?php
if(isset($_GET['code']) {
$input = $_GET['code'];
} else {
// 'code' parameter is empty
$input = '';
}
$checker = new Checker();
// ...
To begin with, I'm having difficulties tying the Google ReCaptcha into my login form. Just for some background information, this is all running on a live webserver with an SSL Certificate, I've got the correct site and secret keys and all that jazz.
Here's my login form:
<html>
<head>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<br />
<p>Please log in to your account below:</p>
<form action="index.php" method="post" target="_self">
<b>User Name:</b><br>
<input type="text" size="20" name="userid"><br />
<br />
<b>Password:</b><br>
<input type="password" size="20" name="password"><br />
<br />
<div class="g-recaptcha" data-sitekey="_MY PUBLIC SITE KEY_"></div>
<br />
<input type="submit" name="submit" value="Login">
<input type="hidden" value="validate" name="content">
</form>
And my script to validate:
<?php
if (isset($_POST['submit'])) {
$userid = $_POST["userid"];
$password = $_POST["password"];
$secretkey = "_MY SECRET KEY_";
$responsekey = $_POST["g-recaptcha-response"];
$useripaddress = $_SERVER["REMOTE_ADDR"];
$url = "https://www.google.com/recaptcha/api/siteverify?secret={$secretkey}&response={$responsekey}&remoteip={$useripaddress}";
$response = file_get_contents($url);
echo $response;
}
require_once("scripts/thecrab.php");
$userid = htmlspecialchars($_POST['userid']);
$password = htmlspecialchars($_POST['password']);
$query = "SELECT userid from users where userid = ? and password = PASSWORD(?)";
$stmt = $pdo->prepare($query);
$stmt->execute([$userid, $password]);
if (!$stmt->rowCount() & $response->success == 0) {
echo "<h2>Sorry, your user account was not validated.</h2><br>\n";
echo "Try again<br>\n";
echo "Return to Home\n";
} else {
$_SESSION['valid_recipe_user'] = $userid;
echo "<h2>Log In Successful</h2><br>\n";
echo "<img src=\"images/image-11.png\">\n";
}
?>
So here's the few issues that I am having. If you notice, at the top of my page that validates the information, I've got
echo $response;
That's in there strictly for testing purposes, so that I can see if the ReCaptcha comes back as true or false, but even when filling out the ReCaptcha, it always comes back as false, no matter what the security setting is set to on my Google site. I added pre tags around the validation so that it could spit back the results in an easier form to read and I'm greeted with this even when I fill out the Captcha:
{
"success": false,
"error-codes": [
"missing-input-response"
]
}
Now, since I'm stuck with an eternal "false", I decided to give the if statement a shot and implement in, if the success is false (ie. 0) then don't login, else login. Pretty simple, and you can see that at the bottom of my validation page in the if statement:
if (!$stmt->rowCount() & $response->success == 0)
So far so good, I FTP it up to the server, refresh and give it a go. But this time I get an error, and it states that the variable $response is undefined. Well I defined the variable at the top of the validation page where I said:
if (isset($_POST['submit'])) // Checks to see if the form was submitted
And it was submitted as I hit the Login button that has name="submit", so it see's that submit is set with the value of login, so it executes what follows the if (you know how PHP works), and at the bottom is where it defines $response. As far as I know, with PHP, it doesn't matter which block the variable is defined in, as long as it gets executed then it can be used anywhere.
So all in all, the issues I'm having is:
ReCaptcha always evaluates to False
Error thrown stating $response is undefined despite it being defined
Ties in with #2, since variable is undefined, it can't execute the if statement.
I've tried almost everything in my skillset.
Check again the parameters you're passing to https://www.google.com/recaptcha/api/siteverify.
The response parameter must be responSe and not respone.
This causes the error returned by the server - "missing-input-response" means you're not passing the "g-recaptcha-response" parameter
Now that the response is working:
file_get_contents will return a string, containing a JSON response. If you want to access the success value in the JSON the way you're accessing here
if (!$stmt->rowCount() & $response->success == 0) {
then you have to first use json_decode to create an object out of the string.
the if logic in that same row is using a bitwise AND operator as you're using a single ampersand & instead of &&
the logic itself - currently if no user account exists AND the recaptcha failed then there will be error, otherwise it is valid. The problem is that if there is no user but recaptcha is OK then the user is valid and if the user is ok and recaptcha failed then the user is still valid. So I'm guessing you meant to use OR instead of AND:
if (!$stmt->rowCount() || $response->success == 0) {
I'm learning MySQL and PHP and got a problem with the input of the form. So I wrote a small test code, but it still cannot work. My PHP version is 5.6.
The code:
<html>
<body>
<form action ="2.php" method ="post">
Name: <input type="text" name="username" />
<input type ="submit" value="ok" />
</form>
</body>
</html>
and
<html>
<?php
if(isset($_POST['username'])){
$user=$_POST['username'];
echo $user;
echo " is your name";
}
else{
$user=null;
echo "error";
}
?>
</html>
The output of the project is always error, can't output the input before.
I tried single quote and double quote for username, both can't work.
I also tried to set always_populate_raw_post_data in php.ini to 0, -1, 1, all can't work.
I don't know where the problem is, though it might be very silly.
As what it look it is correct and should run without any problem. Make sure the above code is what you actually have. From my experience most of the form submission can be
you don't have correct name (username)
you might send incorrect http verb (post)
you submit to wrong endpoint (2.php)
From you code above everything look fine. if you still don't have the right result, you better debug it with var_dump, or print_r function with these built-in
$_POST, $_GET, $_REQUEST and check whether they contains you form variable name username
You are using isset as a variable, but it is a function that returns a boolean.
Change $user=isset($_POST['username']); to $user=$_POST['username'];
Another thing is that in both case you will end up in the IF condition even if there is no value added to the field so you can do something like this too:
<html>
<?php
if(isset($_POST['username']) && !empty($_POST['username'])){
$user=$_POST['username'];
echo $user;
echo " is your name";
}
else{
$user=null;
echo "error";
}
?>
</html>
It's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages that come from a file separate to the html/php form.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
All the research I've done hasn't gotten me far. I understand that sending the headers isn't good practice. I looked at ob_open (php function-I think it was called) and couldn't figure out how to properly use it. I couldn't find a question on here that satisfied the conditions I'm trying to meet either.
Any help is certainly appreciated.Thank You
EDIT: This is not a duplicate of 'Passing error messages in PHP'.
-------While the idea is similar, they are 'Passing error messages in PHP' before the headers are sent. Therefore it's not the same.
Store the error in a session and echo it on the destination page.
Put session_start() at the top of the code of the form.php page. Like this:
<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
<head>
Then replace the echo error with:
$_SESSION['error'] = 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
Use this in your conditions instead of the echo. Then in the form.php page:
if (isset($_SESSION['error'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
}
The unset makes sure that the error is repeated.
An HTTP Redirect causes a new HTTP request. Since php is stateless, it cannot natively support remembering a message to display to a specific user in another request. In order to get around this limitation, you would need to use a stateful storage mechanism (session or cookies), or pass the error message along to the next request via query string parameter. The usual way this is handled is by using session storage to save flash messages.
Here is a library that can make it a bit easier for you https://github.com/plasticbrain/PhpFlashMessages
Set session of error and display on the page on which you are redirecting
I'm new to PHP and developing a login form. Please find below the code I used. When I tried it gave me the following error:
Fatal error: Can't use function return value in write context in
C:\xampp\htdocs\forsiteSystem\login.php on line 3
Please help me to fix the issue.
Source code for thems/login.html:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action=".\login.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit" id="Submit_button">
</form>
</body>
</html>
Source code for index.php:
<?php
// venushka thisara dharmasiri
require 'config.php';
require 'thems\login.html';
?>
Source code for login.php:
<?php
if(isset($_POST("Submit_button"))==true)
print("Submit button pressed");
else
print("submit button sorry");
?>
Source code for config.php:
<?php
$dbUser="root";
$dbPassword="";
$dbName="forsitelogin";
$dbHost="localHost";
$dbConnection= mysql_connect($dbHost, $dbUser, $dbPassword);
if($dbConnection)
{
mysql_select_db($dbName);
//print("Sucessfully connected to database");
}
else
die("<strong>Cound not connect to database </strong> ");
?>
Should be $_POST["Submit_button"] instead of $_POST("Submit_button")
The error the script returns explains it:
Fatal error: Can't use function return value in write context in
C:\xampp\htdocs\forsiteSystem\login.php on line 3
If you don’t understand the meaning of the error—and believe me, most error messages are bizarre even to experienced programmers—look at the line number referenced. And looking at line 3 in login.php shows me the error; $_POST("Submit_button") is invalid:
if(isset($_POST("Submit_button"))==true)
print("Submit button pressed");
else
print("submit button sorry");
It should be $_POST["Submit_button"]:
if(isset($_POST["Submit_button"])==true)
print("Submit button pressed");
else
print("submit button sorry");
But looking at it further, why is there an ==true? It can simply be like this:
if(isset($_POST["Submit_button"]))
print("Submit button pressed");
else
print("submit button sorry");
But I would recommend doing a better check on that value like this:
if(array_key_exists("Submit_button", $_POST) && !empty(trim($_POST["Submit_button"])))
print("Submit button pressed");
else
print("submit button sorry");
I find that using array_key_exists and a combination of !empty with trim works better for basic user submitted data verification.
First some code clean up might help. PHP does not require braces in if() else syntax; however, a great place to start. I would suggest diving into basic syntax of PHP here. Not that what is there would not work.
if(condition){
//do something
} else {
//do something else
}
The main issue you are experiencing is proper syntax for arrays in PHP. Thus this will solve your fatal error.
//old
$_POST("Submit_button")
//new
$_POST['foo']
This fixes your first fatal error; conversely, will not get you much further. Since your form is using 'GET' not 'POST' to send the variables to the script. The submit button does not return a variable; rather, use another <input> or add a name to the form <form name="form" action="file.php" method="post"> to retrieve a variable. Hence using:
if(isset($_POST['form'])){
echo $_POST['name'];
}
Furthermore, there are many concerns using $_GET variables and mysql_connect. I would suggest using Google to find some good tutorials on PHP mysqli or PDO before moving on.