I've been trying to implement the following shopping cart website on xampp. The link for the page is : http://www.w3programmers.com/build-a-shopping-cart-with-php-part-1/
However when I try running my login page I get the following error:-
Here's the tab that opens when I try to login:
Here's the login code :-
<?php
session_start();
require("config.php");
if(isset($_SESSION['SESS_LOGGEDIN']) == TRUE) {
header("Location:".$config_basedir);
}
if($_POST['submit'])
{
$loginsql = "SELECT * FROM logins WHERE username = '" . $_POST['userBox']. "' AND password = '" . $_POST['passBox'] . "'";
$loginres = mysql_query($loginsql);
$numrows = mysql_num_rows($loginres);
if($numrows == 1)
{
$loginrow = mysql_fetch_assoc($loginres);
session_register("SESS_LOGGEDIN");
session_register("SESS_USERNAME");
session_register("SESS_USERID");
$_SESSION['SESS_LOGGEDIN'] = 1;
$_SESSION['SESS_USERNAME'] = $loginrow['username'];
$_SESSION['SESS_USERID'] = $loginrow['id'];
$ordersql = "SELECT id FROM rides WHERE customer_id = " . $_SESSION['SESS_USERID'] . " AND status < 2";
$orderres = mysql_query($ordersql);
$orderrow = mysql_fetch_assoc($orderres);
session_register("SESS_ORDERNUM"); $_SESSION['SESS_ORDERNUM'] = $orderrow['id'];
header("Location:".$config_basedir);
}
else {
header("Location:http://" .$_SERVER['HTTP_HOST']. $_SERVER['SCRIPT_NAME'] . "?error=1");
}
}
else {
require("header.php");
?>
<h1>Customer Login</h1>
Please enter your username and password to log into the websites. If you do not have an account, you can get one for free by registering.
<?php
if(isset($_GET['error'])) {
echo "<strong>Incorrect username/password</strong>";
}
?>
<form action="<?php $_SERVER['SCRIPT_NAME']; ?><br />" method="POST">
<table>
<tbody>
<tr>
<td>Username</td>
<td><input type="textbox" name="userBox" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="passBox" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Log in" /></td>
</tr>
</tbody>
</table>
</form>
<?php
}
require("footer.php");
?>
And here's the header code:-
<?php
session_start();
if(isset($_SESSION['SESS_CHANGEID'])==TRUE){
session_unset();
session_regenerate_id();
}
require("config.php");
$db = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbdatabase, $db);
?>
<head>
<title><?php echo $config_sitename; ?></title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="../stylesheet.css">
</head>
<body>
<div id="header">
<h1><?php echo $config_sitename; ?></h1>
</div>
<div id="menu">
Home
View Rides
</div>
<div id="container">
<div id="bar">
<?php
require("bar.php");
echo "<hr>";
if(isset($_SESSION['SESS_LOGGEDIN'])==True){
echo "Logged in as <strong>".$_SESSION['SESS_USERNAME']."</strong>[<a href='".$congif_basedir."logout.php'>logout</a>]";
}else{
echo "<a href='".$config_basedir."login.php'>Login</a>";
}
?>
</div>
<div id="main">
I suspect it's something to do with the header function, though I'm not really sure.
May I ask you to put here code from config.php? Or at least tell what value of $config_basedir?
Updated: $config_basedir should be URL in this format: http://localhost/ . 'some folders' . 'file name with extension', for example, like this: http://localhost/sites/shop/index.php.
If a file or folder of the file is located in the same or child directory your URL can be just: file 'file_name or folder/file_name. For example just index.php or folder/folder/index.php.
An extension like .php | .htmlmay not be mandatory depending on your server settings. That is, you can indicate the URL like this: folder/index or index; 'index' - is a file name in this case.
Related
I have a page with a contact form.
I'm trying to make some error messages appear next to the fields if the fields are empty/invalid. If all fields are OK the field's contents are sent to a database.
The validation itself works. If the fields are empty or invalid it does not submit them into the database. However no error messages are shown next to the fields.
Here are the codes
Page with the contact form named palaute3.php:
<?php
session_start();
$_SESSION["nimiVirhe"]="";
$_SESSION["spostiVirhe"]="";
$_SESSION["palauteVirhe"]="";
$servername = "localhost";
$username = "username";
$password = "passwd";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Game Over</title>
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="tyyli1.css"/>
<style type="text/css">
#import url('https://fonts.googleapis.com/css?family=Press+Start+2P');
</style>
</head>
<body>
<div id="container">
<div id="header">
</div>
<div id="menuBG">
</div>
<ul class="navlist">
<li>Etusivu
</li>
<li>Leffat
</li>
<li>Pelit
</li>
<li>Ota yhteyttä
</li>
</ul>
<div id="content">
<h3>Palaute</h3>
<p>Anna Palautetta sivujen ulkonäöstä tai vinkkejä uusiksi arvosteluiksi!</p>
<p><span class="error">Kaikki kentät ovat pakollisia</span></p>
<form method="post" action="validointi.php">
<table width="450px">
<tr>
<td valign="top">
<label for="nimi">Nimi</label>
</td>
<td valign="top">
<input type="text" name="nimi" /><span class="error"><?php echo $_SESSION["nimiVirhe"];?></span>
</td>
</tr>
<tr>
<td valign="top">
<label for="sposti">Sähköposti</label>
</td>
<td valign="top">
<input type="text" name="sposti" /><span class="error"><?php echo $_SESSION["spostiVirhe"];?></span>
</td>
</tr>
<tr>
<td valign="top">
<label for="palaute">Palaute</label>
</td>
<td valign="top">
<textarea name="palaute" maxlength="1000" cols="30" rows="6"></textarea><span class="error"><?php echo $_SESSION["palauteVirhe"];?> </span>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="Lähetä" name="submit">
</td>
</tr>
</table>
</form>
<?php
session_unset();
?>
<p>
Palautteet tähän
</p>
<?php
$sql = "SELECT id, palaute FROM dbtable";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Palaute: " . $row["palaute"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</div>
<div id="footer">
<p>© Game Over 2018 All rights reserved</p>
</div>
</div>
</body>
</html>
Here is the validation:
<?php
session_start();
$_SESSION["nimiVirhe"]="";
$_SESSION["spostiVirhe"]="";
$_SESSION["palauteVirhe"]="";
if (isset($_POST['submit'])) {
if (empty($_POST["nimi"])) {
$_SESSION["nimiVirhe"] = " Nimi on pakollinen.";
}
else {
$nimi = $_POST["nimi"];
$_SESSION["nimi"]=$nimi;
if (!preg_match("/^[a-zA-Z ]*$/",$nimi)) {
$_SESSION["nimiVirhe"] = " Nimi on väärässä muodossa.";
}
}
if (empty($_POST["sposti"])) {
$sposti = $_SESSION["sposti"];
$_SESSION["spostiVirhe"] = " Sähköposti on pakollinen.";
}
else {
$sposti = $_POST["sposti"];
$_SESSION["sposti"]=$sposti;
if (!filter_var($sposti, FILTER_VALIDATE_EMAIL)) {
$_SESSION["spostiVirhe"] = " Sähköpostiosoite on väärässä muodossa.";
}
}
if (empty($_POST["palaute"])) {
$_SESSION["palauteVirhe"] = "<br>Palaute on pakollinen.";
}
else {
$palaute = $_POST["palaute"];
$_SESSION["palaute"]=$palaute;
}
if($_SESSION["nimiVirhe"] == "" && $_SESSION["spostiVirhe"] == "" && $_SESSION["palauteVirhe"] == ""){
header("Location: yhteystesti.php");
return;
} else {
header("Location: palaute3.php");
return;
}
}
?>
The database insertion works fine so I'm not going to include it here.
Any idea what am I doing wrong here?
PS: This is a school assignment and the teacher tried to make it work but couldn't.
Ath the top of your palaute3.php file you have this
$_SESSION["nimiVirhe"]="";
$_SESSION["spostiVirhe"]="";
$_SESSION["palauteVirhe"]="";
So you re-init your session error messages before using this them.
Those 3 lines should be in the validation page, but not in your error page !
Remove that and it will work.
Im currently trying to do a login code by myself and i cant figure out how ot work whit session. If anyone can examine my code and say were are the errors i would be much obliged.
Sorry for the lack of organization first time posting here.
Sorry for my english(not my native language), im portuguese.
-index.php
<html>
<head>
<?php session_start(); ?>
<title> Login Page </title>
</head>
<body>
<form action="login2.php" method="post">
<table width="200" border="0">
<tr>
<td> UserName</td>
<td> <input type="text" name="user" > </td>
</tr>
<tr>
<td> PassWord </td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<tr>
<td> Email </td>
<td><input type="email" name="email"></td>
</tr>
<tr>
<td> <input type="submit" name="login" value="LOGIN"></td>
<td>Logout</td>
</tr>
</table>
</form>
</body>
</html>
Home.php
<?php
require_once 'database.php';
$res=mysql_query("SELECT * FROM users WHERE id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res); ?>
<html>
<head>
<title> Home </title>
</head>
<body>
<?php
if(!isset($_SESSION['use']))
{
header("Location:Login.php");
}
echo $userRow['userEmail'];
echo "Login Success";
echo "<a href='logout.php'> Logout</a> ";
?>
</body>
</html>
logout.php
<?php
session_start();
echo "Logout Successfully ";
session_destroy(); // function that Destroys Session
header("Location: Login.php");
?>
database.php
<?php
// this will avoid mysql_connect() deprecation error.
error_reporting( ~E_DEPRECATED & ~E_NOTICE );
// but I strongly suggest you to use PDO or MySQLi.
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '');
define('DBNAME', 'database_sof');
$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);
?>
login2.php
<?php
require_once 'database.php';
if(isset($_SESSION['user'])) {
header("Location:home.php");
}
if(isset($_POST['login'])) {
$user = $_POST['user'];
$pass = $_POST['pass'];
$email = $_POST['email'];
if(empty($user)){
echo "Please enter your username.";}
if(empty($pass)){
echo "Please enter your passoword.";}
if(empty($email)){
echo "Please enter your email.";}
$res=mysql_query("SELECT id, username, password FROM users WHERE email='$email'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res);
if( $count == 1 && $row['password']==$pass ) {
$_SESSION['user'] = $row['id'];
session_start();
header("Location: home.php");} else {
echo $user;
echo "<br>";
echo $pass;
echo "<br>";
echo $email;
echo "<br>";
echo $count;
echo "<br>";
echo $row['password'];
echo "<br>";
echo "Incorrect Credentials, Try again...";
}}?>
(sorry for my english)
if you want to use $_SESSION variable in your file, you must write session_start() at the beginning of that file AND before any output (as Koala Yeung said).
somefile.php:
<?php
session_start();
...
//now you can read or edit $_SESSION
$_SESSION['bar'] = "bar";
$foo = $_SESSION['foo'];
I have created a form for a quiz, where you have to enter the answers and a PHP script will total them and send them to en E-Mail address and save them to a file. However, the user is only redirected on the 2nd attempt (submission) of the form. The results are totalled and sent on the first submission, but it does not redirect. On the 2nd submission, the results are not totalled, but an e-mail is sent and the user is redirected to the completion page.
Here is my code:-
<!DOCTYPE html>
<head>
<title>Quiz</title>
<link rel="stylesheet" type="text/css" href="../styles.css" />
<link rel="shortcut icon" href="../img/favicon.ico" type="image/x-icon" />
</head>
<?php
error_reporting (E_ALL ^ E_NOTICE);
session_start();
if (isset($_SESSION['username'])) $username = $_SESSION['username'];
else header("Location: http://quiz.dibdibguy.com/client/index");
include_once($_SERVER['DOCUMENT_ROOT']."/scripts/sql.php");
$qid = $_SESSION['quiz'];
$con = connect();
$data = mysqli_query($con, "SELECT * FROM `qs` WHERE `id`='$qid' LIMIT 1");
$qinfo = mysqli_fetch_array($data, MYSQLI_ASSOC);
?>
<body><div id="white"> </div>
<div id="content" class="text">
<div class="header">Quizzes</div>
<div class="subheader">Quiz: <?php echo($qinfo['name']); ?></div>
<table width="85%" class="menu text" align="center">
<tr>
<td>
<div align="center"><?php if ($qinfo['desc'] == NULL) echo($qinfo['name'] . ", has no description available."); else echo($qinfo['desc']); ?></div>
</td>
</tr>
</table>
<br>
<?php
$table = $qinfo['table'];
$questionsTable = mysqli_query($con, "SELECT * FROM `$table`");
?>
<table width="85%" class="menu text" align="center">
<tr>
<td>
<div align="left"><b>Please Remember:</b> For questions that require you to type an answer, you must spell it correctly, as the system cannot detect spelling errors.<br>
<b>Playing as: <i><?php echo($_SESSION['username']); ?></i></b></div>
</td>
</tr>
</table>
<br>
<table width="85%" class="menu text" align="center">
<tr>
<td>
<form method="post" name="quiz" action="">
<?php
$amt = mysqli_num_rows($questionsTable);
$count = 1;
echo($questions['que']);
while($ques = mysqli_fetch_array($questionsTable)){
echo("Question: " . $ques['que'] . "<br>");
echo("Answer: <input type=\"text\" name=\"$count\"><br><br>");
$count = $count + 1;
}
?>
<input type="submit" name="submit" value="Submit Answers" id="btn">
</form>
</td>
</tr>
</table>
<?php
if (isset($_POST['submit'])){
$answers = mysqli_query($con, "SELECT `ans` FROM `$table`");
$u_answers = $_POST;
$correct = 0;
while($answer = mysqli_fetch_assoc($answers)){
echo("Hi");
foreach($u_answers as $u_ans){
if ($answer['ans'] == strtolower($u_ans)) $correct = $correct + 1;
$count = $count + 1;
}
}
header("Location: http://quiz.dibdibguy.com/client/index");
#WRITE DATA TO FILE
$file = fopen("../results/" . strtoupper($_SESSION['username']) . "_" . date("d-m-Y_h:i_sa") . "_" . strtoupper($_SESSION['quiz'] . ".txt"), 'w');
fwrite($file, ($correct) . "/" . ($amt));
fclose($file);
mail("aaron#dibdibguy.com", $_SESSION['username'] . "quiz results", $correct . "/" . $amt);
$_SESSION['quiz'] = $qinfo['name'];
}
close($con);
?>
<br>
<?php include "../footer.php"; ?>
<br>
<br>
</div>
</body>
</html>
On the 1st attempt, if I get 1 question correct, I receive an e-mail stating; '1/39', which is what should happen, but on the 2nd attempt, I get an e-mail stating '0/', even if I get some correct.
Thanks in advance for any assistance. If you need anything else, please, E-Mail me (aaron#dibdibguy.com), or comment on this question!
Web Host: unlimitedwebhosting
PHP Version: 5.5
I see two problems.
First - HTML headers have to be sent before any content is sent. If you look in your error logs there are likely warnings about this. You print quite a lot of html to the page before your location header is used for the redirect. Since it's too late for headers it's ignored (you don't get redirected). To fix this either move the redirect logic further up the page before any output (and plain HTML counts as output) or use output_buffering to keep the output from being sent to the browser until you've sent all your headers.
Second - The '0/' email seems to be an error in your logic. If you look at this block:
if (isset($_POST['submit'])){
... Other Stuff
mail("aaron#dibdibguy.com", $_SESSION['username'] . "quiz results", $correct . "/" . $amt);
... More Stuff
}
The logic you've written says that the email will be sent any time the submit button is pressed. You never did a 'sanity check' to see if you actually have any valid information in the form first.
I am having trouble redirecting my code to another page after a correct username/password has been submitted. After I enter the username/password and hit submit, the page does not redirect.
The page just reloads and clears the field inputs (even though it's a sticky form), and stays at the same page, except the URL adds ?submit=Submit to the end of the URL..
I am not getting any mysql errors - the database is connecting fine at the query that matches the row with the username/password combo seems to be going through.
It should be looping through the database, checking if the username/password combo exists, and redirecting to the specified page. I'm not sure what I'm not seeing / missing here that keeps the page from redirecting. Any input would be greatly appreciated.
PHP:
<?php
define('DB_LOCATION', 'x');
define('DB_USERNAME', 'x');
define('DB_PASS', 'x');
define('DB_NAME', 'x');
$dbc = mysqli_connect(DB_LOCATION, DB_USERNAME, DB_PASS, DB_NAME)
or die('Error connecting to database');
$error_message= "";
if (isset($_POST['submit'])) {
$user_name = $_POST['user'];
$user_password= $_POST['pass'];
// ADD QUERY TO CHECK IF USER/PASS COMBO IS CORRECT
if(!empty($user_name) && !empty($user_password)) {
$query = "SELECT * FROM employees WHERE username='$user_name' and password='$user_password'";
$result = mysqli_query($dbc, $query)
or die ('Error querying username/password request');
if(mysqli_num_rows($result) == 1) {
$user_name = $row['user'];
$user_password = $row['pass'];
header("Location: www.mysite.com ");
} // end if rows
else {
$error_message = "You were not able to log in";
} // end else
} // end query
} // end isset
?>
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<link type="text/css" rel="stylesheet" href="/LESSON5/5_Signup_CSS.css">
</head>
<body>
<h1>Welcome to my website!</h1>
<h2>Please login below.</h2>
<h3>Don't have an account? Create one here.</h3>
<div class="formFormat" >
<div id="table1">
<form name =loginForm method="post" action="<?php echo $_SERVER[' PHP_SELF' ];?>">
<table id="cssTable">
<tr>
<td>Username:</td><td><input type="text" id="user" name="user" value="<?php echo $user_name ?>" /></td>
</tr>
<tr>
<td>Password:</td><td><input type="text" id="pass" name="pass" value="<?php echo $user_password ?>"/></td>
</tr>
</table>
</form>
</div>
<div id="table2">
<form>
<table>
<tr>
<td><input type="submit" name="submit"/></td>
</tr>
<tr>
<td id="createAccount">Create an account</td>
</tr>
<tr>
<td><?php echo $error_message ?></td>
</tr>
</table>
</form>
</form>
</div>
</div>
<?php
mysqli_close($dbc);
?>
</body>
</html>
Remove <form>, just before <div id="table2">, and </form> as well.
Remove <form> and </form> just before <div id="table2"> but i say you create a simple function which handles the redirects like below.
why don't you try something like this which creates a function for the redirect.
function Redirect($url, $permanent = false)
{
header('Location: ' . $url, true, $permanent ? 301 : 302);
exit();
}
Redirect('Location: www.mysite.com', false);
I'm creating a page with PHP for a class and when I echo things it shows up in the wrong place.
Here is my HTML page
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>About</h1>
<form action="Insert.php" method="post">
<table>
<tr>
<td><span>First name:</span></td>
<td><input type="text" name="firstname"></td>
</tr>
<tr>
<td><span>Last name:</span></td>
<td><input type="text" name="lastname"></td>
</tr>
<tr>
<td><span>Age:</span></td>
<td><input type="number" name="age"></td>
</tr>
</table>
<input type="submit">
</form>
<?php include("Footer.php");?>
</div>
</body>
</html>
Here is my PHP page:
<?php
$con = mysql_connect("localhost","USERNAME","PASSWORD");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
mysql_select_db("a7068104_world") or die("Cannot connect to database");
header("refresh:1.5; url=NamesAction.php");
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$fullname = mysql_real_escape_string($_POST['firstname'] . " " . $_POST['lastname']);
$age = mysql_real_escape_string($_POST['age']);
$query = "SELECT * FROM names_1 WHERE fullname='$fullname'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname, lastname, fullname, age) VALUES('$firstname', '$lastname', '$fullname', '$age')";
$result = mysql_query($query);
if($result) {
echo "Your name was successfully added to the database!";
}
else{
echo "Your name couldn't be added to the database!";
}
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>
When I echo stuff in my PHP page it shows up at the very top of the frame that it's in right above the
<div id="main">
I want the echoed text to go in the very bottom of the
<div id="main">
Is there any way that I can do that? I appreciate your help!
Thanks,
Leonardude
Your issue is that you are echo'ing the message before you supply your HTML.
Which is evident here:
if($result) {
echo "Your name was successfully added to the database!";
}
else{
echo "Your name couldn't be added to the database!";
}
Because PHP is a server-side language and HTML is client-side, the PHP will process well before the HTML, meaning it will echo before the page is displayed. Hence the issue where it is before your <div id="main"></div>.
A way around this is by setting a variable
if($result) {
$var = "Your name was successfully added to the database!";
}
else{
$var = "Your name couldn't be added to the database!";
}
And somewhere in your <div id="main"></div> you could do something like the following:
<div id="main">
<?php
if(isset($var) && !empty($var)) {
echo $var;
}
?>
</div>