Enabling both a PHP parser and an Include statement - php

I have an existing SHTML page with a few INCLUDE statements for menu's. This has worked well. To this point, my .htaccess file has looked like:
Options +FollowSymLinks
And my Include statement looked like this:
<!--#include virtual="menu_primary.shtml" -->
I have a new need to add some PHP code to the main page. The PHP code queries a Mysql database to return a single row. If the row exists in the database, I want to show it on the SHTML page. If the row does not exist, do nothing. Here's the PHP code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT notice from notification where page = 'home'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Message is: " . $row["notice"]. "<br>";
}
} else {
echo "";
}
mysqli_close($conn);
?>
</body>
</html>
When I implemented this PHP code, the page seemed to interpret everything after the Greater Than symbol as text. When I posted that problem, someone on this forum suggested altering the .htaccess file to include a PHP parser. For a while. I altered my .htaccess file to look like this:
Options +FollowSymLinks
<FilesMatch "\.(htm|html|shtm|shtml)$">
SetHandler application/x-httpd-php5
</FilesMatch>
However when I do that, the PHP code works fine and I display the data from the database on the SHTML page, but the #Include statements no longer work. How can I enable both the PHP and #Include code together in the same SHTML page? Thanks very much for looking at this.

In your PHP script you can invoke the virtual function to work with your SSI
<?php
virtual('menu_primary.shtml');
There's a very old page that talks about this in more detail
http://www.zytrax.com/tech/php/php_ssi.htm

Related

Show Output/Echo of PHP File executing at load on webpage

im trying to create my first website and Im clueless in this case.
So I have a MySQL-Database with a table. And I have a php-File called database.php which reads from the database and echos all the lines of a query:
<?php
$servername = "xxxxxxxxxx.hosting-data.io";
$username = "xxxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ID, Name, Beschreibung, Datum, Uhrzeit FROM Termine";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["ID"]. " - Name: " . $row["Name"]. " - Beschreibung: " . $row["Beschreibung"]. " - Datum: " . $row["Datum"]. " - Uhrzeit: " . $row["Uhrzeit"]."<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Now on my index.php I want to execute this php-code on calling/loading the webpage and print all the lines (data entries).
But i have no idea how to get the echo (=data entries) of the php file printed in the body of my webpage. I read about AJAX and using a js-script but I still wasnt able to figure it out.
Thanks for your help.
Option 1: Place your PHP code inside the HTML body.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo 'Hello World';
// ...
?>
</body>
</html>
Option 2: Create a separate PHP file containing your code above and include/require it into your body.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
include_once('your_php_file.php');
?>
</body>
</html>
Option 3: Call your PHP file using an AJAX call (e.g. by using jQuery load()).
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="aDiv"></div>
<script> $( "#aDiv" ).load('your_php_file.php', function() { console.log('Loaded'); });</script>
</body>
</html>
If your index file is index.php then the PHP code will be run when you load the webpage. That is assuming, of course, that your web server (local or remote) has PHP installed.

PHP and MySQL database search - removing database credentials from php code [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
I found some code for a simple database search using PHP and MySQL and I was able to make it work. However, I decided it might not be such a great idea to leave my database username and password in the PHP code within the root folder. So, I found another code sample that demonstrated how to create a config.ini file outside the root, and use a dbconnect.php file to access the database credentials. I tried to implement this, but I'm not having any luck and was wondering if someone could show me what I'm missing (I only have a rudimentary grasp of coding and am trying to learn little by little). I have included the code for all of the component files (and I changed any username/passwords/servernames to generic placeholders). Below the code I have pasted the errors that are currently being shown when I submit the search form. Thanks!
index.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form action="search.php" method="GET">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
</body>
</html>
search.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php require_once('./includes/dbconnect.php'); ?>
</head>
<body>
<?php
$query = $_GET['query'];
// gets value sent over search form
$min_length = 3;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length) { // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM details WHERE (`title` LIKE '%".$query."%') OR (`text` LIKE '%".$query."%')") or die(mysql_error());
// * means that it selects all fields
// details is the name of our table
// '%$query%' is what we're looking for, % means anything, for example if $query is Hello
if(mysql_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)) {
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<p><h3>".$results['title']."</h3>".$results['text']."</p>";
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
} else { // if there is no matching rows do following
echo "No results";
}
} else { // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
?>
</body>
</html>
dbconnect.php:
<?php
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $connection;
// Try and connect to the database, if a connection has not been established yet
if(!isset($connection)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('/home/cpanelusername/private/config.ini');
$connection = mysqli_connect($config['servername'],$config['username'],
$config['password'],$config['dbname']);
}
// If connection was not successful, handle the error
if($connection === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return mysqli_connect_error();
}
return $connection;
}
// Connect to the database
$connection = db_connect();
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
?>
config.ini:
[database]
servername = localhost
username = username
password = password
dbname = username_database
Warning: mysql_real_escape_string(): Access denied for user
'root'#'localhost' (using password: NO) in
/home4/cpanelusername/public_html/...../search.php on line 29
Warning: mysql_real_escape_string(): A link to the server could not be
established in /home4/cpanelusername/public_html/......./search.php on
line 29
Warning: mysql_query(): Access denied for user 'root'#'localhost'
(using password: NO) in
/home4/cpanelusername/public_html/......../search.php on line 33
Warning: mysql_query(): A link to the server could not be established
in /home4/cpanelusername/public_html/......./search.php on line 33
Access denied for user 'root'#'localhost' (using password: NO)
This is because mysql_real_escape_string takes into account the current character set of the connection. As such, it needs a connection. :-)
Please try to connect database using below code and please let me know if you have any problem.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Scrubbing the strings that come from userland isn't sufficient to prevent SQL injection attacks. The standard way is to use a prepared query. E.g.:
$stmt = mysqli_stmt_init($this);
$result = array();
$okay = mysqli_stmt_prepare($stmt, "SELECT * FROM details WHERE (title LIKE ?) OR (text LIKE ?)");
if ($okay)
$okay = mysqli_stmt_bind_param($stmt, "ss", "%$query%", "%$text%")
else
[handle error]
if ($okay)
$okay = mysqli_stmt_execute($stmt);
else
[handle error]
if ($okay)
$okay = mysqli_bind_result($stmt, $row);
else
[handle error]
if ($okay)
while (mysqli_stmt_fetch($stmt))
array_push($result, $row);
else
[handle error]
mysqli_stmt_close($stmt);

How to use PHP in HTML for mySQL

I am trying to use php for the first time to connect to MySQL on the raspberry pi. Both the server and MySQL are running on the Pi and I want to tweak my index.html file to show some value that is in the data base. Normally for I would be able to do just that with pyton but I have no clue if I can do that with php. Here is my index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ziks</title>
<link href="CSS/style1.css" rel="stylesheet" type="text/css">
<style type="text/css">
body {
background-color: #FFFFFF;
background-image: url(Images/twe_background-1920x1080.jpg);
}
</style>
</head>
<body>
<div class="header">
<p><strong>Welcome to Ziks</strong></p>
</div>
<p> </p>
<div class="box">
<p> Wishing every one a happy life! </p>
<form method="GET" action="ftp://47.55.90.215:21">
<input type="submit" value="Click here to view Disk">
</form>
<body>
<html>
<body>
</body>
</html>
</body>
<div class="image"></div>
<iframe src="http://free.timeanddate.com/clock/i5nb4b3g/n1127/szw160/szh160/hoc9b8578/hbw10/hfc754c29/cf100/hnc432f30/hcw2/fav0/fiv0/mqcfff/mqs4/mql25/mqw12/mqd78/mhcfff/mhs2/mhl5/mhw2/mhd78/hhcfff/hhs2/hhl50/hhw8/hmcfff/hms2/hml70/hmw8/hmr4/hscfff/hss3/hsl70/hsw3" frameborder="0" width="160" height="160"></iframe>
<video width="400" controls>
<!--<source src="///smb://zikpc/f/test.mp4" type="video/mp4">-->
<!--<source src="///smb://zikpc/f/test.ogg" type="video/ogg">-->
<source src="1.mp4" type="video/mp4">
<source src="1.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
</div>
</body>
</html>
This index.html file works fine. All I want to do is write some php in it to connect to MySQL. The current method I'm using in python is:
# External module imports
import time
import os
import datetime
import MySQLdb
os.system('sudo modprobe w1-gpio')
os.system('sudo modprobe w1-therm')
# Connect to mysql
db=MySQLdb.connect("localhost","zikmir","gforce","temp_database")
cursor=db.cursor()
while True:
# Initialization
sensor= "/sys/bus/w1/devices/28-011620ee98ee/w1_slave"
# Open the file for sensor
file = open(sensor)
# Read all of the text in the file.
text = file.read()
# Close the file now that the text has been read.
file.close()
# Split the text with new lines (\n) and select the second line.
second_line = text.split("\n")[1]
# Split the line into words, referring to the spaces, and select the 10th word (counting from 0).
temp_data = second_line.split(" ")[9]
# The first two characters are "t=", so get rid of those and convert the temperature from a string to a number.
temp = float(temp_data[2:])
# Put the decimal point in the right place and display it.
temp = temp / 1000
# Display time
t= datetime.datetime.now()
print t,temp
# Push data into mySQL
sql = "INSERT INTO time_temp VALUES(now(),%s)"
cursor.execute (sql,(temp,))
db.commit()
# Wait 5 seconds
time.sleep(5)
My question is how would I be able to do this in php within the index.html file? Any help would be appreciated!
This is my website
MySQLi Object-Oriented
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
PDO
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
You have a number of choices. The simplest, IMHO, would be something like the following.
Rename your index.html file to index.php (make sure that your web server looks for index.php as well as index.html and index.htm).
Your index.php would then be modified to look something like this:
<?php
//Open MySQL connection
//Get the data you want into a string variable called $info
print <<< END
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ziks</title>
<link href="CSS/style1.css" rel="stylesheet" type="text/css">
<style type="text/css">
body {
background-color: #FFFFFF;
background-image: url(Images/twe_background-1920x1080.jpg);
}
</style>
</head>
<body>
... (rest of HTML excluded for brevity)
END;
?>
Simply put the $info variable where ever you want the data to appear in the HTML data.
The construct:
print <<< END
<<<what you want to print>>>
END;
is called a "heredoc" and is very handy.
I have not described how to actually get the data from the database since your question seemed more about the process of using PHP to output HTML with data from a database. Look at the PDO documentation (PDO documentation) to quickly get up to speed on DB access in PHP.

MySQLi mysqli fech array assoc replacement NO working

here is what I want but cannot make it work with the new MySQLi just because my host does not have all new php etc...
But there must be some kind of solution or thats all MYSQLI can do ?
Please dont talk about PDO because even the ugly name sounds like PEDO and I am only interested in MySQLI and a solution for this simple thing. Please dont change the structure of my script. The question is only is if there is something to make it work with MySQL or if I maybe switch back to MySQL procedure instead of statements
<?php
$sql = new mysqli('localhost','user','pass','db');
$who = $_GET['user'];
$query = $sql->prepare("SELECT * FROM profiles WHERE user=?");
$query->bind_param("s",$who);
$result = $query->execute();
while($row = $result->fetch_array(MYSQLI_ASSOC)) // << HERE IS THE PROBLEM //
// I GET ERROR Fatal error: Call to a member function fetch_array() on a non-object in ... //
"" but there must be some way to make it work like we do with while($row = mysqli_fetch_array($sql)) //
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>title</title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
HELLO <?php echo "$row[USERNAME]"; ?>
YOUR INFO IS <?php echo "$row[JUST_SOME_INFO]"; ?>
</body>
</html>
<?php
}
?>
Here is your solution
You don't have to use fetch_array() but use fetch()
also you will have to bind result using bind_result before fetch
$query->execute();
$query->bind_result($col1);
while($row = $query->fetch()){
printf("%s \n", $col1);
}
You can use $col1 directly also, no need to use it with printf()
My working example according to my db is given below if you want more assistance,
$sql = new mysqli('localhost','user','pass','dbname');
$who = 'php';
$query = $sql->prepare("SELECT * FROM job WHERE skill=?");
$query->bind_param("s",$who);
$query->execute();
$query->bind_result($col1);
while($row = $query->fetch()){
printf("%s \n", $col1);
}
Comment this string:
$result = $query->get_result();
you don't need this.
Try this one.
<?php
$sql = new mysqli('localhost', 'user', 'pass', 'db');
$who = $_GET['user'];
$query = $sql->prepare("SELECT * FROM profiles WHERE user=?");
$query->bind_param("s", $who);
$result = $query->execute() or die($query->error);
while ($row = $result->fetch_array()) {
$username = $row[USERNAME];
$info = $row[JUST_SOME_INFO];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>title</title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
HELLO <?php echo $username; ?>
YOUR INFO IS <?php echo $info; ?>
</body>
</html>
This is what happens when you start copying and pasting php together without knowing what it means.
the solution here is:
create a class for $sql or declare $sql a global imediately after calling the variable.
try
global $sql;
but if you actually want to fix the problem(by making your $sql variable an object)
try
$sql = array();
$sql['host'] = 'host';
$sql['user'] = 'user';
$sql['pass'] = 'password';
$sql['db'] = 'database';
global $sql;
$db = new mysqli($sql);
Now when you wanna do something with the db connection.
$db->action();
this is just the basics and probably won't work. you probably should instead read more on php/mysqli before attempting to write your own classes.

redirect to different website

I searched on the various solutions with respect to my question about redirecting to a different webpage - both on this site and google.com, but I can figure out why i keep getting the error in my specific scenario -
the error being: : "Warning: Cannot modify header information - headers already sent by (output started at test_ecis_lib_pdo.php:3) in login_submit3.php on line 10".
The code of login_submit3.php:
<?php
//! include config file; includes session_start() and ecp php library
include 'config.php';
if(DBLoginSubmitA($mysql_hostname, $mysql_username, $mysql_password,$mysql_dbname))
{
//redirect to webpage depending on SESSION paramter ['customertype'
switch($_SESSION['customertype'])
{
case 'member':
header("location:members3.php",true,'301');
die();
break;
case 'admincrm':
header("location:admincrm3.php");
die();
break;
default:
break;
}
};
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>PHPRO Login</title>
</head>
<body>
</body>
</html>
The code of config.php:
/*** begin our session ***/
session_start();
//! include lib after session_start()
include 'test_ecis_lib_pdo.php';
/*** mysql hostname ***/
$mysql_hostname = 'localhost';
/*** mysql username ***/
$mysql_username = 'root';
/*** mysql password ***/
$mysql_password = 'xxxx';
/*** database name ***/
$mysql_dbname = 'xxx';
?>
The code of test_ecis_lib_pdo.php (a library with functions - and where the error refers to) starts with:
<?php
//GLOBAL VARIABLES
$error = "no error";
$timezone = date_default_timezone_set("Europe/Amsterdam");
$CUSTOMER_TYPE=array(
"interested"=>"1",
"member"=>"2",
"chair"=>"3",
"admincrm"=>"4",
"adminfinance"=>"4",
"adminenergymanagement"=>"5"
);
I checked that the test_ecis_lib_pdo.php file does not send send any tags or echo text before calling header() but i still get the error - where do i go wrong??? Please your help.
First,use
header("location: admincrm3.php");
instead of header("location:admincrm3.php");
second, what is your encoding ? if is utf-8 be sure is utf-8 without BOM
and be sure there is no space or another text before <?php
if you want to put text before send header, use ob_start() and ob_flush()
I'm not sure what is going on in your includes, but you may need to look at Output Buffering -- if you try and send headers after data has already been sent to the buffer your going to get that error.

Categories