Why are html and php files not properly exchanging information? - php

I am creating a website where a user logs in, enters information that is submitted to a database, and then can call information from the database that will be inserted into an html text element. I have separate html files for each website page, and multiple php files. They are all contained and linked properly on the same server, under the same FTP account. EDIT: THIS WAS MY PROBLEM. I HAD SEPARATE PHP AND HTML FILES. ONCE I COMBINED THEM, I NO LONGER NEEDED THE JAVASCRIPT AND EVERYTHING WORKED FINE. My code has been checked by multiple sources, and I can have the user correctly input information into the database. When it comes to retrieving the information to be displayed on client-side, however, the php will not change the html via javascript.
I am currently using 000webhost.com, but I tried plugging the files into dreamweaver and the files still aren't communicating properly. I'm wondering whether this is a software limitation (aka something is going wrong with 000webhost.com) or if there is a key piece of info I am missing, such as a command that will link the files together.
Here is the example php and html for one of the retrieve information functions:
$servername = "localhost";
$username = "-";
$password = "-";
$database = "-";
$link = mysqli_connect($servername, $username, $password, $database);
if (!$link) {
die(mysqli_error());
}
$sql = "SELECT UserClassName FROM UserInfo1 WHERE UserEmail = '". mysqli_real_escape_string($link, $_SESSION['useremail']) . "'";
if (!$sql) {
die(mysqli_error());
}
$result = mysqli_query($link, $sql);
if (!$result) {
die(mysqli_error());
}
?>
<script>
function getclassname() {
return document.getElementById("UserClassName").innerHTML = "<?php echo
$result ?>";
}
</script>
<html>
<body onload="getclassname(); getcurrentlevel();">
<h1 class="text-center" id="UserClassName" name="UserClassName"><b>Welcome Enviroquest Research Team!</b></h1>
</body>
</html>

I think the only problem is that you put the javascript code outside the html. It should be placed before the closing body tag.
This is what your html should look like :
<?php // your php code here ?>
<html>
<body onload="getclassname(); getcurrentlevel();">
<h1 class="text-center" id="UserClassName" name="UserClassName"><b>Welcome Enviroquest Research Team!</b></h1>
<script>
function getclassname() {
document.getElementById("UserClassName").innerHTML = "<?php echo $result; ?>";
}
function getcurrentlevel() {
// this function should be remove if not used
}
</script>
</body>
</html>

Related

Code that works on Apache II local host but not on a commercial hosting service server

I'm a rookie amateur trying to build my own site that uses PHP and a backend SQL database. Having got all my pages working with the database on an Apache II localhost, I have now moved my files to a commercial hosting service. Post migration, some of the pages have gone blank. I have narrowed the problem down to a block of php code that runs as follows:
<?php
if (isset($_POST['submit3'])) {
$email = htmlentities($_POST['email']);
$password = htmlentities($_POST['password']);
if (empty($email) || empty($password)) {
echo <<<EOF
<script type="text/javascript">
$(".welcome").hide();
$("#form3").hide();
$("#error").show();
</script>
EOF;
}
else {
$sql = "SELECT `email` FROM `Registrations` WHERE `email` = '".$email."' AND `password` = '".$password."'";
$rs = $connection->query($sql);
if ($rs->num_rows === 0) {
echo <<<EOF
<script type="text/javascript">
$(".welcome").hide();
$("#form3").hide();
$("#nomatch").show();
</script>
EOF;
}
else {
$_SESSION["email"] = "$email";
echo <<<EOF
<script type="text/javascript">
window.location = "PharMEdCentral-MyAccount.php";
</script>
EOF;
}
$rs->free();
}
}
?>
The html renders well when these two lines are commented out, but I get blank page with these line in. It's probably a silly thing but I have been unable to figure out what mistake I'm making. The problem is not with the connection to the database as other pages with the same connection are rendered properly.
The server version is MySQL 5.6.26 via UNIX socket.
Would highly appreciate any tips on how to fix this!

PHP Include another php that queries MySQL

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.

php header command isn't working

I'm having a problem getting this code to work on the website that I'd like to launch soon. In particular when I sign in the header won't redirect after a successful login. I have used this code before many times and I've never had a problem with it. The only difference now is that I'm using a different server and a different database. Here's the code that is giving me trouble:
<?php
/*set all the variables*/
$email = $_POST['email'];
$password = sha1($_POST['password']); /* hash the password*/
$conn = mysqli_connect ('servername', 'username', 'password', 'databasename') or die('Error connecting to MySQL server');
/*select the id from the users table that match the conditions*/
$sql = "SELECT id FROM users WHERE email = '$email' AND password = '$password'";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
$count = mysqli_num_rows($result);
if ($count == 1) {
echo 'Logged in Successfully.';
$row = mysqli_fetch_array($result);
session_start();
$_SESSION['user_id'] = $row['id'];
/*If true head over to the users table*/
header('location: users_table.php');
}
/*If invalid prompt them to adjust the previous entry*/
else {
echo '<h2>Invalid Login</h2><br />';
echo '<h2>Click HERE to go back and adjust your entry.</h2>';
}
mysqli_close($conn);
?>
It's not a matter of it connecting properly because I get the message 'successful Login' but it won't redirect at all.
Thanks for all the answers, I tried removing the echo but all I get now is a blank page, I thought maybe it was the browser I was using so I switched to another and I still just get a blank page, any other suggestions?
You cannot echo anything before your header statement.
echo 'Logged in Successfully.';
This is causing the header call to not work.
if ($count == 1) {
echo 'Logged in Successfully.';
//this statement is creating problem
$row = mysqli_fetch_array($result);
session_start();
$_SESSION['user_id'] = $row['id'];
/*If true head over to the users table*/
header('location: users_table.php');
}
This is because you are echoing something berfore header
You should use ob_start() at start and ob_end_flush() at the end of the document..
or do not echo before header().As we found you haven't turned on the error.So turn it ON.
You can't be posting the header after the echo... if this actually worked you'd never see the text (it would simply redirect). (To fix remove/comment out the echo line)
Also the location header requires an absolute/full URL (although many browsers seem to cope with relative URLs).
If you want to do it this way (show some sort of status before hand), use an HTML or Javascript redirect that triggers after a couple of seconds.
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Logged in Successfully.</title>
<meta http-equiv="REFRESH"
content="5;url=http://www.example.com/users_table.php"></HEAD>
<BODY>
Logged in Successfully.
</BODY>
</HTML>
Javascript
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>Logged in Successfully.</title>
</HEAD>
<BODY onLoad="setTimeout(function() {
window.location='http://www.example.com/users_table.php'},5000)">
Logged in Successfully.
</BODY>
</HTML>
Better yet, allow the users_table.php page to display a successful login message and use the header-location redirect.

PHP code included in HTML won't update

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.

Access denied www-data#localhost

I am using Jquery.load to load an external file with html/php content into one div. It loads the file, and displays what it's supposed to except it says access denied www-data#localhost password: no where it should be echoing some content.
I know that the main page, not the one being loaded, is connected to the db using require_once("assets/functions/config.php"); to call on my php file that contains the connection.
What am I doing wrong? It's probably simple, and I'm overlooking something.
EDIT: Okay on the index.php above <html> I have:
<?PHP
require_once("assets/functions/config.php");
//if ($notInstalled == 1) header("Location: install");
require_once("assets/functions/functions.php");
if ($users->checkAuth() == 0) {
header("Location: login.php");
exit;
}
$currentUser = $_COOKIE['vetelixir_username'];
?>
config.php is as follows:
<?
// MySQL Database
$db_host = "localhost";
$db_name = "dbname";
$db_username = "username";
$db_password = "password";
// Connect to the database
$connection = #mysql_connect($db_host,$db_username,$db_password) or die(mysql_error());
$db = #mysql_select_db($db_name,$connection)or die(mysql_error());
// end MySQL
?>
jQuery:
$("#button").click(function() {
$('#content').load('pages/external.php');
});
External File to Load:
<div id="div">
<?
$currentBlah = mysql_query("SELECT `firstname`,`lastname` FROM `blah` ORDER BY `lastname` ASC") or die(mysql_error());
while($u = mysql_fetch_array($currentBlah)) {
echo "<div class='clientRow'><span class='name'>".$u['firstname']." ".$u['lastname']."</span></div>";
}
?>
</div>
This looks like the php script that your jQuery function is calling is trying (and failing) to open an SSH session.

Categories