I'm currently learning php so I'm a beginner I have learned the basics and some advanced stuff but now I'm trying to make a project to help me learn faster which will be basically a Math test in times table in which a user will enter the site, and then the user will enter his name and click 'Begin test' to enter the test which is 10 questions. the user need to answer the question first by clicking on a button and then click on 'Next' to go to next question and after finishing 10 questions the result will be shown to him something like "You have answered CorrectAnswersNumber from total of 10 questions!".
I have made something like this when I was learning ASP.Net MVC but in php it is a bit complicated. So my question is should I need to create 10 php pages that contains code to generate random numbers for the questions? if so how can I pass whether the user has answered the question right or wrong?
What I have did so far is the page in the first which contain the username and save it by using a session here is my code for the index.php page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Math Test</title>
</head>
<body style="background-color: #DDD">
<h1 style="font-size: 75px;" align="center">Math Test</h1>
<form method="POST" action="Math_Test.php">
<div style="text-align: center;">
<input type="text" name="Name" style="width: 500px; height: 100px; font-
size: 75px; color: blue;">
<br /><br />
<input type="submit" value="Begin Test" style="width: 250px auto;
height: 100px auto; font-size: 75px;">
</div>
</form>
</body>
</html>
and the code for the secondpage:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$Name = $_POST['Name'];
} else {
echo "<h1 align='center' style='margin-top: 250px;'>Sorry, You can't
access this page directly.<br /> Please go back ant try again or simply
click here!</h1>";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Math Test</title>
</head>
<body style="background-color: #DDD;">
<?php echo "<h1 align='center' style='font-size: 100px;'>Hi " . $Name .
"</h1>"; ?>
</body>
</html>
You can do something like this on your index page
<?php
// starts session
session_start();
// check if submit button was clicked
if ( isset($_POST['submit']) ) {
$name = htmlspecialchars(trim($_POST['name']));
// check if name was provided
if ( $name !== '' ) {
// store name in session
$_SESSION = array(
'answered_questions' => 0,
'correct_answers' => 0,
'wrong_answers' => 0,
'name' => $name
);
// redirect to second page
header('Location: second_page.php');
exit();
}
// set error if name was not provided
$error = 'Please provide your name';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Math Test</title>
</head>
<body style="background-color: #DDD">
<h1 style="font-size: 75px;" align="center">Math Test</h1>
<?php
// no name was provided so display the error message
if ( isset($error) ) {
echo '<p style="color: red">'. $error . '</p>'
}
?>
<form method="POST" action="">
<div style="text-align: center;">
<input type="text" name="name" style="width: 500px; height: 100px; font-
size: 75px; color: blue;">
<br /><br />
<input type="submit" name="submit" value="Begin Test" style="width: 250px auto;
height: 100px auto; font-size: 75px;">
</div>
</form>
</body>
</html>
And then on your second page you do something like so
<?php
// starts session
session_start();
// check if name key and value is not in the session
// if not there, then redirect back to the index.php page
if ( !isset($_SESSION['name']) ) {
header('Location: index.php');
exit();
}
if ( isset($_POST['submit']) ) {
$answer = (int)$_POST['answer'];
$expected_answer = $_SESSION['first'] * $_SESSION['second'];
$_SESSION['answered_questions'] += 1;
if ( $expected_answer == $answer ) {
$_SESSION['correct_answers'] += 1;
} else {
$_SESSION['wrong_answers'] += 1;
}
if ( $_SESSION['answered_questions'] == 10 ) {
// reset the session values from that page except name of course
header('Location: show_results.php');
exit();
}
$_SESSION['first'] = rand(1, 10); // random number between 1 and 20
$_SESSION['second'] = rand(1, 10);
} else {
$_SESSION['first'] = rand(1, 10); // random number between 1 and 20
$_SESSION['second'] = rand(1, 10);
}
// set the variable name to value in the session
$name = $_SESSION['name'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Math Test</title>
</head>
<body>
<?php var_dump($_SESSION); ?>
<h1>Hello, <?php echo $name; ?></h1>
<form method="POST" action="">
<p><?php
echo $_SESSION['first'] . ' * ' . $_SESSION['second'] . ' = ';
?><input type="text" name="answer" id="answer" required></p>
<p><input type="submit" name="submit"></p>
</form>
</body>
</html>
Then after if you want you can handle all the logic on the second page if you want as per #SamiKuhmonen advice
You don't need to do 10 pages for PHP to handle the math test that you are trying to do, instead, there is a technique called AJAX, which you can read about it from this URL:
https://www.tutorialspoint.com/php/php_and_ajax.htm
they have a very nice tutorial that deals with databases as well, which will help you in your case.
Give it a look and try to implement it, it will help you learn much faster.
Just for the record, PHP does have MVC frameworks, two are popular for developers,
Laravel: https://laravel.com/
Codeigniter: https://codeigniter.com/
Both supports MVC, I'll recommend you to go first with Codeigniter, once you feel that you are comfortable in PHP, switch to Laravel.
All the best, happy coding!
Related
I have created a code that run in a popup of WordPress website, the purpose of this code is to validate entered data available in mysql db table if available it displays relative code else it executes other code.
I have tried
action="<?php echo $_SERVER['PHP_SELF']; ?>"
and
headlocation(.......)
but none worked, it is submitting code and redirecting to index.php to display results.
<style><?php include 'search-zip.css'; ?>
</style>
<?php
include 'search-config.php';
$conn = OpenCon();
?>
<h3 class="formhead">Available in</h3>
<h2 class="formhead">Melbourne Inner Suburbs</h2>
<form class="form-wrapper" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="$POSTCODE" id="search" size="25" maxlength="35" value="<?php echo $_REQUEST['$POSTCODE'] ?>" />
<input type="submit"
name="submit" value="Search" id="submit"></form>
<p class="form-text">Please search your postal code for service availability</p>
<?
if (isset($_POST['submit'])) {
{
$zipcode=$_REQUEST['$POSTCODE'];
$sql = "SELECT * FROM service_location WHERE zipcode = $zipcode";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
?>
<style>.formhead{display:none;} .form-wrapper{display:none;} .form-text{display:none;}</style>
<div class="available">
<img class="zipimage" src="https://www.hastygrocer.com.au/wp-content/uploads/2019/07/hasty-grocer-available-popup-image.png" alt="Happy Minion" >
<h2 style="text-align: center;">Experience Melbourne's</h2>
<h2 style="text-align: center;"><i style="color: #3aafa9; font-family: Faster One script=all rev=2; font-size: 60px;">Fast</i> & <b style="color: green; font-family: Aladin; font-size: 60px;">Fresh </b></h2>
<h2 style="text-align: center;">Grocery Delivery</h2>
<span class="pum-close popmake-close "><button class="zipbutton" type="button">Shop</button></span></div>
<?
} else {
?>
<style>.formhead{display:none;} </style>
<div class="available">
<h3 style="text-align: center;">Get Notified When Available in <b style=" text-align: center;font-weight: 800; font-family: arial; color: #3aafa9;"><?php echo "$zipcode"?></b></h3>
<div class="zipform"><?php echo do_shortcode( '[contact-form-7 id="613" title="PopUp"]' ); ?></div>
</div>
<?
}
}}
?>
I created this code to redirect to same page.
but this is redirecting to index.php to display result.
please help me in fixing this using any php or ajax that may fix this code.
sorry I am not an expert developer I got code from internet and created the following code.
Thanks in advance
See this part of code: action="<?php echo $_SERVER['PHP_SELF']; ?>"
The submit will be performed to the link passed from the $_SERVER array, but PHP manual says:
$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these.
Try to make an <? echo $_SERVER['PHP_SELF']; ?> and see what is printed. You will probably get the index.php location.
Try to set the action to the page that contains the form.
I'm writing a program that has 3 pages.
On page 1 there is an option for the user to select a quantity of a breakfast product he wants to purchase. After selecting a quantity the user hits the submit button, if the user is not registered, it will take him to Page 2 for him to register. If the user is registered, it will direct them to Page 3.
However, if the user goes to Page 2 first and does not have a quantity selected from Page 1 it will redirect him to Page 1 after he registers and press submit, and then once they select a quantity and hit submit on Page 1 it will go to Page 3.
I'm struggling to maintain my session variables between the pages because two of them have forms that get overwritten if the user ever goes back to that page.
Page 1:
<?php
session_start();
$_SESSION['name']= $_POST['name'];
$_SESSION['email']= $_POST['email'];
$platter_quantity = $_SESSION['platter_quantity'];
$yogurt_quantity = $_SESSION['yogurt_quantity'];
$waffles_quantity = $_SESSION['waffles_quantity'];
?>
<!DOCTYPE html>
<head>
<title>Product Page</title>
<link rel="stylesheet" type"text/css" href="settings.css">
</head>
<html>
<body>
<ul>
<li><a class="active" href="product.php">Product</a></li>
<li>Registration</li>
<li>Invoice</li>
<li style="float:right">Login</li>
</ul>
<?php
$action = '';
if (!empty($_SESSION['name']) or !empty($_SESSION['email'])) {
$action = "invoice.php";
}
else {
$action = "registration.php";
}
?>
<form action="<?php echo $action; ?>" method="post">
<div class="container">
<img src="images/platter.jpg" alt="Breakfast Platter" style="float: left; width: 400px; height: 300px;";>
<h1>Breakfast Platter</p>
<p>The breakfast platter option comes with two fried eggs, four pancakes, and a bunch of bacon.</p>
Quantity: <input type="number" name="platter_quantity" min="0">
<p value="10.99" name="platter_price">Price: $10.99</p>
</div>
<div class="container">
<img src="images/yogurt.jpg" alt="Yogurt Parfait" style="float: left; width: 400px; height: 300px;">
<h1>Yogurt Parfait</p>
<p>The yogurt parfait option comes with two cups of yogurt, oats, and a mixture of berries.</p>
Quantity: <input type="number" name="yogurt_quantity" min="0">
<p value="6.99" name="yogurt_price">Price: $6.99</p>
</div>
<div class="container">
<img src="images/waffles.jpg" alt="Waffles" style="float: left; width: 400px; height: 300px;";>
<h1>Waffles</p>
<p>The waffles option comes with two buttermilk waffles with butter and syrup.</p>
Quantity: <input type="number" name="waffles_quantity" min="0">
<p value="$4.99" name="waffles_price">Price: $4.99</p>
</div>
<br>
<button class="button" type="submit" name="submit">Submit</button>
</form>
</body>
</html>
Page 2:
<?php
session_start();
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$_SESSION['platter_quantity'] = $_POST['platter_quantity'];
$_SESSION['yogurt_quantity'] = $_POST['yogurt_quantity'];
$_SESSION['waffles_quantity'] = $_POST['waffles_quantity'];
?>
<!DOCTYPE html>
<head>
<title>Registration Page</title>
<link rel="stylesheet" type"text/css" href="settings.css">
</head>
<html>
<body>
<ul>
<li>Product</li>
<li><a class="active" href="registration.php">Registration</a></li>
<li>Invoice</li>
<li style="float:right">Login</li>
</ul>
<br>
<?php
$action = '';
if (!empty($_SESSION['platter_quantity']) or !empty($_SESSION['yogurt_quantity']) or !empty($_SESSION['waffles_quantity'])) {
$action = "invoice.php";
}
else {
$action = "product.php";
}
?>
<form action="<?php echo $action; ?>" method="post">
Name: <input type="text" name="name" pattern="[A-Za-z]" required><br><br>
E-mail: <input type="text" name="email" pattern="/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/" required><br><br>
<input type="submit">
</form>
<br>
<?php
print_r($_SESSION);
echo "<br>Platter: " . $_SESSION["platter_quantity"] . "<br>";
echo "Yogurt: " . $_SESSION["yogurt_quantity"] . "<br>";
echo "Waffles: " . $_SESSION["waffles_quantity"];
?>
</body>
</html>
Page 3:
<?php
session_start();
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$platter_quantity = $_SESSION['platter_quantity'];
$yogurt_quantity = $_SESSION['yogurt_quantity'];
$waffles_quantity = $_SESSION['waffles_quantity'];
?>
<!DOCTYPE html>
<head>
<title>Invoice Page</title>
<link rel="stylesheet" type"text/css" href="settings.css">
</head>
<html>
<body>
<ul>
<li>Product</li>
<li>Registration</li>
<li><a class="active" href="invoice.php">Invoice</a></li>
<li style="float:right">Login</li>
</ul>
<h1>Hi! Welcome <?php echo $_SESSION['name']; ?>! </h1>
<?php
print_r($_SESSION);
echo "<br>Platter: " . $platter_quantity . "<br>";
echo "Yogurt: " . $yogurt_quantity . "<br>";
echo "Waffles: " . $waffles_quantity;
?>
</body>
</html>
What's the best way for me to implement this using session variables without using a database?
I tried doing this as well, but it did not seem to work:
<?php
session_start();
if (empty($_SESSION['name']) or empty($_SESSION['email'])) {
$_SESSION['name'] = $POST_['name'];
$_SESSION['email'] = $POST_['email'];
}
else {
$name = $_SESSION['name'];
$name = $_SESSION['email'];
}
if (empty($_SESSION['platter_quantity']) or empty($_SESSION['yogurt_quantity']) or ($_SESSION['waffles_quantity'])) {
$_SESSION['platter_quantity'] = $POST_['platter_quantity'];
$_SESSION['yogurt_quantity'] = $POST_['yogurt_quantity'];
$_SESSION['waffles_quantity'] = $POST_['waffles_quantity'];
}
else {
$platter_quantity = $_SESSION['platter_quantity'];
$yogurt_quantity = $_SESSION['yogurt_quantity'];
$waffles_quantity = $_SESSION['waffles_quantity'];
}
?>
You never insert $_POST or $_GET without first checking if they're set isset($_POST['variable']), and you can use checks here as well - do a check for the existence of $_POST-variables, and if they exist, use them, and if not, assign the $_SESSION-variables. So on page 3, you will have something like:
$name = $_SESSION['name'] = (isset($_POST['name']) ? $_POST['name'] : ((isset($_SESSION['name']) ? $_SESSION['name'] : '')));
And so on for the other variables. What this does is checks for $_POST, and if it's set, it updates the $_SESSION-variable, and if it's not set, it just updates the $_SESSION-variable with the already existing $_SESSION-variable, and if that doesn't exist either, it sets both variables $name and $_SESSION['name'] to empty, which you then can check for later in the script (and redirect etc.)
This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 7 years ago.
I am trying send email using php mail() function. It sends email but only HTML Part and not including the dynamic values through php. Any help will be appreciated.
I am trying to make it work but it is not working. I have tried multiple variations but still it only sends HTML part.
$to = $vendor_email;
$subject = "";
$mime_boundary = '<<<--==+X['.md5(time()).']';
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-Type: multipart/mixed;';
$headers[] = ' boundary="'.$mime_boundary.'"';
$message = '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/home.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<title>BuyBusTours</title>
<style>
body{
font-family: Calibri,Candara,Segoe,"Segoe UI",Optima,Arial,sans-serif;
}
h4{
text-align: center;
}
#wrapper{
width: 60%;
}
hr{
border-color: black;
border-width: 1px;
}
label{
display: inline-block;
width: 250px;
}
</style>
</head>
<body>
<div class="container" id="wrapper">
<h3 style="text-align: center; background-color: orange; height: 60px; padding-top: 18px;">Booking Confirmation for Order Number: { <?php echo $order_id;?> }</h3>
<h4>Dear <?php echo $vendor_name ?></h4><br>
<h4>Thank you for Choosing BuyBusTours</h4>
<hr>
<p style="color:red;">This is the confirmation email that we have received your order and it is processing. Please do not confuse it with your e-ticket.</p>
<p>We have received your order and we are working on it. As soon as your order is confirmed we will send your E-Ticket. Complete information about your tour and other important details will be mentioned on your E-Ticket. If in case your tour is sold out or it is not operating we shall refund your complete payment.
</p>
<p>This is <b>NOT A CONFIRMATION</b> that you have reserved a seat on the bus. We are working on your order and as soon as it is confirmed we will send your e-ticket.</p>
<hr>
<h3 style="color:#F60">Order Details</h3>
<label>Tour Name:</label><?php echo $tour_name;?><br>
<label>Departure Date</label> <?php echo $dept_date;?> <br>
<label>Departure Location:</label> <?php echo $dept_loc;?> <br>
<label>Tour Code:</label> <?php echo $tourcode;?> <br>
<label>Vendor Tour Code:</label> <?php echo $vendorcode;?> <br>
<label>Number of People:</label> <?php echo $no_of_adult + $no_of_child;?> <br>
<?php if (!empty($no_of_rooms)) { ?>
<?php for ($i = 1 ; $i <= $no_of_rooms ; $i++) {?>
<?php if ($i == 1) {?>
<label style="color:#F33">Room <?php echo $i;?></label> <br>
<?php if (!empty($room1traveler1)) {?>
<label>Traveler 1: </label>
<?php echo $room1traveler1;?><br>
<?php } ?>
<?php if (!empty($room1traveler2)) {?>
<label>Traveler 2: </label>
<?php echo $room1traveler2;?><br>
<?php } ?>
<?php if (!empty($room1traveler3)) {?>
<label>Traveler 3: </label>
<?php echo $room1traveler3;?><br>
<?php } ?>
<?php } ?>
<?php if ($i == 2) {?>
<label style="color:#F33">Room <?php echo $i;?></label><br>
<?php if (!empty($room2traveler1)) {?>
<label>Traveler 1: </label>
<?php echo $room2traveler1;?><br>
<?php } ?>
<?php if (!empty($room2traveler2)) {?>
<label>Traveler 2: </label>
<?php echo $room2traveler2;?><br>
<?php } ?>
<?php if (!empty($room2traveler3)) {?>
<label>Traveler 3: </label>
<?php echo $room2traveler3;?><br>
<?php } ?>
<?php } ?>
<?php if ($i == 3) {?>
<label style="color:#F33">Room <?php echo $i;?></label><br>
<?php if (!empty($room3traveler1)) {?>
<label>Traveler 1: </label>
<?php echo $room3traveler1;?><br>
<?php } ?>
<?php if (!empty($room3traveler2)) {?>
<label>Traveler 2: </label>
<?php echo $room3traveler2;?><br>
<?php } ?>
<?php if (!empty($room3traveler3)) {?>
<label>Traveler 3: </label>
<?php $row["room3_traveler3"];?><br>
<?php } ?>
<?php } ?>
<?php if ($i == 4) {?>
<label style="color:#F33">Room <?php echo $i;?></label><br>
<?php if (!empty($room4traveler1)) {?>
<label>Traveler 1: </label>
<?php echo $room4traveler1;?><br>
<?php } ?>
<?php if (!empty($room4traveler2)) {?>
<label>Traveler 2: </label>
<?php echo $room4traveler2;?><br>
<?php } ?>
<?php if (!empty($room4traveler3)) {?>
<label>Traveler 3: </label>
<?php echo $room4traveler3;?><br>
<?php } ?>
<?php } ?>
<?php } }?>
<hr>
<h3 style="color:red; text-align:center">Total Amount Charged: <?php echo $total_price;?></h3>
<h3 style="text-align: center; background-color: orange; height: 60px; padding-top: 18px;">Contact us at: 0345-1272211</h3>
</div>
</body>
</html>';
$message = html_entity_decode($message);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to, $subject, $message, $headers);
<h4>Dear <?php echo $vendor_name ?></h4><br>
Should be
<h4>Dear '.$vendor_name.'</h4><br>
The reason being is that in the mail body you are already in <?php ?> tags, and so there is no needs to repeat them.
What's happening here is you are ending $message='.......... with Dear '
and then concatenating with the . $variable . (concatenate again) '</h4> Resume writing out $message.
Repeat this for all of the times you use a variable within a string.
Anything in there such as an if() statement or a for() loop, you should calculate these before you start defining any of the email strings, and assign each of their results an individual $var and assign just like I mention above. This will also make your code less messy, easier to navigate and thus adjust if and when you need to.
Your email message is being sent inside single quotes, ', so no PHP variables will be interpolated inside it. That will fix quite a few of the problems immediately, but a bigger problem is that you appear to have PHP statements inside there too, such as loops and conditionals – you can't put those inside strings.
What you need to do is pre-calculate your text, i.e. moving all those loops and conditionals out of your HTML message text, so that whatever they calculate end up just being variables. You should then switch to using double-quoted strings (or, in this case, heredoc is probably easier) to put those values into your message.
I am new to php and I want to add a functionality such that whenever user fills the form and logs in, the php code runs perfectly fine but after refreshing the page user have to again fill the form. I don't know code nor have knowledge of further.I tried googling but I only see these kind of solutions:
header(refresh: 5, url: url);
or
meta tag
That refreshes automatically but not after clicking the refresh button.
This is my php code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="services.css"/>
<link rel="stylesheet" type="text/css" href="bootstrap-css/bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="bootstrap-3.3.5-dist/css/bootstrap.min.css">
<script type="text/javascript" src="validate.js"></script>
<style>
a{
color: dodgerblue;
}
a:hover{
color: dodgerblue;
font-size: 101%;
}
span{
font-size: 110%;
line-height: 8px;
font-style: bold;
margin-left: 50px;
}
body{
background-color: #F0F0F0 ;
}
button{
margin-left: 15px;
}
</style>
</head>
<body link="slateblue">
<div id="LogIn"><b>Log In</b></div><br>
<form method="post" onsubmit="return logInPass()" action="log.php">
<div class="col-xs-4"/>
<label for="usr">Email:</label>
<input id="usrEmail" name="usrEmail" type="email" class="form-control" size="25%" placeholder="sample#example.com"/>
</div>
<br><br><br><br>
<div id="PasswordField" class="col-xs-4"/>
<label for="u_pswd">Password:</label>
<input id="u_pswd" type="password" class="form-control" size="25%" placeholder="Enter alteast 8 characters" />
</div>
<br><br><br><br>
<button id="submit" name="checkout" class="btn btn-primary" type="submit" value="submit">Log In</button>
</form>
<br><br>
<span>Not a part of GameRangers? Click here for Sign Up!</span>
<br>
</body>
</html>
<?php
echo "<style>body{font-family: segoe ui; font-size: 110%;}</style>";
session_start();
$_SESSION['username'] = $_POST['usrEmail'];
echo"Welcome ".$_SESSION['username']."<br><br>";
echo "Today is ".date("Y-m-d")."<br>".date("h:i:sa")."<br>";
?>
use sessions:
session_start(); // in top of PHP file
...
$_SESSION["userName"] = $userName;
in your page
session_start();
if(isset($_SESSION["userName"]) && $_SESSION["userName"] != ''){
//redirect to logged in page
}
as you are using sessions to store user name . This session can be used in if condition as like i had used here:
<div id="nav1">
<?php session_start();
if($_SESSION['id']=='')
{
?>
<font style="font-size:16px; font-weight:bold; color:#063443;">Welcome, Guest <a href="Login.php" >SignIn</a></font>
<?php }
else
{ ?>
<font style="font-size:16px; font-weight:bold; color:#063443;">Welcome, <?php echo $_SESSION['name'];?> My Account</font>
<?php }
?></div>
Here i had stored User Id in session[id] which will make a condition to show user login or not.
Firstly you're outputting before header with the location of session_start();.
Place it as your first line under your opening <?php tag, and you're missing an underscore in $SESSION and for $SESSION['username'], it is a superglobal.
The session isn't being recorded/stored because of it.
Sidenote: I'm really hoping that wasn't a typo on your part.
That should read as $_SESSION['username']
Having used error reporting, would have signaled a notice of an undefined variable.
Make sure that $_POST['usrEmail'] also holds a value and the element bears the same name attribute, and that the session is started inside all pages using sessions and with no typos as you have now.
Add error reporting to the top of your file(s) which will help find errors.
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
If you want to retain session values in a form, use a ternary operator for the inputs:
<input type="text" name= "usrEmail" id="usrEmail" value="<?php echo !empty(htmlspecialchars($_SESSION['username'])) ? htmlspecialchars($_SESSION['username']) : ''; ?>">
...and apply that same method to your other form inputs.
Check to see if the session is set and not empty.
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_SESSION["userName"]) && !empty($_SESSION["userName"]) )
{
// do something
}
else{
// do something else
}
Use SESSION or COOKIES to store logged in status
On successful sign in, set a session variable or cookie.
Then check if the session variable or cookie is isset and is the intented value, then keep the user on the page. Otherwise, redirect to login.
Also keep session_start() at the beginning of the page.
Edits to make it clear for the OP
Add session_start() at the beginning of the page. After validating the username and password, if an existing user, set a session using the below code.
$_SESSION['u_name'] = $_POST['usrEmail'];
otherwise, redirect to login page.
Then on top of all user specific pages (the pages that are accessible only to logged in users) paste the below code.
session_start();
if(!isset($_SESSION['u_name']))
{
header('location:login.php?redirect='.$_SERVER['REQUEST_URI']);
exit;
}
Hope this will help.
I'm working on some sort of search engine that adds on to a URL to complete the request. using header(Location:http://www.WEBSITENAME.com/'. $search); Although sometimes this will send me to a blank page. Was wondering if there's any sort of code that will redirect me to another page if that error happens. I want the else to be what it redirects to if the page is blank. Thanks.
My code:
search.php
<?php
$search = $_POST["search"];
if(isset($_POST['search'])){
header('Location:http://cydia.saurik.com/package/'.$search);
}else{
?>
<?php
echo "
<head>
<style>
#header{
color:black;
}
.header{
color:black;
font-size:25px;
}
#header_minor{
margin-top:20px;
}
.header_minor{
font-size:18px;
}
a[class='header_minor']{
color:black;
}
body{
text-align:center;
margin-top:14%;
}
#idea{
margin-top:20px;
}
.hidden{
display:none;
visibility:hidden;
}
</style>
</head>
";
?>
<div id="header">
<span class="header">
Sorry, this tweak was not found...
</span>
</div>
<div id="header_minor">
<span class="header_minor">
Would you like to suggest it? or Return home
</span>
</div>
<div id="idea">
<form method="POST" action="idea.php" name="idea">
<input type="text" name="idea" value="<?php echo $_POST['search']; ?>"/>
<input type="text" name="hidden" class="hidden"/>
<input type="submit" value="Submit"/>
</form>
</div>
<?php
exit();
}
?>
It could have been better if you can call an api on that site so that you can interact easier with the external site.
I would do something like this:
PHP:
<?php
if(isset($_POST['search'])) {
$search_text = $_POST['search_field'];
$location_url = "http://cydia.saurik.com/package/{$search_text}/";
$content = #file_get_contents($location_url); // use this function to query on site
if($content) {
// redirect if it has a result
header("Location: {$location_url}");
} else {
// will go here if query on external site is empty (blank)
// create your own empty result page that says your search yielded no results (your own page, redirect the user)
// sample
header("Location: http://www.yoursite.com/index.php?noresults=1");
}
}
?>
HTML:
<form method="POST" action="index.php">
<input type="text" name="search_field" class="" id="" /><br/>
<input type="submit" name="search" class="" id="" value="Search" />
</form>
<?php if(isset($_GET['noresults'])): ?>
<div class="yourdesign" style="display: block; width: 300px; border: 1px solid black;";>
<h1>No results found</h1>
</div>
<?php endif; ?>