I have a form in LDAP where i can add a user and a password, what can i do to have a live check of the username using php and ajax, is not mysql and i don't know how to compare and switch commands like sqlquery or sql_num_rows used in mysql and move it to LDAP, i read LDAP manual on php and is different than mysql how can i replace this commands in LDAP so i can have my username checked live?? using javascript (everything uspposed to be in one page)
http://www.developphp.com/video/PHP/Check-User-Sign-Up-Name-Ajax-PHP-Social-Network-Tutorial
https://www.webslesson.info/2016/02/how-to-check-username-availability-in.html
and other web pages tried and working with mysql
i used ldap_connect, ldap_bind_ ldap_search, ldap get entries and is working printing out everythng in funny way, so using php i cleaned out everything and is printing in a nice manner everything, my question is how can i check live the username??? Like is happening (tested) i this link above???
<label for="name"><b>name</b></label>
<input type="text" name="name" onBlur="checkusername() "maxlength="15"value="">
<span id="namestatus"></span>
<script>
function checkusername(){
var status = document.getElementById("namestatus");
var u = document.getElementById("name").value;
if(u != ""){
status.innerHTML = 'checking...';
var hr = new XMLHttpRequest();
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
status.innerHTML = hr.responseText;
}
}
var v = "name="+u;
hr.send(v);
}
}
</script>
$user = 'cn=Manager,dc=mydc ,dc=it';
$password = 'mypass';
$host = 'my_numeric_IP';
$basedn = 'ou=sistem,ou=thinks,dc=mydc,dc=it';
$ds = ldap_connect("ldap://{$host}") or die('Could not connect to LDAP server.');
if($ldapbind){
$filter='(&(objectClass=inetOrgPerson)(uid=*))'; // single filter
$attributes=array('dn','uid','sn', 'displayName');
$search = ldap_search($ds,$basedn,$filter,$attributes); // search
ldap_sort($ds, $search, 'sn');
print_r($info = ldap_get_entries($ds, $search));
$info = ldap_get_entries($ds, $search);
$ldaprecord['cn'] = $_POST['name'];
$_dn = "uid=".$_POST[value'].",ou=".$_POST['othervalue'].",ou=VOIP,ou=sistem,dc=something,dc=it";
$r = ldap_add($ds, $_dn, $ldaprecord);
}else {
echo "LDAP bind failed";
}
I think it is a little bit more difficult than only replace the mysql functions because of the mysql (or other SQL server) is not similar to LDAP.
I suggest to use an existing PHP package for LDAP. For example Adldap2 looks good for me. And there is many code snippets. For example the authentication
Related
I have been spending lots of time trying to figure out the issue. Nothing is working though. It continues to send the PHP file as text.
This is my javascript file with the ajax request.
var ajax = new XMLHttpRequest();
var method = "GET";
var url = "http://localhost:8000/createTable.PHP";
//send ajax request
ajax.open(method, url, true);
ajax.send();
//retrieve table data
ajax.onreadystatechange = function () {
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
//convert data to array
alert(this.responseText);
var data = JSON.parse(this.responseText);
}
and this is my php file which is alerted as is on my website.
//connect to MYSQL
require_once('../connectSQL.php');
//query
$result = mysqli_query("SELECT * FROM fitness");
//
$to_encode = array();
while ($row = mysqul_fetch_assoc($result)){
$to_encode[] = row;
}
echo json_encode($to_encode);
mysqli_close($dbc);
//fclose($myfile);
My php file work fine when I'm sending json from javascript file to php for storing in database. However, now that I'm retrieving data from database, seems like the PHP file is not being read as PHP.
I have tried changing all sorts of things in httpd.conf. Using apache 7 and mac osx.
You must insert PHP tags, so the server understands this code as PHP
in this case it would look like this:
<?php
//connect to MYSQL
require_once('../connectSQL.php');
//query
$result = mysqli_query("SELECT * FROM fitness");
//
$to_encode = array();
while ($row = mysqul_fetch_assoc($result)){
$to_encode[] = row;
}
echo json_encode($to_encode);
mysqli_close($dbc);
//fclose($myfile);
?>
I just wanted to retrieve some PHP/Mysql stuff at the beginning of my app (authentication and x and y data) from the users which I later plan to emit to the app.js (one time at the beginning and once the user disconnects update x - y values).
So basically I have set up Nodes.js and understood that some stuff is not possible like before (e.g with plain php)
Where I already have a problem is the AJAX php request in the index.html of my nodes Server
Schema:
app.js: pull Data from the /Client/index.html (I think need to do it via sockets)
index.html: get or post data via Ajax to a php file and get the values of the database back to the index.html(JavaScript)
then send that data via sockets to the app.js
php: select mysql database
retrieve values from mysql
parse them via Json and make them available in the index.html file Nodes.js (Client)
Maybe somebody of you have a solution
Nodes.js /Client/index.html:
function checkuser(username, password) {
var myObj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
myObj = xhttp.responseText;
var i = 0;
while (i <= myObj.length) {
//console.log("ASQL found and Auth Username:"+ myObj[i].username) ;
console.log(myObj.username);
i++;
}
}
};
xhttp.open("GET", "/client/is_user.php?username333=" + username + "&password333=" + password, true);
xhttp.send();
}
is_user.php:
<?php
require('config_sql.php');
$email = stripslashes($_GET['username333']);
$email = mysqli_real_escape_string($con,$email);
$password369 = stripslashes($_GET['password333']);
$password369 = mysqli_real_escape_string($con,$password369);
$query = "SELECT * FROM `users` WHERE email='$email'
and password='".md5($password369)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$response = array();
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row;
}
$jsonData = json_encode($response);
echo $jsonData;
mysqli_close($con);
?>
atm is not retrieving the username form the created json on the php side.
If I console.log(myObj); it's showing the me complete php.file data as plain text if I want to retrieve the username from MySql its saying undefined.
Is the php Interpreter actually working when I post/get via Ajax in a Node.js environment?
Normally when I was programming with pure php all the request worked well.
Thank you in advance.
Check you code for recieving result from query:
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row;
}
$jsonData = json_encode($response);
Should be so:
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row_user;
}
$jsonData = json_encode($response);
I know this site doesn't like "spot my mistake" code, but I'm desperate. I have a website that needs to access user-specific data from a database (PHP), convert the data into a JSON file, and then change a HTML header to display that specific data. The database table has the user email, password, and class name, among other things. I have a login page that establishes the session variables for the email and the password. When the user logs in, I want their class name to be entered into HTML text. I've used dozens of sources, mostly W3schools, and came up with this code:
PHP:
<?php
session_start();
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
if (!$obj) {
die(mysqli_error());
}
$servername = "localhost";
$username = "id5143969_enviroquest1";
$password = "codeteam1";
$database = "id5143969_enviroquest1";
$link = mysqli_connect($servername, $username, $password, $database);
$result = $link->query("SELECT UserClassName FROM ".$obj->UserInfo1." WHERE ".$obj->UserEmail."= '". mysqli_real_escape_string($link,
$_SESSION['useremail']) . "' and ".$obj->UserPassword." = '" . mysqli_real_escape_string($link, $_SESSION['userpassword']) . "'");
if (!$result) {
die(mysqli_error());
}
$_SESSION['classname'] = $result->fetch_assoc();
if (!$_SESSION['classname']) {
die(mysqli_error());
}
echo json_encode($_SESSION['classname']);
Javascript:
function getclassname() {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "UserInfo1":"UserClassName"};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
document.getElementById("UserClassName").innerHTML = myObj;
}
};
xmlhttp.open("GET", "php2.php" + dbParam, true);
xmlhttp.send();
}
HTML:
<h1 class="text-center" id="UserClassName" name="UserClassName" onload=
"getclassname()"> </h1>
I have no idea what's going wrong, and am too new to coding to figure it out by myself.
Try this (I can't test it, but)—
PHP:
Remove the ?> at the end of the file. Pure-PHP files should always leave off the closing tag.
Change (MYSQLI_ASSOC) to just () - per this and the docs, you don't need it.
Javascript:
Remove the session_start() call
Change
for (x in myObj) {
txt += myObj[x].name + "<br>";
}
to
txt = myObj.UserClassName
The fetch_assoc() call in PHP gives you a mapping that uses the database field names ("each key in the array represents the name of one of the result set's columns" per the docs) for a single row. Therefore, if the JSON encode/decode worked OK, you should be able to refer directly to the field.
To test this, in the developer tools, set a breakpoint at the txt = ... line and see what myObj is.
I don't think you need $obj, dbParam, or ?x=, but I would not suggest changing them unless the above doesn't help.
Good luck!
I'm trying to build a very simple "budget" website solely for practice, but I can't make this site update my database.
Basically I have a database 'budgetdb' running in XAMPP with MySQL. I've got 1 table where the structure looks like this:
I've got two files, 'index.html' and 'handleUserInput.php'.
Index.html:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="description">
<input type="number" id="budgetin">
<input type="number" id="budgetout">
<button type="button" onclick="updateDB()">Add to database</button>
<script>
function updateDB() {
var description = document.getElementById('description').value;
var budgetin = document.getElementById('budgetin').value;
var budgetout = document.getElementById('budgetout').value;
var xmlhttp = new XMLHttpRequest();
var url = "handleUserInput.php?description='" + description + "'&budgetin='" + budgetin + "'&budgetout='" + budgetout + "'";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert('Variables sent to server!');
}
}
xmlhttp.open("POST", url);
xmlhttp.send();
}
</script>
</body>
</html>
handleUserInput.php:
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "budgetdb"
mysql_connect($host, $username, $password;
mysql_select_db($dbname);
$description = $_POST['description'];
$budgetin = $_POST['budgetin'];
$budgetout = $_POST['budgetout'];
$query = 'INSERT into budget VALUES ($description, $budgetin, $budgetout)';
mysql_query($query)
?>
The message prompt is displayed, but no data is shown in the database. Any clue on what I am doing wrong here?
UPDATE chrome error:
Notice: Undefined index: description in /Applications/XAMPP/xamppfiles/htdocs/handleUserInput.php on line 13
Notice: Undefined index: budgetin in /Applications/XAMPP/xamppfiles/htdocs/handleUserInput.php on line 14
Notice: Undefined index: budgetout in /Applications/XAMPP/xamppfiles/htdocs/handleUserInput.php on line 15
Other answers have shown the problem with the way you write the query, it. should be, with quotes around each of the values.
$query= "INSERT into budget VALUES('$description',$budgetin,$budgetout)";
But you also have a problem with the way you create the URL. Quotes shouldn't be put around query parameters, and you should use encodeURIComponent to ensure that special characters are escaped properly.
var url = "handleUserInput.php?description=" + encodeURIComponent(description) + "&budgetin=" + encodeURIComponent(budgetin) + "&budgetout=" + encodeURIComponent(budgetout);
And to prevent SQL injection problems, you need to escape the strings before you use them as SQL parameters. And since you're sending the parameters in the URL, rather than in the POST data, you need to get them from $_GET, not $_POST.
$description = mysql_real_escape_string($_GET['description']);
Although if you're first learning PHP now, you should use PDO or mysqli, instead of the obsolete mysql extension, and use prepared statements instead of string substitution.
Change the line that performs the query to:
mysql_query($query) or die(mysql_error());
If there's a problem performing the query, this will display the error message.
The quotes in your query are incorrect. Should be (note outer double quotes and inner single quotes):
$query= "INSERT into budget VALUES('$description',$budgetin,$budgetout)";
However, be aware this has opened you up to a SQL injection where description is
'); DROP budget;
Also, your description may contain punctuation and spaces, which may be messing up your url. You are sending a POST anyway, so all the data should be in the body of the request not the url.
Use
$query = "INSERT into budget VALUES ('$description', $budgetin, $budgetout)";
description is string type in database so you close with single quote or double quote in PHP String.
Always consider safety. ReWrite a code as (somewhat safety):
$description = mysql_real_escape_string( $_POST['description'] );
$budgetin = intval( $_POST['budgetin'] );
$budgetout = intval( $_POST['budgetout'] );
$query = 'INSERT into budget VALUES ("$description", $budgetin, $budgetout)';
Note: Don't use mysql_* function. It is deprecated in future versions. Use MySQLi or PDO
You are sending your values as GET parameters not POST parameters.
handleUserInput.php?description='" + description + "'&budgetin='" + budgetin + "'&budgetout='" + budgetout + "'"
Everything you pass to PHP thru url will fall into $_GET variable. Not only PHP bu every server side language will behave the same, once it is a standard GET means URL parameters and POST is Request Payload
You can change $_POST to $_GET or add your data do xmlhttprequest object
<!DOCTYPE html>
<html>
<body>
<input type="text" id="description">
<input type="number" id="budgetin">
<input type="number" id="budgetout">
<button type="button" onclick="updateDB()">Add to database</button>
<script>
function updateDB() {
var description = document.getElementById('description').value;
var budgetin = document.getElementById('budgetin').value;
var budgetout = document.getElementById('budgetout').value;
var params = "description=" + description + "&budgetin=" + budgetin + "&budgetout=" + budgetout;
var xmlhttp = new XMLHttpRequest();
xmlhttp .setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp .setRequestHeader("Content-length", params.length);
xmlhttp .setRequestHeader("Connection", "close");
var url = "handleUserInput.php?";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert('Variables sent to server!');
}
}
xmlhttp.open("POST", url,true);
xmlhttp.send(params);
}
</script>
</body>
</html>
In order to minize your code use Jquery library instead of simple JS code
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
<input type="text" id="description">
<input type="number" id="budgetin">
<input type="number" id="budgetout">
<button type="button" onclick="updateDB()">Add to database</button>
<script>
function updateDB() {
var description = $('#description');
var budgetin = $('#budgetin');
var budgetout = $('#budgetout');
$.post( "handleUserInput.php", { "description": description, "budgetin": budgetin, "budgetout": budgetout }, function( data ) {
alert( "Variables sent to server!" );
} );
}
</script>
</body>
</html>
Use mysql_real_escape_string in order to avoid SQL injection into your application. Initial problem was caused because php variables wasn't correctly added in the string of SQL query, for example :
$input = 'aaa';
echo 'text $input';
this code will output
text $input
but this one
$input = 'aaa';
echo "text $input";
or this one
$input = 'aaa';
echo "text ".$input.";
will output
text aaa
Please check the code bellow
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "budgetdb"
mysql_connect($host, $username, $password;
mysql_select_db($dbname);
$description = $_POST['description'];
$budgetin = $_POST['budgetin'];
$budgetout = $_POST['budgetout'];
$description = mysql_real_escape_string($description);
$budgetin= mysql_real_escape_string($budgetin);
$budgetout= mysql_real_escape_string($budgetout);
$query = "INSERT into budget VALUES ('".$description."', ".$budgetin.", ".$budgetout.")";
mysql_query($query)
?>
Use single inverted comma with php variables like below.
$query = "INSERT into budget VALUES ('$description', $budgetin, $budgetout)";
What is it that I am doing wrong? the value of myid1 is not being accepted by my PHP script. My Javascript code is below followed by my PHP script. Please help.
Javascript code
function generaterepno(selectedid) {
var idnum=selectedid;
var idnum1=idnum.split(":",1);
var text='[{"myid1":idnum1}]';
var httpc = new XMLHttpRequest();
var url = "reportnumber.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", text.length);
httpc.onreadystatechange = function() {
if(httpc.readyState == 4 && httpc.status == 200) {
alert(httpc.responseText);
var myArr = JSON.parse(httpc.responseText);
}
httpc.send(text);
document.getElementById('genno').value=idnum1;
}
My PHP is as follows-
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$mynewid=$_POST["myid1"];
$mynewid=strip_tags($mynewid);
include("inc_con.php");
$myquery="SELECT MAX(report_number) AS mrepno FROM childreports WHERE child_id='$mynewid' ORDER BY report_number";
$myresult=mysql_query($myquery);
if(!$myresult) {
$outp = '[{"reportn":"0"}]';
echo ($outp);
die('records do not exist');
}
$outp = "[";
while($rm = mysql_fetch_array($myresult)) {
$outp .= '{"reportn":"'.$rm["mrepno"].'"}';
}
$outp .="]";
mysql_close($con);
echo ($outp);
?>
I am a newbie to JSON and Javascript. Been trying to learn it on my own by reading. The alert message of the responseText is displaying a notice that myid1 is not defined. Also in my Javascript the HTML id genno is supposed to get the the return value from PHP code that is the max report number as obtained from the SQL query. Once I get reportn variable with some value I can JSON parse it and put it in the genno id but my problem is sending the myid1 value properly to my PHP script reportnumber.php.
Can someone help please? Thanks!
After prompt and great help from Kyle I made some changes in my Javascript function as follows and my query appears in the comments section below.
function myFunction(arr) {
var tempans = arr.reportn;
var myans = 0;
if(tempans.length == 0) {
var asknum = prompt('Enter previous report number:');
myans = parseInt(asknum)+1;
} else {
myans = parseInt(tempans)+1;
}
document.getElementById('genno').value=myans;
}
Why am i prompted TWICE for a user input?
You have a problem here. var text='[{"myid1":idnum1}]'; is not valid JSON because you're trying to put the variable idnum1 inside the string. It would be easier to set it in an object and then use JSON.stringify() to convert it to JSON.
var text = JSON.stringify({"myid1": idnum1});
In PHP, you then need to decode it from the request body as it won't be set in $_POST.
$contents = json_decode(file_get_contents("php://input"), true);
$myNewId = $contents['myid1'];