I'm trying to make some sort of communication between two servers(can be called license verification).
Already got this:
index.php
if ($verification == 1) {
echo "license validated";
}
else {
echo "this license key does not exist.";
}
validate.php
$license_key = mysql_real_escape_string($_GET['license_key']);
$query = "SELECT license_key FROM users WHERE license_key = '$license_key'";
$mysqli = new mysqli();
$mysqli->connect($db_hostname, $db_username, $db_password, $db_name);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}
$result = $mysqli->query($query);
$row_cnt = $result->num_rows;
if ($row_cnt == 1) {
return true;
}
else {
return false;
}
What I can't figure out is how to send that request from index.php to validate.php ( this 2 files are not in same server ) and how to get back to index.php information what it returns (true or false).
Use file_get_contents:
$verify_result = file_get_contents("http://validation.domain.com/validate.php?license_key=$key");
if ($verify_result == 'license validated') {
...
}
Probably the easiest way would be to setup a service. Here's one of numerous tutorials out there.
For example, let's say that the validation server's hostname is val.com. You could setup a service there that looks like:
val.com/validation/validate?dataToValidae=<validationString>
Be sure to send the request over SSL if you don't want it to be intercepted.
You could then have the service return whether or not the validation succeeded, and then check for that in your code.
Related
I'm a beginner of PHP coding which I face this problem and I tried to fix it.
I have search through stackoverflow for answers but it stills no good.
This is my Login form.php file
<form name = 'LoginForm' method = 'POST' action = 'verifyUser.php'>
<br />
E-MAIL: <input type = "Textbox" Name = "App_Email"><br><br>
PASSWORD: <input type = "password" Name = "App_Password"><br><br>
<input type = 'Submit' name = 'Login' value = 'Log in'><br><br>
</form>
This form will goes to verifyUser.php and these are codes
include ('DBconnect.php');
$username = $_POST['App_Email'];
$pass = $_POST['App_Password'];
if($username=='' || $pass=='') {
header("Location:login.php?id=Some fields are empty");
}
$result = mysql_query("SELECT * FROM applicant_acct ");
if(!$result) {
die("Query Failed: ". mysql_error());
} else {
$row = mysql_fetch_array($result);
if ($username==$row['App_Email']) {
if($username==$row['App_Email'] && $pass==$row['App_Password']) {
header("Location: index.html?id=$username");
} else {
header("Location:login.php?id=username or your password is incorrect. Please try again");
}
}
}
And final DBconnect.php
<?
$dbc = mysql_connect('localhost','root','root') OR die('Wrong Connection!!!!!!!');
mysql_select_db('onlinerecruitment') OR die ('Cannot connect to DB.');
?>
I really have no idea why it shows "Query Failed: No database selected"
I think the problem is in verifyUser.php but have no idea where.
And another thing, after I logged in how can I generate the text "Welcome - "Username"" and provide them the logout button?
Please help.
Thank you.
Generally you may want to research a graphical user interface such as XAMPP or MySQL workbench until you are more comfortable with Database systems.
Here it seems like most of the improvements can be made in you DBConnect.php file. You are beginning and I can appreciate that. Consider something along the following lines that incorporates additional the security of PDO:: static calls.
<?php
public function _dbconnect($hostpath, $database, $username, $password){
try {
$this->conn = new PDO("mysql:host = {$hostpath};
dbname - {$database};
charset = utf8",
$username,
$password);
} else { exit(); }
?>
If this particular code block doesn't help I would highly recommend that you continue by investigating PDO:: calls.
<?php
include ('DBconnect.php');
if(isset($_POST['Login'])){
$username = $_POST['App_Email'];
$pass = $_POST['App_Password'];
if(empty($username) || empty($pass) || ctype_space($username) || ctype_space($pass)){
header("Location:login.php?error=1");
} else {
$result = mysql_query("SELECT * FROM applicant_acct");
if(!$result) {
die("Query Failed: ". mysql_error());
} else {
$row = mysql_fetch_array($result);
if($username==$row['App_Email'] && $pass==$row['App_Password']) {
header("Location: index.php?id=$username");
} else {
header("Location:login.php?error=0");
}
}
?>
I have a lot to say about your code.
Use isset function . This function check if something was done.
Check your database details again. Maybe you wrote something
wrong (misclick or something)
Use $_GET['error'] to get errors. I set 1 = for empty characters and 0 for 0 match between database and inputs.
Use sessions for after login message. You can also use Session to handle your errors.
EDIT: I recommend you to start to learn MySQLi or PDO.
I have created a script for users to invite a friend using a email address, the email address and a randomly generated 10 character string 'inviteCode' is sent to a table called 'referrals'.
The invited person then receives an email with a URL link that contains their email and their unique inviteCode; http://website.com/register.php?email=email&inviteCode=1234567890
When the user clicks on the link the page register.php should then check the URL and if they data is valid in the 'referrals' table. If so then I have an include line to add the register form, if not then they are redirected. The point is nobody can access register.php unless they have been invited and sent a link.
At the moment the page keeps redirecting to index.php;
Register.php script:
<?php
include 'config.php';
if (isset($_GET['email'],$_GET['inviteCode'])) {
$mysqli = new Mysqli(/* your connection */);
$email = $mysqli->real_escape_string($_GET['email']);
$inviteCode = $mysqli->real_escape_string($_GET['inviteCode']);
$sql = "SELECT email,inviteCode FROM referrals WHERE email='".$email."' AND inviteCode='".$inviteCode."'";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) { //check if values are correct and available in database
echo 'lol';
}
else
{
echo 'no';
exit;
}
}
else
{
echo 'problem'; //Page not accessible if neither email nor referral entered
}
?>
I replaced the first if statement with:
if(!isset($_GET['email']) || !isset($_GET['inviteCode'])) {
die(header('Location: index.php'));
} else
And I receive a blank page with no errors. I believe there may be something wrong with the email and invite code not being set.
Any help on this would be much appreciated (Y) thanks.
You should really be looking at handling the errors first. Try something like this:
if(!isset($_GET['email']) || !isset($_GET['inviteCode'])) {
die(header('Location: index.php'));
} else {
$mysqli = new Mysqli(/* your connection */);
$email = $mysqli->real_escape_string($_GET['email']);
$inviteCode = $mysqli->real_escape_string($_GET['inviteCode']);
$sql = "SELECT email,inviteCode FROM referrals WHERE email='$email' AND inviteCode='$inviteCode'";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) { //check if values are correct and available in database
include'register-form.php';
} else {
die(header('Location: index.php'));
}
}
Breakdown
The if block checks to see if GET[email] or GET[inviteCode] are not set. if that is the case, kill the app with die() and redirect the user to index.php.
The second change is this line:
if ($query->num_rows > 0) {
That will check to ensure the rows returned are more than 0 (meaning there are actually rows returned.) Because you were just testing the presence of the $query->num_rows before.
Another Note:
Turn on error reporting, it will help you emensly during debugging:
ini_set('display_errors', 1);
error_reporting(E_ALL);
You could alternatively change your sql query to select the COUNT(id) and check if that is greater than 0, but that seems like overkill for what you're trying to do.
Do this to find out if anything is being returned by your query:
Start by making sure that the connection to your database is succeeding:
$mysqli = new Mysqli(/* your connection */);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$email = $mysqli->real_escape_string($_GET['email']);
Add that then let us know the results afterward, also provide specific error messages.
To debug your num_rows, replace this:
$query = $mysqli->query($sql);
if ($query->num_rows) //check if values are correct and available in database
{
include'register-form.php';
}
With this:
$query = $mysqli->query($sql);
$count = $query->num_rows;
print $count;
exit;
if ($query->num_rows) //check if values are correct and available in database
{
include'register-form.php';
}
If it shows 0, I have a suspicion it is because your sql statement needs to be concatenated.
"SELECT email,inviteCode FROM referrals WHERE email='".$email."' AND inviteCode='".$inviteCode."'";
i have this simple php code. Locally, with a simple xampp 1.7.3 the echo returns correctly "false" or "true". When i put the code online (on a server, i mean, and i do not have really knowdledge of how the server is made) it returns always "1". Why?
<?php
include "connectionToDb.php";
$nome_utente=$_GET['nome_utente'];
$queryUserAvailable = "SELECT * FROM utente where nome_utente='$nome_utente'";
$rsUserAvailable = connetti($queryUserAvailable);
if(mysql_num_rows($rsUserAvailable) == 0){
$valid=true;
}
else{
$valid=false;
}
echo json_encode($valid);
?>
ConnectionToDb.php
<?php
function connetti($SQL){
$conn = mysql_connect("localhost", "root", ""); //(online this data are obviously different)
$db = mysql_select_db("dbName",$conn);
$risultato = mysql_query($SQL,$conn)
or die("Query non valida: " . mysql_error());
return ($risultato);
}
?>
As it seems from the comments, JSON is not included in the server's PHP configuration.
You might want to consult your host and check whether you can include this by just overriding settings via a .htaccess directive
Maybe you can also first try:
if (!extension_loaded('json')) {
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
dl('json.dll');
} else {
dl('json.so');
}
}
I've read a lot of posts on this general subject but I still can't seem to figure it out.
I'm building a Mac/PC desktop application. When a user first authorizes the app, I want to store their info in an online Mysql database. I'm using the JUCE library to call and handle a php file online which in turn handles the updating of the online database. On my desktop app:
String url = "http://www.syntorial.com/onlinePHPFileToCall.php?email=" + email + "&computer=" + SystemStats::getComputerName();
URL authURL(url);
InputStream *input = authURL.createInputStream(true);
String result = input->readString();
And the php file:
<?php
$result = "";
$mysqli = new mysqli('localhost','username','password','dbname');
if (mysqli_connect_errno())
{
$result = "connection failed";
}
else
{
$mysqli->select_db("UserInfo");
$email = $_GET['email'];
$computer = $_GET['computer'];
$query = "UPDATE UserInfo SET computer = '$computer' WHERE email = '$email'";
if ($queryResult = $mysqli->query($query))
{
$result = "true";
}
else
{
$result = "false";
}
}
echo $result;
?>
The result comes back "true" on my desktop app, but the information doesn't actually get saved into the database. If instead of
InputStream *input = authURL.createInputStream(true);
I use:
authURL.launchInDefaultBrowser();
it opens up the php file in a browser and everything works fine. Any ideas what I'm doing wrong?
Joe,
Seems like one of your first question on this forum. So Welcome. You mentioned you want to store information in an online database. But while connecting you added db information about your local via
mysqli('localhost',
. Update localhost to point to an online database by finding its ip address/servername, username and password. Also you will have to ensure the computer where you run this application can connect to that online db.
Here is what I am ran on my local and worked for me.
<?php
$result = "";
$mysqli = new mysqli('localhost','root','','test');
if (mysqli_connect_errno())
{
$result = "connection failed";
}
else
{
$email = "xyz#yahoo.com";
$computer = "1mycomp";
$query = "UPDATE so1 SET computer = '$computer' WHERE email = '$email'";
/*
Printing the query to check what is being executed.
Remove the below line after program works.
*/
echo $query;
if ($queryResult = $mysqli->query($query))
{
$result = "true";
}
else
{
$result = "false";
}
}
echo $result;
Turns out the "true" argument in CreateInputStream was telling it to use POST data instead of GET so the call was ignoring the GET data. Thanks the help.
I have connected to a database for the first time with oop and stright away come up with an issue, below is my code which i'm struggling with:
$q = 'SELECT * FROM test';
$sqli->query($q);
if($sqli->query($q)){
echo "worked";
}
if($sqli->error){
echo $sqli->error;
}
I have checked for errors when connecting to the db and that works fine, but when I run this query I get no output, why? I expected an error or "worked", but have got neither.
Whats happening?
I have put some comments in the source code to help:
$q = 'SELECT * FROM test';
//$sqli is the result of a
//new mysqli("localhost", "user", "password", "database");
$resource = $sqli->query($q); // this returns a resource or false
if(!$resource) {
echo $sqli->error;
die; // do not process further
}
// process the results
$rows = $resource->fetch_all();
if ($rows) { // check if there are rows
echo "worked";
}
else {
echo "query is ok, but there are no rows";
}
You could also use $resource->fetch_object() which returns an object for output. Therefore if you wanted to print specific data from the result set, you would do something like
//table test.Name and test.Country
while ($rowobj = $resource->fetch_object()){
printf ("%s (%s)\n", $rowobj->Name, $rowobj->Country);
}
Good luck,
You could use this method, I hope it's what you are looking for. You will need to define the DB first. Then you can connect in OOP and test the connection is true or exit();
Let me know if this works for you. You can also define the DB in an external file and just do an include(); towards the top of your script for any pages needing connection to the DB.
define("SERVER","IP Address");
define("USER","DB USERNAME");
define("PASSWORD","DB PASSWORD");
define("DATABASE","DB NAME");
// This is for connection
$mysqli = new mysqli(SERVER, USER, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
exit();
}