PHP problems with linking HTML. Doesn't redirect - php

Basically my shirt e-commerce website won't redirect to my html website. Whenever I try to click on the virtual try on button next to the shirt, it doesn't redirect me to the page instead it just loads and refreshes the current page. Any tips?
Here is my code:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="get">
<input type="hidden" name="product_id" value="124">
<input type="submit" value="Virtual Try ON" name="form_virtual_try_on">
</form>
<?php
$product_id = $_GET['product_id'] ?? '';
switch ($product_id) {
case '124':
$text = 'Virtual Try On';
$link = 'vton_ls.html';
break;
default:
$text = '';
$link = '';
break;
}
if (isset($_GET['form_virtual_try_on'])) {
$product_id = $_GET['product_id'];
if ($product_id == '124') {
header('Location: vton_ls.html');
exit;
} else {
echo "Invalid product ID";
}
}
?>
<div class="share">
<?php echo LANG_VALUE_58; ?> <br>
<div class="sharethis-inline-share-buttons"></div>
</div>
I tried GET, switch case, and redoing all my codes from scratch but it doesn't seem to work.

By simply adding little snippets of code rather than the actual full page it is potentially easy to misinterpret what you are trying to do and why things are going awry so if the following is not correct I apologise.
Given a testing target page (vton_ls.html) and an interpretation of the above
<?php
session_start();
if( !defined('LANG_VALUE_58') )define('LANG_VALUE_58','LANG_VALUE_58......... ok');
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['product_id'] ) ){
switch( intval( $_GET['product_id'] ) ){
case 124:
$text = 'Virtual Try On';
$link = 'vton_ls.html';
break;
default:
$text = '';
$link = '';
break;
}
exit( header( sprintf('Location: %s?product_id=%s&text=%s', $link, $_GET['product_id'], $text ) ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<form method='get'>
<input type='hidden' name='product_id' value='124' />
<input type='submit' />
</form>
<div class='share'>
<?php echo LANG_VALUE_58; ?> <br>
<div class='sharethis-inline-share-buttons'></div>
</div>
</body>
</html>
By clicking the button the form submits to the same page where the GET request is processed to build the new url that redirects to your html website

You already added the header and pls add anchor tag too
header ('Location: vton_ls.html');
you're trying to link from an HTML page to a PHP page, you can use an anchor tag like this:
Virtual Try-On

If you fail to complete this, you’ll probably see an error message that tells you “headers are already sent.” The error might not be a massive one — the header function is so finicky that a single white space can prompt this error.
<?php
header('Location: http://www.example.com/');
exit;
?>
<head>
<title>Example</title>
</head>
<body>
<p>Hello, world!</p>
</body>

Related

POST/REDIRECT/GET not working in PHP contact form

I am trying to configure a basic contact POST form with one checkbox input and server-side validation. This means the form must submit to itself, so a self-serving contact form. The problem I'm having is when refreshing the page, the form is submitted again.
I am using session data to store form validation as this form is an initial popup to which the user must tick and confirm to enter the page. The page has two contact forms on it but I am showing one and I think the implementation should be the same for both (correct me if I'm wrong). Once the user ticks the box and submits the form, the popup form will hide allowing the user to see the page.
To solve this, I believe the POST/REDIRECT/GET design pattern should prevent this, however, I don't think my implementation is correct and I don't know what is wrong in my code.
index.php code below:
<!DOCTYPE html>
<html lang="en">
<?php
session_start();
include('form_process.php');
?>
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="assets/css/main.min.css" />
</head>
<body>
<section id="selfCertOverlay" <?=$_SESSION['closeSelfCert']?>>
<div class="blurOverlay">
<form id="selfCert" method="post">
<label for="self_cert">I have read and confirm the statement.
<input type="checkbox" name="self_cert" id="self_cert">
<span id="checkmark" class="<?= ($_SESSION['self_cert_checkbox_error']) ? 'inputError' : ''; ?>"></span>
<span class="error"><?= (isset($_SESSION["self_cert_error"])) ? $_SESSION["self_cert_error"] : ''; ?></span>
</label>
<input type="submit" name="submit_self_cert" value="Confirm & Proceed">
</form>
</div>
</section>
</body>
</html>
form_process.php code below:
<?php
$_SESSION["self_cert_error"] = "";
$_SESSION["self_cert_checkbox_error"] = false;
if (!isset($_POST["self_cert"])) {
$_SESSION["self_cert_error"] = "Please read and accept the statement to proceed";
$_SESSION["self_cert_checkbox_error"] = true;
} else {
unset($_SESSION["self_cert_error"]);
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value) {
$keyOutput = str_replace('_', ' ', $key);
$keyOutput = ucwords($keyOutput);
$message_body .= "$keyOutput: $value\n";
}
$to = 'example#mailprovider.com';
$subject = 'Email Subject';
if (mail($to, $subject, $message_body)){
$_SESSION["closeSelfCert"] = 'style="display: none;"';
// Redirect to itself.
header( "Location: {$_SERVER['REQUEST_URI']}", true, 303 );
return;
}
}
?>
The refresh button on the browser resends the last HTTP request that was sent by the client. This is why when you refresh the page, it re-submits the form.
The only way to get around this is to use the POST/REDIRECT method.
To setup a POST/REDIRECT method, use an intermediate page to do the operations and then redirect to the original form afterwards.
For example:
index.php --> the page with the form on - make sure the form has action="form_process.php" declared, so it will POST the data to the form_process.php script
form_process.php --> receives the form data and carries out your operations, then redirects back to the index.php page at the end.
So your final code should look something like the below;
index.php
I have removed the include('form_process.php'); at the top
I have added action="form_process.php" to the <form> tag
<!DOCTYPE html>
<html lang="en">
<?php
session_start();
?>
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="assets/css/main.min.css" />
</head>
<body>
<section id="selfCertOverlay" <?=$_SESSION['closeSelfCert']?>>
<div class="blurOverlay">
<form id="selfCert" method="post" action="form_process.php">
<label for="self_cert">I have read and confirm the statement.
<input type="checkbox" name="self_cert" id="self_cert">
<span id="checkmark" class="<?= ($_SESSION['self_cert_checkbox_error']) ? 'inputError' : ''; ?>"></span>
<span class="error"><?= (isset($_SESSION["self_cert_error"])) ? $_SESSION["self_cert_error"] : ''; ?></span>
</label>
<input type="submit" name="submit_self_cert" value="Confirm & Proceed">
</form>
</div>
</section>
</body>
</html>
form_process.php
I have added session_start(); at the top so you can access the $_SESSION data
I have added header( "Location: index.php", true, 303 ); within your first IF statement
I have altered your header() routing which takes place after you send your email, so this redirects back to index.php
<?php
session_start();
$_SESSION["self_cert_error"] = "";
$_SESSION["self_cert_checkbox_error"] = false;
if (!isset($_POST["self_cert"])) {
$_SESSION["self_cert_error"] = "Please read and accept the statement to proceed";
$_SESSION["self_cert_checkbox_error"] = true;
header( "Location: index.php", true, 303 );
exit;
} else {
unset($_SESSION["self_cert_error"]);
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value) {
$keyOutput = str_replace('_', ' ', $key);
$keyOutput = ucwords($keyOutput);
$message_body .= "$keyOutput: $value\n";
}
$to = 'example#mailprovider.com';
$subject = 'Email Subject';
if (mail($to, $subject, $message_body)){
$_SESSION["closeSelfCert"] = 'style="display: none;"';
// Redirect back to the form page.
header( "Location: index.php", true, 303 );
exit;
}
}
?>

Creating a php program to compare video game characters

<?php
$connect = mysqli_connect("localhost", "root", "jmpmvp", "characters");
if ($connect){
echo "connected<br>";
}
$query = "SELECT * FROM `character`";
$result1 = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action ="handler.php" method="post">
<label for="character">SELECT A CHARACTER </label>
<select multiple name="character">
<?php while($character = mysqli_fetch_assoc($result1)){?>
<option value ="<?php echo $character['id'];?>"</option>
<?php echo $character['name'];?></option>
<?php }?>
<input type="submit" value="submit"/>
</select>
</form>
</body>
</html>
this is my index page above
<?php
$connect = mysqli_connect("localhost", "root", "jmpmvp", "characters");
if ($connect){
echo "connected<br>";
}
$query = "SELECT * FROM `character` where id = ". $_POST ["character"];
$result1 = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php while($character = mysqli_fetch_assoc($result1)){?>
<?php echo $character["name"];?><br>;
<?php echo $character["attack"];?><br> ;
<?php echo $character["defense"];?><br>;
<?php } ?>
</body>
</html>
alright here is my handler page the issue I am having is I can select multiple options in my html select on my index page but I am having a problem displaying when multiple characters are selected in my handler page. Does anyone know how to fix this specific issue? I also want the data to displayed in a table which I'm pretty sure I can figure out.
What You actually need is logical approach. You have to ask yourself a question "what You want", "what You need" and "how to do it".
So in Your case You want to compare something but You didn't actually say what exactly You need. So if You're new i can can help You that:
What You need for sure is webpage, where user can select character from a list. But what then? I don't know. You didn't specify so...:
1) Show user a select box to choose character. How to get them? Select from database. This is what You already have.
2) After user select character You need to send this data to the server. How to do it? Use <form> tag like:
<form method="post">
<select name="character">...option list...</select>
<input type="submit" value="Search">
</form>
3) Get data sent by Your form and use them to compare with... something You have.
<?php
if( isset( $_POST['character'] ) ){
// do something with this character
}
?>
4) Show user response like found or not found or something else. Pass this data into some div like:
<?php
$found = 'set this true OR false';
if( $found ){
$message = 'Found it!';
}else{
$message = 'Not_found!";
}
?>
Then in HTML write something like:
<div><?php echo isset( $message ) ? $message : ''; ?></div>
Thats it, rest is up to You. Any simple problem You will solve by searching in Google.
-------- Edit
First of all if You're using multiple select box, the name must be:
<select name="character[]" multiple>
Then Your $_POST['character'] is now an array. You can check its content by:
echo '<pre>';
var_dump($_POST);
echo '</pre>';
Use foreach:
$ids = []; // or $ids = array(); if php version lower than 5.4
foreach( $_POST['character'] as $v ){
$ids []= (int) $v;
}
$query = 'SELECT * FROM `character` where id IN ('. implode(',', $ids) .') ';

PHP Keep the variable scope even after the page reload

The website generates the random number from 1 to 100 when accessing the first page(page1.php). And the user will guess the number.
The first page contains
- a text box for accepting a
number from the user, and a submit button.
The second page(page2.php) will be returned to the user if the guess number is too high or too low. And the page shows a message telling the user "Too High" or "Too Low". The page also contains
a button(retry button) that allows the user to go back to the first page(page1.php) to re-enter a new number
a button that allows the user to quit the game.
The third page(page3.php) is returned to the user if the guess is correct. The page displays "Correct", the random number, and the count of tries.
And I have this index.php which is heart for all the pages. And here is the code.
index.php
<?php
$name = '';
$inputnumber = '';
$random = 33; //this is just an assumption to keep it simple
$message = '';
$guesscount = '';
if (isset($_POST['action'])) {
$action = $_POST['action'];
}
if ($action === 'guess') {
$guesscount = $_POST['$guesscount'];
$inputnumber = $_POST['$inputnumber'];
if ($inputnumber == $random) {
$message = "Correct!";
include 'page3.php';
}
if ($inputnumber > $random) {
$message = "Too High";
include 'page2.php';
}
if ($inputnumber < $random) {
$message = "Too Low";
include 'page2.php';
}
}
if ($action === 'retry') {
include 'page1.php';
}
page1.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Number Guess: <input type="text" name="$inputnumber" value="<?php if(isset($inputnumber)==1){
echo $inputnumber;}else echo ""; ?>" /><br>
<input type="submit" name="action" value="guess" />
<hr>
Guess Count: <?php echo $guesscount; ?>
</form>
</body>
</html>
page2.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Message: <?php echo $message; ?>
<input type="hidden" name="$guesscount" value="<?php echo $guesscount;?>"/><br>
<input type="submit" name="action" value="retry" />
<hr>
Guess Count: <?php echo $guesscount;?>
</form>
</body>
</html>
page3.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Message: <?php echo $message; ?>
Number of Tries: <?php echo $guesscount; ?>
<input type="submit" name="action" value="ok" />
</form>
</body>
</html>
page1.php is the page to load first.
Challenge I have faced is, I couldn't keep the $guesscount stable always. It keeps resetting on me. I have tried session but couldn't resolve it.Please help resolving it.
Thanks in advance.
I don't know why but my gut feeling tells me that the reason why the session is not working for you on other pages is because you do not initiate it ??
So what you have to do is:
index.php
<?php
session_start();
$_SESSION['myVariable'] = 'myVariable';
?>
page1.php
<?php
session_start();
$mySessionVar = $_SESSION['myVariable'];
var_dump($mySessionVar); // <- this should print myVariable
?>
You may get an error saying that $_SESSION is null or not set and to prevent that you can just enclose $_SESSION inside and isset method
if(isset($_SESSION['myVariable']) && $_SESSION['myVariable'] != null) {
$mySessionVar = $_SESSION['myVariable'[;
}

PHP $_SESSION Not checking login status

I've looked through multiple web articles and stackoverflow answers, however I cannot find the bug in my code. Maybe I've been looking at it too long.
Basically I'm just setting up a simple login for a demonstration, yes I know its inject-able and outdated, this doesn't matter. Basically I'm using a login with sessions and then redirecting the user to secure content when they're logged in. I've also created a script that checks for the session variables, to see if the user is logged in or not. Basically, I'm beating a dead horse and I don't know why this isn't working, could someone please help?
index.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome, please log in</title>
<link href="../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<?PHP require_once"scripts/mysql_connect.php"; // Establish a database connection ?>
<div id="admin_top">
<div id="admin_logo"></div>
</div>
<div id="admin_login_box">
<H1 style="margin-left: 20px;">Please log in</H1>
<hr><br>
<?PHP
echo "<form method='post' action='checklogin.php' name='loginform'>
<input type='email' name='aEmail' placeholder='Your Email Address' required><br>
<input type='password' name='aPassword' placeholder='Password' required><br><br>
<input type='submit' value='Log In'>
</form>"
?>
</div>
</body>
</html>
checklogin.php:
<!doctype html>
<html>
<head>
<title>Checking login...</title>
<link href="../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="admin_top">
<div id="admin_logo"></div>
</div>
<div id="admin_login_box">
<?php
require_once"scripts/mysql_connect.php";
$aEmail = $_POST['aEmail'];
$aPassword = $_POST['aPassword'];
$md5Password = MD5($aPassword);
$sql = "SQL";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$active = $row['active'];
$count = mysql_num_rows($result);
// If result matched, table row must be 1 row.
if($count == 1) {
$_SESSION["login"] = "OK";
$_SESSION["aEmail"] = $aEmail;
echo "<h1>Log in successfull!</h1>
<hr><br />
Your details checked out! Redirecting you now...";
// Wait 1 seconds then redirect to the secure content.
header("Location: http://www.website.com/secure_content.php");
} else {
echo "<h1>Log in unsuccessfull!</h1>
<hr><br />
Sorry. It seems your log in detials were incorrect. Please go back and try again.";
// Wait 2 seconds then redirect back to the log in page.
header("Location: http://www.website.com/index.php");
}
exit;
?>
</div>
</body>
</html>
loginstatus.php:
<?php session_start();
if(!(isset($_SESSION["login"]) && $_SESSION["login"] == "OK")) {
header("Location: http://www.website.com/index.php");
exit;
}
?>
Thanks for any help!
In checklogin.php and index.php you need to start the session. Add the following code before <!doctype html>
Add this code:
<?php session_start(); ?>
You forgot to put that line in this file because you are creating a new session during the checks in the database.
Looks like you haven't started the session in the first place. On the top of your page please write the following code:
<?php session_start(); ?>
Now, secondly, I'd suggest you to write your HTML and PHP separately instead of writing your HTML for the form within the echo.
Also, it's better if you add a name to your submit button.
Let me show a sample below.
<div id="admin_login_box">
<H1 style="margin-left: 20px;">Please log in</H1>
<hr><br>
<form method='POST' action='checklogin.php' name='loginform'>
<input type='email' name='aEmail' placeholder='Your Email Address' required><br>
<input type='password' name='aPassword' placeholder='Password' required><br><br>
<input type='submit' name='submit' value='Log In'>
</form>
Now, in your checklogin.php. you should place an isset condition and see if you're getting any POST request.
Try this:
<?php
require_once"scripts/mysql_connect.php";
if (isset($_POST['submit']) { // Add this condition
$aEmail = $_POST['aEmail'];
$aPassword = $_POST['aPassword'];
$md5Password = MD5($aPassword);
/* Other code */
if($count == 1) {
/* Other code */
} else {
/* Other code */
}
}
Hope this helps.

Congratulation page not showing the variable from the number-guessing game

I have a php script for a number-guessing game and an html script for a congratulation page. If the guess is correct, the game will end and the congratulation page will open. In the php, I have a variable $prize=1000-100 * $_POST['tries'], such that if the first guess is right, the player will win $1000; if the player has a second guess, the prize will be $100 less, and so on. This variable is saved in a hidden field in the php as $_POST['prize']. I hope the final prize can be printed in the congratulation page, but it didn’t work as I expected. Did I do anything wrong in the html? Thanks guys, Maria.
guess.php:
<?php
if(isset($_POST['number'])) {
$num = $_POST['number'];
} else {
$num = rand(1,10);
}
if(isset($_POST['prize'])) {
$prize =1000-100 * $_POST['tries'];
} else {
$prize = 900;
}
$tries=(isset($_POST['guess'])) ? $_POST['tries']+1: 0;
if (!isset($_POST['guess'])) {
$message="Welcome to the Guessing Game!";
} elseif (!is_numeric($_POST['guess'])) {
$message="You need to type in a number.";
} elseif ($_POST['guess']==$num) {
header("Location: Congrats.html");
exit;
} elseif ($_POST['guess']>$num) {
$message="Try a smaller number";
} else {
$message="Try a bigger number";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<p><strong>Guess number: </strong><?php echo $tries; ?></p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p><label for="guess">Type your guess here:</label><br/>
<input type="text" id="guess" name="guess" />
<input type="hidden" name="tries" value="<?php echo $tries; ?>"/><br/>
<input type="hidden" name="number" value="<?php echo $num; ?>"/><br/>
<input type="hidden" name="prize" value="<?php echo $prize; ?>"/>
</p>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</body>
</html>
congrats.html:
<! DOCTYPE html>
<html>
<header>
<title>Congratulation!</title>
<body>Congratulation!<br/>
You Won <?php echo $_POST['prize']; ?> dollars!
</body>
</header>
</html>
it looks like your script will work, but you'll need to change congrats.html to congrats.php because html is static and php is dynamic. Also you might want to use sessions because anyone can inspect-element and change the value.
You just need to pass the value to the congrats page, using either GET request or a session. I'd recommend using a session so people cannot alter the prize value.
Just amend this part here:
} elseif ($_POST['guess']==$num) {
$_SESSION['prize'] = $_POST['prize'];
header("Location: Congrats.php");
exit;
}
Then (you need to change the congrats page to a php page to use the session btw to enable php)
Congrats.php
<! DOCTYPE html>
<html>
<header>
<title>Congratulation!</title>
<body>Congratulation!<br/>
You Won <?php echo $_SESSION['prize']; ?> dollars!
</body>
</header>
</html>
PS: Session will also require session_start() at the top of both documents.

Categories