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');
}
}
Related
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.
In my site im trying to include on the top of each page a "banner" that is itself a separate php page that queries a MySQL database to return a number that displays.
When i goto the exact URL of the banner php url (www.sitename.com/banner.php) it works perfectly.
However, when i include the banner into another page include'banner.php' it returns the following error: Database access error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
I have 2 ways i need to include this, my main site pages are all php. My forum is phpbb and the file i need to include is HTML so i used (Note, i did ../ back out to the banners root, its not a matter of my file not being found.
Im assuming that when including the scope is different. How would i correctly accomplish this include?
Banner.php
<?php
require("../mysql.inc.php");
check_get($tp, "tp");
$tp = intval($tp);
$link = sql_connect();
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
if (!$result) {
echo "Database error.<br>\n";
exit;
}
list($total) = mysql_fetch_row($result);
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="menu_css.css" media="screen"/>
</head>
<body>
<div class="menucenter">
<div class="Online"> <? echo"$total" ?> Online</div>
</body>
</html>
mysql.inc.php
<?php
$SQLhost = "****.db.****.hostedresource.com";
$SQLport = "3306";
$SQLuser = "****";
$SQLpass = "****";
$SQLdb = "****";
function sql_connect()
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
if ($SQLport != "")
$link = #mysql_connect("$SQLhost:$SQLport","$SQLuser","$SQLpass");
else
$link = #mysql_connect("$SQLhost","$SQLuser","$SQLpass");
if (!$link) {
echo "Database access error ".mysql_errno().": ".mysql_error()."\n";
die();
}
$result = mysql_select_db("$SQLdb");
if (!$result) {
echo "Error ".mysql_errno($link)." selecting database '$SQLdb': ".mysql_error($link)."\n";
die();
}
return $link;
}
function sql_query($link, $query)
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
$result = mysql_query("$query", $link);
if (!$result) {
echo "Error ".mysql_errno($link).": ".mysql_error($link)."\n";
die();
}
return $result;
}
function check_get(&$store, $val)
{
$magic = get_magic_quotes_gpc();
if (isset($_POST["$val"])) {
if ($magic)
$store = stripslashes($_POST["$val"]);
else
$store = $_POST["$val"];
}
else if (isset($_GET["$val"])) {
if ($magic)
$store = stripslashes($_GET["$val"]);
else
$store = $_GET["$val"];
}
}
?>
#Craig, there is a possibility that the include file contains other includes which are not getting the right path. Can you paste some codes of the include file for us to validate the error ?
EDIT:
You have a missing quote at the end of the query.
$result = sql_query($link, "SELECT COUNT(*) FROM online_count);
It should be
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
EDIT:
You have a problem with the quotes. See you check_get function. $val is a variable and you dont need quotes around it. Check the below code.
if (isset($_POST[$val])) {
if ($magic)
$store = stripslashes($_POST[$val]);
else
$store = $_POST[$val];
}
else if (isset($_GET[$val])) {
if ($magic)
$store = stripslashes($_GET[$val]);
else
$store = $_GET[$val];
}
EDIT:
Also remove the quotes from $query:
$result = mysql_query($query, $link);
First things first:
Remove the # from your mysql statements and see if you are getting any other errors related to variables or so. You should not suppress errors while debugging.
Try printing the host, port, user and password variables inside the sql_connect() function and see if you are getting the correct values in your function.
If you have access to your server, check if /var/lib/mysql/mysql.sock exists, and has sufficient permissions.
srwxrwxrwx 1 mysql mysql 0 Sep 21 05:50 /var/lib/mysql/mysql.sock
If all is well till this point, you might want to troubleshoot your MySQL service further. A restart would help flush the connections, if that is the issue. Check a similar thread in SO too.
I currently have a PHP file which will search my MySQL database and see if a user is logged in. If they are logged in, it will echo "Welcome 'username'. Logout" and if they're not logged in it will echo "Login. Register."
If I view this PHP file directly, it will echo out the correct text, depending on whether or not I am logged in. However, if I put into my HTML file using include it will only echo out the logged out text, regardless of whether I'm logged in.
Is there some conflict between PHP and HTML which will stop it from printing out the correct text maybe? It seems strange that it will work opening the PHP file itself, but not when it's included in HTML.
HTML code:
<?php include "loginreg/check.php"; ?>
Would the fact it's in a subfolder make a difference? Haven't included the PHP code as that itself is working, but I have got it if you need to see it.
Cheers
PHP code:
// Gets IP address
$ip = visitorIP();
// Connect to database
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die('Unable to select database');
$query = "SELECT * FROM loggedin WHERE userip='$ip'";
$result = mysql_num_rows(mysql_query($query));
if ($result == '0') {
mysql_close();
loggedOut();
return;
}
if (isset($_COOKIE['sid'])) {
$sessionid = $_COOKIE['sid'];
}
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
if ($row['sessionid'] == $sessionid) {
mysql_close();
loggedIn($row['id']);
} else {
mysql_close();
loggedOut();
}
}
function visitorIP() {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$TheIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$TheIp = $_SERVER['REMOTE_ADDR'];
}
return trim($TheIp);
}
function loggedIn($id) {
global $username, $password, $database;
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die('Unable to select database');
$query = "SELECT * FROM users WHERE id='$id'";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$fname = $row['fname'];
$sname = $row['sname'];
}
echo "<div class=\"fltrt\">Welcome, " . $fname . ". Logout</div>";
}
function loggedOut() {
echo "<div class=\"fltrt\">Login Register</div>";
}
Without seeing the code of both scripts this is just a guess, but a likely problem would be that you are outputting html (anything...) before you include your loginreg/check.php script.
That would render any session_start() statements in your included file useless as the headers already have been sent. And not being able to get to the session would lead to the error that you describe.
Edit: For cookies the same principle applies, they need to be set before the headers are sent so before you output anything to the browser.
Your issue is that you are setting cookies while inside a subdirectory. Use the path parameter of setcookie to ensure you're setting the cookie in the root folder of your website:
// Sets the cookie for the root of the domain:
setcookie("username", "foo", time() + 60 * 60, "/");
Correct me if I'm wrong here, but are you trying to use a PHP include in an HTML file? If so, that will never work (unless you've got some custom server config that will parse PHP code in HTML files).
PHP code is for PHP files. HTML code can work in HTML and PHP files. You cannot do a PHP include, in an HTML file.
I use this code to connect to a database:
#mysql_connect("localhost","root","") or die(mysql_error());
#mysql_select_db("ECOLE") or die (mysql_error());
#mysql_set_charset('utf8');
if(isset($_POST['profname_in'])){
$querycheck = "SELECT prof_som FROM prof_table
WHERE prof_som=$_POST[profsom_in];";
$_querycheck=mysql_fetch_array(mysql_query($querycheck));
if(isset($_querycheck['prof_som'])){
echo "0";
}else{
$query="INSERT INTO prof_table
VALUES('$_POST[profname_in]',
'$_POST[profcin_in]',
'$_POST[profsom_in]',
'$_POST[profville_in]',
'$_POST[profecole_in]',
'$_POST[profmat_in]',
'$_POST[profpass_in]');";
if(mysql_query($query)){
echo "1";
}
}
}
the echos is recupered by a javascript function (ajax):
function adding_prof_Reply() {
if(http.readyState == 4){
var response = http.responseText;
if(response==0){
document.getElementById('prof_validation').innerHTML = '<font color="red">'+response+'</font>';
}else if (response==1){
document.location.href="dir_paneau.php";
}else{
document.getElementById('prof_validation').innerHTML = '<font color="red">'+response+'</font>';
}
}
}
everything works good, the problem is when I use require('anyfile') in the php code then the test if(response==0) is always false even when respose==0 ; if I remove the line of require everything works as it should.
I need the require to not repeat the connection information, any ideas?
"i need the require to not repeat the connection information"
To only connect once, put the 'connection information' in a separate file, maybe dbConnect.php and use the function require_once('dbConnect.php') in the files which need a database connection.
This ensures you only connect to your database once, which may solve your problem.
<?php
function redirect_to_index_with_error(){
echo '<meta http-equiv="refresh" content="0;url=index.php">';
}
function go_to_home(){
echo '<meta http-equiv="refresh" content="0;url=home.php">';
}
$email = mysql_real_escape_string($_POST['username']); echo $email;
$pwd = mysql_real_escape_string($_POST['password']);
echo $pwd;
$query = "SELECT * FROM users WHERE email='$email' AND password=MD5('$pwd')";
echo "query variable created.";
mysql_connect("localhost","root","") or die(mysql_error());
echo "connected."; //nothing
mysql_select_db("mcp") or die(mysql_error());
$results = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($results) == 0){
redirect_to_index_with_error();
exit();
}
$userID = null;
$name = null;
$school = null;
$mod = null;
while($user = mysql_fetch_array($results)){
$userID = $user['ID'];
$name = $user['Name'];
$school = $user['School'];
if($user['Mod'] == '1')
$mod = true;
else
$mod = false;
}
if(!isset($_SESSION))
session_start();
//set session variables
$_SESSION["userID"] = $userID;
$_SESSION["name"] = $name;
$_SESSION["school"] = $school;
$_SESSION["mod?"] = $mod;
go_to_home();
exit();
?>
PHP echos everything up until "connected". It's not even showing a mysql error. I've had this code work flawlessly on Windows with WAMP, but not on Mac with MAMP. I've verified that the servers are running, so I can't tell what the problem is. I'm using PHP 5.3.6.
Your connection needs to be established before you call mysql_real_escape_string()
So move mysql_connect("localhost","root","") or die(mysql_error()); to the top.
Move the mysql_connect() statement above everything else.
// put this at the TOP
mysql_connect("localhost:3306","root","") or die(mysql_error());
Just as everyone else mentioned, see this note:
http://php.net/mysql_real_escape_string#refsect1-function.mysql-real-escape-string-notes
Also, you should see errors, in development, at least.
See: error_reporting()
you have to call mysql_real_escape_string() after connect.
otherwise this function returns an empty string and your query fails.
though it raises an error but it seems you haven't seen that.
So, you ought to either turn displaying errors on or peek error logs - it's impossible to program without ability to see error messages
Also, you have to improve your formal logic.
To make a statement like "PHP seems to be refusing to connect to MySQL" youi have to verify it first. Connect is just a single line and returns a value.
You can verify this value and make a certain conclusion.
But running whole code of several dozens of lines and making statements about just one makes no sense.