Trying to use a class in a php page embedded with javascript - javascript

I'm trying to use a class that is already declared.
When the user types in something in the username text box I've used a javascript function to load a php file where it checks wether a username is available. this file is recalled for every keypress.
A connection to my database, which is a class, is already declared on the main page, however, the php file can't actually use the database classes. What can I do?
If I wrote a separate script to connect to the database it works, but I don't want to do that.
Contents of Php File:
$query("SELECT username FROM client WHERE username = :username");
$query_params = array(
':username' => $username
);
$db->DoQuery($query);
$check_num_rows = $db->fetch();
if ($username == NULL)
echo 'Choose a Username';
else if (strlen($username)<=3)
echo 'too short.';
else {
if ($check_num_rows ==0)
echo "Available!";
else if ($check_num_rows >= 1)
echo "Not Available.";
}
?>
body.php
<script type="text/javascript">
$(document).ready(function() {
$('#wowson').load('functions/check_username.php').show();
$('#username_').keyup(function() {
$.get('functions/check_username.php', { username: forms.username.value },
function(result) {
$('#wowson').html(result).show();
});
});
});
</script>
<label>Username:</label><br>
<input id="username_" name="username" required="required" type="text" placeholder="Username"/>
<div id="wowson">
</div>
database class
class database {
public function initiate() {
try
{
$this->database = new PDO("mysql:host='host';dbname='db", 'user, 'pass');
}
catch(PDOException $e)
{
$error = "I'm unable to connect to the database server.";
die("Failed to connect to database: " . $e->getMessage());
}
}
public function DoQuery($query, $query_params) {
try
{
$this->result = $this->database->prepare($query);
if ($query_params != null)
{
$this->result->execute($query_params);
}
else
{
$this->result->execute();
}
}
catch(PDOException $e)
{
die();
}
}
public function fetch() {
return $this->result->fetch();
}
}

When you load your original page, you are creating your object from your database class, right?
Well, when you are using Ajax to query the server about the username, that is a totally new request, and it knows nothing about the previous requests.
As such, just add something like require_once('my/path/database.php'); $db = new database(); to your PHP script which responds to the ajax request.

Related

Phpmailer Script Not Executed

I am writing this code where there is 2 user type : Normal User & Admin User.
Normal User Submit Data To Admin User, Both Admin (More Then 1 Admins In database) & Normal User Should Receive Email Regarding The Submission Of Data.
The submission and retrieving of the data is working fine. But in the Email Part, I reuse the code from my registration part that works for the submission code, Result is, It does not read the $mail.
Both of my registration and submission files are in the same folder. (Path should be working fine).
The logic also seems fine. Maybe i forget or miss something ? Could use a help to check my code.
...//
if ($conn->query($sqlDeleteSelected) === TRUE)
{
require_once "../assets/inc/phpmailer/PHPMailerAutoload.php";
$mail = new PHPMailer(true);
try
{
$sqleMail = "SELECT * FROM users_details WHERE users_Admin_University_Name = '$basket_UniCourse_UniName_1'";
$resultSqleMail = $conn->query($sqleMail);
while($dataResultSqlMail=mysqli_fetch_assoc($resultSqleMail))
{
$mail->AddAddress($dataResultSqlMail['users_Email']);
}
$mail->From = "myemail#gmail.com";
$mail->FromName = "MyName";
$mail->isHTML(true);
$mail->Subject = 'Application Registered';
$mail->Body = 'Congratulations!';
$mail->Send();
if($mail->Send())
{
// echo "Message has been sent successfully";
?>
<script type="text/javascript">
alert("sucesss");
</script>
<?php
}
else
{
?>
<script type="text/javascript">
alert($mail->ErrorInfo);
</script>
<?php
}
}
catch (phpmailerException $e)
{
echo $e->errorMessage();
}
catch (Exception $e)
{
echo $e->getMessage();
}
}
//..
Thank You So Much.
I'm not sure if I understand you 100% correctly but I assume that the java script "success" or the alert is not executed? This is because your if condition is not used properly. Actually you are trying to send the email twice:
$mail->Send();
if($mail->Send())
{...
A better way to see if the email was send successfuly is using a try&catch:
try {
$mail->send();
// print success message
} catch (Exception $e) {
// print error message
}

how to pass variables between 2 php files

I have two php files to make authentication to active directory users, i want to get the attribute url from it and pass this variable $data from authenticate.php to login.php if the function returned true to be in the location of header("Location: *URL*");,how can this be done?
authenticate.php:
<?php
// Initialize session
session_start();
function authenticate($user, $password) {
if(empty($user) || empty($password)) return false;
// Active Directory server
$ldap_host = "CRAMSDCR01V.cloud4rain.local";
// connect to active directory
$ldap = ldap_connect($ldap_host);
$ldap_dn="OU=by-style,DC=cloud4rain,DC=local";
// verify user and password
if($bind = #ldap_bind($ldap, $user, $password))
{
$result = ldap_search($ldap,$ldap_dn, "(cn=*)") or die ("Error in search query: ".ldap_error($ldap));
$data = ldap_get_entries($ldap, $result);
echo $data["url"];
return true;
}
else
{
// invalid name or password
return false;
}
}
?>
login.php:
<?php
include("authenticate.php");
// check to see if user is logging out
if(isset($_GET['out'])) {
// destroy session
session_unset();
$_SESSION = array();
unset($_SESSION['user'],$_SESSION['access']);
session_destroy();
}
// check to see if login form has been submitted
if(isset($_POST['btn-login'])){
// run information through authenticator
if(authenticate($_POST['userLogin'],$_POST['userPassword']))
{
// authentication passed
header("Location: authenticate.php?$data");
die();
} else {
// authentication failed
$error = "Login failed: Incorrect user name, password, or rights<br /-->";
}
}
// output logout success
if(isset($_GET['out'])) echo "Logout successful";
?>
login.php
<?php
include("authenticate.php");
That essentially acts like pasting the contents of authenticate.php inside login.php so although it's technically 2 files, it acts as if it's just the one - however $data is defined within the authenticate() function and so is only scoped within that function.
In authenticate.php - return the data from the function
// verify user and password
if($bind = #ldap_bind($ldap, $user, $password))
{
$result = ldap_search($ldap,$ldap_dn, "(cn=*)") or die ("Error in search query: ".ldap_error($ldap));
$data = ldap_get_entries($ldap, $result);
// echo $data["url"]; // I assume this is just for debugging...
// return $data from the function which should be "truthy"
return $data;
}
else
{
// invalid name or password
return false;
}
In login.php - evaluate the return from the authenticate() function - since PHP is loosely typed any (non-empty) string returned by the function can be evaluated as being "truthy" - the only other returns you have from the function are false so...
// run information through authenticator
if($authData = authenticate($_POST['userLogin'],$_POST['userPassword']))
{
// authentication passed
// renamed the variable $authData just for clarity
header("Location: authenticate.php?$authData");
die();
}
else {
// authentication failed
$error = "Login failed: Incorrect user name, password, or rights<br />";
}
Not sure why you have $_SESSION = array(); in login.php but if you want to pass $data from one php to another then just set it in session as
$_SESSION['data'] = $data;
ang to get it in the other file use
$data = $_SESSION['data'];

How can I keep PHP session alive with AJAX in native JS?

My HTML file calls functions on the JS file which pass parameters to the PHP file to call specific functions. My problem is that I would like the PHP session to stay alive so that when the user calls the login function, the $connection variable stays alive and can be used when the user eventually calls the loadBD function and Ajax calls the PHP file, the $connection variable is empty. I know I could use a file with the login details and include it at the start of the PHP file, but that won't work, because I don't know the details yet. How can I only login once?
Here is the JS file:
function runScript(params) {
xhr = new XMLHttpRequest();
xhr.open('POST', 'scripts.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById("demo").innerHTML = xhr.responseText;
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(encodeURI(params));
}
function login() {
var params = "func=login";
params += "&svr=" + document.getElementById('srv').value;
params += "&name=" + document.getElementById('name').value;
params += "&psw=" + document.getElementById('psw').value;
;
runScript(params);
}
function loadBD() {
var params = "func=load_db";
runScript(params);
}
Here is my PHP file:
<?php
$func = $_POST["func"];
$connection;
switch ($func) {
case 'login':
login();
break;
case 'load_db':
load_db();
break;
default: echo 'Function Error';
break;
}
function login() {
$connection = #mysqli_connect($_POST["svr"], $_POST["name"], $_POST["psw"]) or die("initial host/db connection problem");
if(errorCheck($connection)) {
getDatabases($connection);
}
}
function errorCheck($connection) {
if (!$connection) {
echo "internal error " . mysqli_errno();
return FALSE;
} else {
return TRUE;
}
}
function getDatabases($connection) {
$result = mysqli_query($connection, "SHOW DATABASES");
$available = array();
$index = 0;
while( $row = mysqli_fetch_row( $result ) ){
if (($row[0]!="information_schema") && ($row[0]!="mysql")) {
echo $row[0];
$available[$index] = $row[0];
$index += 1;
echo "<a href='javascript:loadDB();' >Load $row[0]</a>";
echo "<br>";
}
}
}
function load_db() {
echo "loading";
echo $connection;
}
?>
This is extremely insecure and a very bad idea. You are exposing your database credentials to the world on your web page. Standard practice is to store your database configuration in a secure location on your server and reference that config file directly from PHP.
Keeping database connections alive between requests is separate from PHP sessions. It depends very much on the details of your setup, so see the official docs for details.
PHP sessions themselves are "alive" in the sense they are tracked across requests via the session cookie. As long as the same cookie exists and the session hasn't expired, you do not need to do anything extra to keep it "alive".
You can't keep the connection open between requests; that's not really how PHP works (by default, anyway). What you could do is store the connection details for the user session in PHP's $_SESSION and use that to reestablish the connection to the database when the user hits your PHP script.

php function that sends message to XMPP server give no log and doesn't work

Im working on getting a webpage where users input a text in a form and click submit. From there it validates the input and sends it to a php function that uses JAXL 3.0 library to send the message to my XMPP server.
My problem is that when I call the JAXL function nothing just happens. it's like it can't finish the function as the next function never gets it's call. if I swap the order around the other functions gets called but it still doesn't finish the sendmessage() function.
I'm rusty/new in php and I can't get JAXL to provide a log or anything to debug where my issue is.
If anyone know how to debug this php/JAXL function properly it would be a large help.
I've searched the web around and looked at examples for JAXL but can't find my issue :/
EDIT: Tried some debugging with ECHO. I can't get a ECHO out if it's posted below my Create client. If I ECHO right above it works.
My Sendmessage function:
function sendping()
{
//get the form elements and store them in variables
$ping_text=$_POST["pingtext"];
// Config Details
$host = 'example.com';
$user = 'host';
$pass = 'password';
// Create Client
$client = new JAXL(array(
'log_path' => '/var/log/jaxl.log',
'jid' => $user.'#'.$host,
'pass' => $pass,
'log_level' => JAXL_INFO,
'auth_type' => 'PLAIN'
));
// Add Callbacks
$client->add_cb('on_auth_success', function() use ($host, $client, $ping_text) {
$client->send_chat_msg($host.'/announce/online', $ping_text);
$client->send_end_stream();
});
$client->add_cb('on_auth_failure', function($reason) use ($client)
{
$client->send_end_stream();
_info("got on_auth_failure cb with reason: $reason");
});
$client->add_cb('on_disconnect', function() use ($client)
{
_info("got on_disconnect cb");
});
// Startup Client
$client->start();
My hole .php page:
<?php
/*
Template Name: Stahp Ping
*/
require 'jaxl.php';
get_header(); ?>
<div id="hidden_div" style="display:none; margin-left:auto; margin-right:auto; margin-top:20px;
text-align:center;">
<p>Ping has been sent </p>
</div>
<div style="width:850px !important;
margin-left:auto;
margin-right:auto;
margin-top:20px;
text-align:center;" id="pingform">
<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']);?>" method="post" name="stahpbox">
<textarea name="pingtext" rows="8" cols="60"></textarea>
<input type="submit" value="Send Ping" />
</form>
</div>
<script type="text/javascript">
function showHide() {
var div = document.getElementById("hidden_div");
var pingdiv = document.getElementById("pingform");
if (div.style.display == 'none') {
div.style.display = '';
pingdiv.style.display='none';
}
else {
div.style.display = 'none';
pingdiv.style.display = '';
}
}
</script>
<?php
function sendping()
{
//get the form elements and store them in variables
$ping_text=$_POST["pingtext"];
// Config Details
$host = 'example.com';
$user = 'user';
$pass = 'password';
// Create Client
$client = new JAXL(array(
'log_path' => '/var/log/jaxl.log',
'jid' => $user.'#'.$host,
'pass' => $pass,
'log_level' => JAXL_INFO,
'auth_type' => 'PLAIN'
));
// Add Callbacks
$client->add_cb('on_auth_success', function() use ($host, $client, $ping_text) {
$client->send_chat_msg($host.'/announce/online', $ping_text);
$client->send_end_stream();
});
$client->add_cb('on_auth_failure', function($reason) use ($client)
{
$client->send_end_stream();
_info("got on_auth_failure cb with reason: $reason");
});
$client->add_cb('on_disconnect', function() use ($client)
{
_info("got on_disconnect cb");
});
// Startup Client
$client->start();
}
//Validation and redirection to send to jabber
// Initialize variables and set to empty strings
$pingtextERR="";
// Validate input and sanitize
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true; //Your indicator for your condition, actually it depends on what you need. I am just used to this method.
if (empty($_POST["pingtext"])) {
$pingtextERR = "Text is required";
$valid = false; //false
echo "<script type='text/javascript'>alert('$pingtextERR');</script>";
}
//if valid then redirect
if($valid){
echo "<script> showHide(); </script>";
sendping();
}
}
?>
Apprently the issue was that the PLAIN auth. isn't working for JAXL, so changed it to another AUTH and it worked fine.

Add and retrieve to mysql

I am building a small php application where you can add people and then see them on a page. When I was simply adding it went fine, but then I started using a switch and now it doesn't work to either add or retrieve. I cannot see any problem in my syntax, can anyone see something wrong?
php
<?php
$con = mysql_connect("hostWasHere","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbIsHere", $con);
try{
switch($_POST['action'])
{
case 'retrieve':
$show=mysql_query("Select * from test",$con);
while($row=mysql_fetch_array($show)){
echo "<li><b>$row[firstName]</b> : $row[lastName]</li>";
}
mysql_close($con);
break;
case 'new':
$sql="INSERT INTO test (firstName, lastName)
VALUES
('$_POST[fname]','$_POST[lname]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
break;
}
}
?>
The javascript using this is :
function saveToServer() {
alert("clicked");
$.post("api.php", {
'action': "new",
'fname': $('#fname').val(),
'lname': $('#lname').val()
},
function () {
alert("succes");
}
);
}
function getFromServer() {
console.log("in get!");
$.ajax({
type: "post",
url: "api.php",
data: "action=retrieve",
success: function (data) {
$("#comment").html(data);
console.log("success!");
}
});
}
You are using a try block without any catch or finally – this doesn't work. Most likely, your server is configured not to output any errors, so it dies silently.
A few other remarks:
As pointed out in the comments, please use PDO or MySQLi instead of the deprecated MySQL class.
Beware of SQL injection and always sanitize properly, no excuses. (My code below with PDO uses prepare and takes care of this.)
Use quotes when you're accessing an array with a string as key: $_POST['fName'] or $row["lName"], as opposed to $row[lName].
Output all errors while you're developing your page by adding error_reporting(E_ALL) at the top of your file. Note that server settings may still suppress the error output, but this generally takes care of everything.
Using a switch statement with a lot of code is never a good idea; you want to keep all code there rather lightweight or switch to a combination of if, else if and else.
Enough talk. Here's my edit for your page, using PDO instead of the deprecated MySQL family.
<?php
error_reporting(E_ALL);
// PDO has more options to read about
// for initialization, but this should do for now
$con = new PDO("host=host;dbname=db_here", "username", "password");
if (!$con) {
die('Could not connect: !');
}
// Do some validation on $_POST before using it.
$action = '';
if(isset($_POST['action'])) {
$action = $_POST['action'];
}
if($action == 'retrieve') {
$sql = $con->execute('SELECT * FROM test');
$rows = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row) {
echo '<li><b>'.$row['firstName'].'</b> : '.$row['lastName'].'</li>';
}
$con = null;
}
else if($action == 'new') {
$sql = $con->prepare('INSERT INTO test (firstName, lastName)
VALUES (?, ?)');
// TODO: more checks on fname and lname before accepting
if(isset($_POST['fname']) || isset($_POST['lname'])) {
$result = $sql->execute( array($_POST['fname'], $_POST['lname']) );
if(!$result) {
die('Error occured');
}
else {
echo 'Added 1 row';
}
}
$con = null;
}
else {
// TODO: Default page
}
PS: Please don't ever trust user input. The code is still inserting $_POST values rather blindly (just checking that they're at least set), further checks with is_scalar() and some length checks would probably be good.
I hope this can help – good luck with your project!

Categories