Q.) Which Function Substitutes htmlspecialchars() For Arrays?
I'm working on a small app for adding tables to a db, printing them via html and allowing for these tables to be deleted via a hidden form button.
I only receive error for ?addjoke.
Error is on line #19 of HTML File. I marked line 19 with comment tags above and below.
I also attached PHP Controller below HTML code block for reference. The $jokes array lies below "// ***** Display DB ***** //."
I just changed selecting just one table to two tables and I had to change my mysqli_fetch_array code from just calling the joketext table (for just printing the rows) to joketext AND id (id for deleting joketext - the functionality that caused this problem to arise.)
So this code:
while ($row = mysqli_fetch_array($result))
{
$jokes[] = array('id' => $row['id'], 'text' => $row['joketext']); // Changed from just $row['joketext'] to now both tables.
}
has forced me to change:
<p><li><?php echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8'); ?> -
to:
<p><li><?php echo htmlspecialchars($joke['text'], ENT_QUOTES, 'UTF-8'); ?> -
Which I understand is in fact an array because there's no other way to call both without it right? I'm a newbie so I don't understand why htmlspecialchars() can only be used with strings...what am I missing?
HTML File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>List of Jokes</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Slabo+27px">
</head>
<body>
<div id="mainContainer">
<div id="contentContainer">
<div class="headerItem">Here are all the jokes in the database:</div>
<div id="addJoke">+ Add Joke</div>
<ol>
<?php foreach ($jokes as $joke): ?>
// ***** LINE***** 19 //
<form action="?deletejoke" method="post">
// ***** LINE***** 19 //
<p><li><?php echo htmlspecialchars($joke['text'], ENT_QUOTES, 'UTF-8'); ?> -
<input type="hidden" name="id" value="<?php echo $joke['id']; ?>">
<input type="submit" value="Delete"></li></p>
</form>
<?php endforeach; ?>
</ol>
</div>
<div id="footer">
<p>IDJB Home - Add Joke to IDJB - Sitemap</p>
<p>© <?php echo date("Y") ?> Internet Joke Database</p>
</div>
</div>
</body>
</html>
PHP Controller File
<?php
// ***** MagicQuoteFix ***** //
if (get_magic_quotes_gpc())
{
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
// ***** Begin Connection Info ***** //
$connection = mysqli_connect('localhost', 'ijdbuser', 'ijdbpw');
if (!$connection)
{
$error = 'Unable to connect to the database server.';
include 'error.html.php';
exit();
}
if (!mysqli_set_charset($connection, 'utf8'))
{
$output = 'Unable to set database connection encoding.';
include 'output.html.php';
exit();
}
if (!mysqli_select_db($connection, 'ijdb'))
{
$error = 'Unable to locate the joke database.';
include 'error.html.php';
exit();
}
// ***** Display DB ***** //
$result = mysqli_query($connection, 'SELECT id, joketext FROM joke');
if (!$result)
{
$error = 'Error fetching jokes: ' . mysqli_error($connection);
include 'error.html.php';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$jokes[] = array('id' => $row['id'], 'text' => $row['joketext']);
}
if (isset($_GET['addjoke'])) {}
else
{
include 'jokes.html.php';
}
//
// ***** Begin Add/Remove DB Options ***** //
if (isset($_GET['addjoke']))
{
include 'form.html.php';
exit();
}
if (isset($_GET['deletejoke']))
{
$id = mysqli_real_escape_string($connection, $_POST['id']);
$sql = "DELETE FROM joke WHERE id='$id'";
if (!mysqli_query($connection, $sql))
{
$error = 'Error deleting joke: ' . mysqli_error($connection);
include 'error.html.php';
exit();
}
//header('Location: .');
exit();
}
if (isset($_POST['joketext']))
{
$joketext = mysqli_real_escape_string($connection, $_POST['joketext']);
$sql = 'INSERT INTO joke SET
joketext="' . $_POST['joketext'] . '",
jokedate=CURDATE()';
if (!mysqli_query($connection, $sql))
{
$error = 'Error adding submitted joke: ' . mysqli_error($connection);
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}
?>
I realize some of my code is old or depreciated. I started learning from an older book and I figure I'll just finish it for context with older apps before moving to more advanced OOP programming.
Thanks for helping me learn.
I'm a newbie so I don't understand why htmlspecialchars() can only be used with strings...what am I missing?
You have to iterate through the array and escape the strings in it:
foreach($arr as &$v)
$v = htmlspecialchars($v);
Now you have each value in the array escaped.
Related
I have scoured the web (including Stack Overflow) for an answer to what is going on, but have had no luck :( I am trying to set up a user-based site that is done by sessions. My site is set up like so:
index.php
<?php include("header.php");
//some html stuff
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
?>
header.php
<!DOCTYPE html>
<html>
<head>
<title>My title</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="style.css" />
<link rel='shortcut icon' href='images/favicon.ico' type='image/x-icon'/ >
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('America/Denver');
?>
</head>
<body>
<div class="header">
<div class='outer-nav'>
<ul>
<?php //navigation
if (isset($_SESSION['user_name'])) {
echo '<li>' . $_SESSION['user_name'] . '</li>';
} else {
echo '<li>user_name does not exist</li>';
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
}
?>
</ul>
The problem is that even though session_start(); is IN the header file, the header file will not recognize the session variables, but the index file that includes the header (and does not have a separate session_start(); iteself) is able to get session variables.
I have tried moving session_start() around and using ob_start and ob_flush, but have not found any way to be able to get session variables to be used in my header file (in the navigation bar specifically). What am I doing wrong??
EDIT
Ok, so I think I figured out where the problem is originating. My index has an include before the header:
index.php
<?php include("admin/settings.php");
include("header.php");
settings.php
<?php session_start(); ?>
//just variable declarations here
header.php
//removed <?php session_start(); ?>
//see above for rest of code in header.php
When I change the code to this, now I'm getting the session variables in index body, but now I get Notice: Undefined variable _SESSION in... in the header. So now it's not even seeing the session at all... is this because it's an include?
Addional Edit
My session info from phpinfo():
loggedin.php (where session variables are declared):
<?php
include_once("admin/settings.php");
$inputusername = mysqli_real_escape_string($connect, $_POST['user_name']);
$inputpassword = mysqli_real_escape_string($connect, $_POST['user_pass']);
$sql = "SELECT user_id, user_name, user_pass, user_role, user_lastloggedin
FROM user WHERE user_name = '$inputusername'";
$result = mysqli_query($connect, $sql);
if (!$result) { //query returned a mistake
include_once($header);
echo '<div class="full_page_content">';
echo "<h1>Sign In</h1>";
echo '<center>Something went wrong while signing in. Please try again later.</center>';
//echo mysqli_error();
include_once($footer);
exit();
} elseif (mysqli_num_rows($result) == 0) { //check if user exists
include_once($header);
echo '<div class="full_page_content">';
echo "<h1>Sign In</h1>";
echo '<center>That username does not exist. Please check your spelling and try again.</center>';
include_once($footer);
exit();
} else { //user was found, continue login
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['user_name'];
$pass = $row['user_pass'];
$id = $row['user_id'];
$role = $row['user_role'];
$last = $row['user_lastloggedin'];
}
$errors = array();
if (empty($inputpassword)) { //check if password field is empty
$errors[] = '<center>The password field must not be empty</center>';
} elseif (!password_verify($inputpassword, $pass)) {
$errors[] = '<center>The password you entered was incorrect. Please check your spelling and try again.</center>';
}
if (!empty($errors)) { //if there are errors...
include_once($header);
echo '<div class="full_page_content">';
echo "<h1>Sign In</h1>";
echo '<ul>';
foreach ($errors as $key => $value) {
echo '<li>' . $value . '</li>';
}
echo '</ul>';
include_once($footer);
exit();
} else {
//there are no errors, process the form
$_SESSION['signed_in'] = true;
$_SESSION['user_id'] = $id;
$_SESSION['user_name'] = $name;
$_SESSION['user_role'] = $role;
$now = time();
if (strlen($last) == 1) {
$_SESSION['first'] = true;
header("Location: changepass.php");
} else {
mysqli_query($connect, "UPDATE users SET user_lastloggedin='$now' WHERE user_id = '$id'");
header("Location: index.php");
}
}
}
?>
In header.php on line 1 you have
session start(); NOT session_start(); (Fixed)
Also, it seems you also forgot to close the PHP tags on line 1.
What happens if you echo the session variable before session_start(); and what happens if you echo it after that (outside of any if statement)?
Alright, remove all session_start();, and then add a single session_start(); into index.php.
Make sure to have only 1 session_start(); across all files you include.
try this instead ob_start();
ob_start();
session_start();
if(!isset($_SESSION['user_name'])){
}
Can anyone see any noticeable errors as to why I am not able to retrieve anything from the db?
<!DOCTYPE html>
<html>
<body>
<?php
//Grabbing from ? in url
$query_string=$_SERVER['QUERY_STRING'];
// Converting query_string to int for restaurant_id
$rest_id=(int)$query_string;
var_dump($rest_id);
$con=mysqli_connect("","","", "");
$sql="SELECT * from menu_item WHERE restaurant_id='".$rest_id."'";
if($result = $con->query($sql)){
if($count=$result->num_rows){
echo '<p>', $count, '</p>';
}
} else {
die($con->error);
}
$rows=$result->fetch_all(MYSQLI_ASSOC);
foreach($rows as $row) {
echo $row['category'], '<br>';
}
$mysqli->close();
?>
<h1>You clicked a button</h1>
<p>Yay!!!</p>
</body>
</html>
I am trying to set the value to be displayed in a SELECT list using php scripts.
What I have done is create an input html page (MatchSelect.php) which shows two select boxes and a submit button.
On pressing the submit button a new new php file is called (MatchSelectResult.php) which is as follows;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Seniors Inter-Club Match Management</title>
<link rel="stylesheet" href="MainBody.css">
<link href="dropDown.css?v=1.1" rel="stylesheet" >
<?PHP require '../../configure.php';
include "Main_PHP_Code.php" ;
?>
</head>
<body>
<?PHP include "MatchPopulate.php"; ?>
<div class="container">
<?PHP include "menu.txt" ?>
<div class="content">
<div>
<h1>Team Selection</h1>
<form name="matchSelect" method="POST" action="MatchUpdate.php">
<p>
<select id = "Venue" name= "Venue" >
<option disabled selected value> -- select an option -- </option>
<option value="Away">Away</option>
<option value="Home">Home</option>
</select>
match against
<select id ="Opponents" name ="Opponents">
<?php
Global $OpponentName;
$oop = $OpponentName;
opponent_load('$oop');
?>
</select>
etc.
the function opponent_load() is contained within the "Main_PHP_Code.php" code and is as follows;
function opponent_load($oppon){
Global $OpponentName;
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementdb";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM opponentsdb";
$result = mysqli_query($db_handle, $SQL);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['Opponents'];
if ($uName == $oppon)
{
$selected = 'selected="selected"';
}
else
{
$selected = '';
}
echo "<option value='$uName' $selected> $uName </option>";
}
}
else {
print "Database NOT Found ";
}
mysqli_close($db_handle);
}
The "MatchPopulate.php" code in the HEAD section is used to search the mySQL database using the two values from MatchSelect.php page. If the data is found, then the global variable $OpponentName is defined. The code is thus;
<?php
Global $OpponentName;
//require '../../configure.php';
$uOpponentName = $_POST['Opponents'];
$uVenue = $_POST['Venue'];
//$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementdb";
$conn = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// check to see if Match (Opponents + Venue)already in the database, if so, retrieve data or add match to database
$SQL = "SELECT * FROM teamselect WHERE Opponents = '$uOpponentName' AND Venue = '$uVenue'";
$result = $conn->query($SQL);
//if $result->num_rows >0 then retrieve data ELSE add match to database
if (!$result){
print "Error selecting record: " . $sql . "<br>" . $conn->error;
} else {
if ($result->num_rows >0) {
while($row = $result->fetch_assoc()) {
$OpponentName = $row['Opponents'];
}
} else {
$sql = "INSERT INTO teamselect (Opponents, Venue) VALUES ('$uOpponentName', '$uVenue')";
if ($conn->query($sql) === TRUE) {
} else {
print "Error adding record: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
The code stops when it tries to populate the Opponents Select box on MatchSelectResult.php. Any help to solve this would be appreciated.
I have solved the problem by opening a session and using $_SESSION["Opponents"] to pass the variable around the scripts.
Also changed opponent_load('$oop') to opponent_load($oop).
what is the best way to direct the user to another page given the IF statement is true. i want the page to direct the user to another page using PHP, when the IF statement is run, i tired this but it doesn't work??
if ( mysqli_num_rows ( $result ) > 0 )
{
header('Location: exist.php');
die();
}
Below is the full source code for the page.
<?php
// starts a session and checks if the user is logged in
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: index.php');
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<p><span>Room No: </span><?php $room = $_SESSION['g'];
echo $room; // echo's room ?>
</p>
<p><span>Computer No: </span><?php
$select3 = $_POST['bike'];
echo $select3;
?>
</p>
<p><span>Date: </span><?php $date = $_POST['datepicker'];
echo $date; // echo's date
?>
</p>
<p><span>Start Session: </span>
<?php
if(isset($_POST['select1'])) {
$select1 = $_POST['select1'];
echo $select1;
echo "";
}
else{
echo "not set";
}
?>
</p>
<p><span>End Session: </span>
<?php
if(isset($_POST['select2'])) {
$select2 = $_POST['select2'];
echo $select2;
echo "";
}
else{
echo "not set";
}
?>
</p>
</div>
<div id="success">
<?php
$servername = "localhost";
$name = "root";
$password = "root";
$dbname = "my computer";
// Create connection
$conn = mysqli_connect($servername, $name, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM `booked` WHERE
`date` = '{$date}' AND
`computer_id` = '{$select3}' AND
`start_time` = '{$select1}' AND
`end_time` = '{$select2}' AND
`room` = '{$room}'
";
$result = mysqli_query($conn, $query);
if ( mysqli_num_rows ( $result ) > 0 )
{
header('Location: exist.php');
die();
}
else
{
$sql = "INSERT INTO booked (date, computer_id, name, start_time, end_time, room)
VALUES ('$date', '$select3', '$username', '$select1', '$select2', '$room')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
</div>
<form action="user.php">
<input type="submit" value="book another" class="bookanother" />
</form>
</div>
</body>
</html>
If the header is sent already, for example you have echo something before then the header will not work, because the header cannot be set after data flow has started, (since php would have already set the default headers for you). So, in this case if that is so, I do the redirect using javascript.
PHP Docs:
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
WORK-AROUND: This is a function I have written long back and include in controllers.
/**
* Safely redirect by first trying header method but if headers were
* already sent then use a <script> javascript method to redirect
*
* #param string
* #return null
*/
public function safeRedirect($new_url) {
if (!headers_sent()) {
header("Location: $new_url");
} else {
echo "<script>window.location.href = '$new_url';</script>";
}
exit();
}
add the function and simply call:
safeRedirect('index.php');
Hi I am trying to develop a login sistem but I seem to be getting an error on a condition.This is my code:
//header.php
if($_SESSION['signed_in']){
echo 'Hello' . $_SESSION['user_name'] . '. Not you? Sign out';
}
else{
echo 'Sign in or create an account.';
}
//Signin.php
if(mysql_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysql_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
echo 'Welcome, ' . $_SESSION['user_name'] . '. Proceed to the forum overview.';
}
The error is pointed on the first condition : if($_SESSION['signed_in']) and it says that:
Notice: Undefined variable: _SESSION in C:\xampp\htdocs\Tutorials\Forum\header.php on line 21
How can I corect this?
EDIT:session_start() is included at the top of the header.php file in the doctype and header.php is included in Signin.php
Full Code:
header.php
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="nl" lang="nl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="A short description." />
<meta name="keywords" content="put, keywords, here" />
<title>PHP-MySQL forum</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<h1>My forum</h1>
<div id="wrapper">
<div id="menu">
<a class="item" href="/forum/index.php">Home</a> -
<a class="item" href="/forum/create_topic.php">Create a topic</a> -
<a class="item" href="/forum/create_cat.php">Create a category</a>
<div id="userbar">
<div id="userbar">
<?php
if($_SESSION['signed_in']){
echo 'Hello' . $_SESSION['user_name'] . '. Not you? Sign out';
}
else{
echo 'Sign in or create an account.';
}
?>
</div>
</div>
<div id="content">
Signin.php
<?php
//signin.php
include 'conn.php';
include 'header.php';
echo '<h3>Sign in</h3>';
//first, check if the user is already signed in. If that is the case, there is no need to display this page
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
echo 'You are already signed in, you can sign out if you want.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo '<form method="post" action="">
Username: <input type="text" name="user_name" />
Password: <input type="password" name="user_pass">
<input type="submit" value="Sign in" />
</form>';
}
else
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Varify if the data is correct and return the correct response
*/
$errors = array(); /* declare the array for later use */
if(!isset($_POST['user_name']))
{
$errors[] = 'The username field must not be empty.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'The password field must not be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo 'Uh-oh.. a couple of fields are not filled in correctly..';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li>' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul>';
}
else
{
//the form has been posted without errors, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$sql = "SELECT
user_id,
user_name,
user_level
FROM
users
WHERE
user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
AND
user_pass = '" . sha1($_POST['user_pass']) . "'";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysql_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysql_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
echo 'Welcome, ' . $_SESSION['user_name'] . '. Proceed to the forum overview.';
}
}
}
}
}
include 'footer.php';
?>
Before you store something into the session, the variable $_SESSION['signed_in'] will be empty. The warning occurs because you ask for this value, but nothing is inside.
if (isset($_SESSION['signed_in']) && $_SESSION['signed_in'])
{
}
To avoid the warning, you should first check if the variable exists, then you can read from it. Of course this is a bit cumbersome, so most developers create a function just for reading safely from an array.
Edit:
Actually the problem above would lead to another message...
Notice: Undefined index: ...
...so it is as Mob said, the variable $_SESSION doesn't exist at all, because no session was started. I will let this answer stay, because this will be the next pitfall.
There's no session_start(); That's the reason, you have to always declare that befoe using sessions in PHP.