Webservices in PHP and Oracle Database - php

i want to create a web service to check if the login
i create first an html form
<form action="webservice_ocl.php" method="post">
<p>Username:
<input name="user" type="text" />
</p>
<p>
Password:
<input name="password" type="password" />
</p>
<p>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
</p>
</form>
then i create a php file " webservice_ocl.php to do the traitement
<?php
session_start();
try {
$dbh = oci_connect('test', '123456', 'localhost/XE');
} catch (PDOException $e)
{
echo $e->getMessage();
}
if ($_POST['user'] != null and $_POST['user'] != "" and $_POST['password'] != null and $_POST['password'] != "")
{
$username = $_POST['user'];
$password = $_POST['password'];
$sth = oci_parse($dbh ,"SELECT * FROM utilisateur WHERE LOGIN='$username' and PASS='$password'");
oci_execute($sth);
if(oci_fetch($sth)){
echo "Nice";
}
else { echo "nono";}
}
?>
i want to konw , the php file " webservice_ocl.php " is a webservice ??
and how to call them in html using ajax ??
i want to use this on mobile developpement

I wouldn't really class webservice_ocl.php as a webservice as such, a webservice (in my opinion) is usually an SOAP/REST complaint API. See http://en.wikipedia.org/wiki/Web_service.
As for calling this with AJAX, I would personally look into jquery - namely the $.post function, I use this all the time and find it much easier than plain javascript.
Lastly, i would advise you look at how you have wrote your SQL statements - as pointed out by Quentin you are vulnerable for injection, which I have had done before (whoops) and believe me it is not nice!
Hope this helps.
Smithey.
Edit - If your looking at mobile apps, take a look at jquery mobile ;). I'm using it for a project im working on at the minute, its pretty cool!

====== in form.html change type="submit" to type="button" and delete action+mithod attr
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<form id="my-form" >
<p>Username:
<input name="user" type="text" />
</p>
<p>
Password:
<input name="password" type="password" />
</p>
<p>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
</p>
</form>
<div id=result >the result will display here</div>
<script type="text/javascript">
$("#btnSubmit").click({
$.post(
"webservice_ocl.php",
$("#my-form").serialize(),
function(data){ $("#result").html(data); }
);
});
</script>

Related

How can i separate php code with html to have them both clean and separate in different files?

what i want to do is something like this
<div id="login">
<h6> Log in </h6>
<form method="POST">
<p> Usuario: <input type="text" name="user"/></p>
<p> Password: <input type="text" name="pass"/></p>
<input name="accion" value="login" type="hidden"/>
<input type="submit" value="Send" />
</form>
</div>
and i want to separate with a php code that makes me log in if you have cirtain user, what i did was :
<?php
session_start();
if($_POST["accion"] == "login"){
if($_POST["user"]=="root" && $_POST["pass"]=="123"){
$_SESSION["usuario"]= $_POST["user"];
$_SESSION["time"]=time() - $_SESSION;
echo $_SESSION["usuario"];
}else{
$error= "Usuario y/o contraseƱa incorrecto";
echo $error;
}
}
$logeado = isset($_SESSION["usuario"]);
?>
so, how do i link this functions so that when the client hits the submit it executes this function? After that i would like to know how to change my view there if he succeeds to his username and to tell him he is logged like a message, if you can help me i'd appreciate it! thank you
Add the form action to your form.
<div id="login">
<h6> Log in </h6>
<form method="POST" action="path-to-your-file.php">
<p> Usuario: <input type="text" name="user"/></p>
<p> Password: <input type="text" name="pass"/></p>
<input name="accion" value="login" type="hidden"/>
<input type="submit" value="Send" />
</form>
</div>
Add header('Location: redirect-location.php'); to your login success function to redirect the user.
<?php
session_start();
if($_POST["accion"] == "login"){
if($_POST["user"]=="root" && $_POST["pass"]=="123"){
$_SESSION["usuario"]= $_POST["user"];
$_SESSION["time"]=time() - $_SESSION;
echo $_SESSION["usuario"];
header('Location: redirect-location.php');
}else{
$error= "Usuario y/o contraseƱa incorrecto";
echo $error;
}
}
$logeado = isset($_SESSION["usuario"]);
?>
What you want to do is called MVC pattern, or Model View Controller pattern. It separates responsibilities of the different components of a web application.
The only best practice to answer your question is to use a PHP framework. Any framework. Personally I would recommend you to use Laravel, but there are plenty of them: Zend, CakePHP, Symfony, Yii.

XAMPP : My input (name and pass) always has root and password inside of it..how so?

Today I was trying to create a login page with PDO class in PHP. It worked fine but my problem is my input always have a "root" string value for my first input, and a password inside my second input. Why and how can I erase that? I tried to put a "placeholder" inside of each input, and it still doesn't replace it. Oh, by the way, my input has a "yellow" background...kinda weird. And when I erase it manually, they return white as usual..
This is my code :
<?php
include_once('user.php');
if (isset($_POST['submit'])) {
$name = $_POST['username'];
$pass = $_POST['password'];
$object = new User();
$object->Login($name,$pass);
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?= $_SERVER['PHP_SELF']; ?>">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" name="submit" value="Log In">
</form>
</body>
</html>
Cache, or saved credentials problem.
Try:
<input type="text" name="username" value="" placeholder="" autocomplete="off">

How to validate login form using JavaScript PHP and MariaDb?

I am starting to learn JavaScript today. I want to validate the user login form using JavaScript and MariaDB. I know how to connect to database using PHP, but if I have to do it through JavaScript, is that possible? I
I want to get the user's table using JavaScript. The user will get an error when, of course, their username/password does not match what they have on the database. I am really curious about this.
<form name="loginForm" id="loginForm" method="post" action="login.php" onsubmit="return validateLoginForm();">
Username: <input type="text" name="username">
Password: <input type="password" name="password"> <br/>
<input type="submit" name="login" value="Login"/>
</form>
If the user click the button, will connect to the table using JavaScript. But I dont know how to do it.
Thanks.
I am going to use jquery which is an excellent javascript framework.
Since you have no code to show, I will only post for you pseudo code to show you how you can validate a username and password using jquery,php and mariadb. The mysqli API in php will work with mariadb
HTML\Client side
<html>
<head>
<script src="jquery-1.X"></script>
<script>
$(document).ready(function(e){
var username=$("#username").val();
var password=$("#password").val();
$("#login").click(function(){
if(username=="" && password=="")
{
alert("username or password is blank");
e.preventDefault();//prevent the form from submitting.
}
})
})
</script>
</head>
<body>
<form name="loginForm" id="loginForm" method="post" action="login.php">
Username: <input type="text" name="username" id="username">
Password: <input type="password" name="password" id="password"> <br/>
<input type="submit" name="login" id="login" value="Login"/>
</form>
</body>
</html>
PHP Side - Login.php
<?php
include("conn.php");
$username=$_POST['username'];
$password=sha1($_POST['password']); //my passwords are hashed in the database using the sha1
$checklogin="SELECT * FROM users_tbl WHERE Username=? AND Password=?";
$query = $connection->prepare($checklogin);
$query->bind_param("ss",$username,$password);
$query->execute() or die($connection->error);
$count = $query->num_rows;
if($count==1)
{
while($row=$query->fetch_assoc)
{
$_SESSION['username']=$row['Username'];
}
header("Location:index.php")
}
?>
PHP Connection File - conn.php
<?php
//connect to database
$connection = new mysqli("localhost","user","password","mydatabase");
if(mysqli_connect_errno()){
printf("Connection failed: %s\n",mysqli_connect_error());
exit();
}
?>
Please not this is a very basic login script to give you a general understanding. You need to read up on jquery and PHP in detail.

php javascript alertbox have to click 2 times before it show

I'm doing php that is textbox a value empty it will open a alertbox (I'm using javascript in here )
this is my code
<?php
include('config.php');
if(isset($_POST['submit'])){
$username=$_POST['username'];
?>
<script>
function validate(){
if(document.forms[0].username.value==""){
window.alert("You must enter both values");
return false;
}
}
</script>
<?php
}
?>
<html>
<div><p>Member Profile</p>
<form action="testing.php" method="POST" onsubmit="return validate();">
Username<br>
<input class="user" type="text" name="username" id="username" /><br>
<input type="submit" name="submit" value="register" />
</form>
</div>
</html>
The problem is i have to click 2 times before the alert show
please help me to solve this problem
It's because the script is inside the php if(isset){} block, one click submits the form, which generates the script and then it works the second time.. try this setup instead:
<?php
include ('config.php');
if (isset($_POST['submit']))
{
$username = $_POST['username'];
}
?>
<html>
<head>
<script>
function validate () {
if (document.forms[0].username.value == "") {
window.alert("You must enter both values");
return false;
}
}
</script>
</head>
<body>
<div>
<p>
Member Profile
</p>
<form action="testing.php" method="POST" onsubmit="return validate();">
Username
<br>
<input class="user" type="text" name="username" id="username" />
<br>
<input type="submit" name="submit" value="register" />
</form>
</div>
</body>
</html>
Edit:
I've moved the script tag inside the head tag. I'm not sure if there are any implications for having the script outside but just to be sure I've moved it.
2nd Edit: (OCD is kicking in)
I've added body tags, not sure if you copied and pasted this code but it looked weird to me :)

How to do a ajax request for login

I have this in my PHP code, and it currently does the login request in the same login.php page but now i want to do it with Ajax. Basically I have this in the login.php
echo '<form method="post" ><div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="submit" value="Submit" name="submitlogin" class="button" />
</div>';
I would like to still use this but have a login_request.php or something where i can send the username and password validated and then change the <div id=login> to say you are logged in!</div> I can do it the conventional way, with the form post .. but now I would like to try it with Ajax.
Any help will be much appreciated.
Regards
What have you tried so far? This is how I would start:
This should get you started:
HTML:
<form id="loginForm">
<div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="button" value="Submit" id="submitlogin" class="button" />
</div>
</form>
jQuery:
$("#submitlogin").click(function() {
inputs = //grab then inputs of your form #loginform
$.ajax ({
url: "urltoyourloginphp.php",
data: inputs,
success: function() {
$("#login").html("You are now logged in!");
}
});
})
I wrote this a while ago, it's not quite a full ajax login (i.e. at the end it does still redirect you), but it may serve as a basis for a full ajax login. As a plus you actually don't need https (that was the whole point of this little project).
https://github.com/eberle1080/secure_http_login/blob/master/login.php
The high level steps go something like this:
Ask the server for a seed value (a salt) using an ajax request
Hash the password + seed using a sha1 sum
Ask the server to verify the username and salted + hashed password
If it's valid, the server sets a session cookie indicating that the user is logged in
The server responds to the ajax request with a success / fail message
jQuery has built in .post() and .serialize() methods for wrapping up a form.
$.post("login.php", $("#loginForm").serialize(), function(data) {
//pass information back in with data. if it's JSON, use $.parseJSON() to parse it.
alert('either logged in or errored');
);
You will also need to edit your form so it has an id, like: <form id="loginForm">...
I don't know PHP but will give you an example of how I would have done it with vbscript (classic asp) so you may try to adapt it to PHP as needed.
I, in my applications, don't use the form tag since I first used ajax. So, here we go:
login html page:
include jquery
<script type='text/javascript' src='your-jquery-url'></script>
<script type='text/javascript'>
function tryLogin() {
var inputs='userName='+$('logInUsername').val()+
'&userPassw='+$('logInPassword').val();
//notice that I changed your name= to id= in the form
//notice the '&' in the '&userPassw=
$.post('your-login-validation-page',inputs,function(data) {
eval('var json='+data);
if (json['success'] == 'true') {
$('#loginForm').html('<p>Congratulations! You\'ve been logged in successfully</p>')
} else {
alert(json['errorMessage']);
$('#logInUsername').focus();
}
});
}
</script>
<div id='loginForm' >
<label for="login">User Name</label>
<input type="text" id="logInUsername" />
<label for="Password">Password</label>
<input type="password" id="logInPassword" />
<button onClick='tryLogin(); ' >LOGIN</button>
</div>
login-validation-page
[in vbscript]
user = request.Form("userName")
passw = request.Form("userPassw")
"if is there this user" (coded as if there was a database look up...)
"if the password = passw" (coded as comparing the values)
response.write "{'sucess':'true'}"
else
response.write "{'success':'false','errorMessage':'wrong password'}"
end if
else
response.write "{'success':'false','errorMessage':'user not found'}"
end if
---> end of login-validation-page

Categories