Clear Cookies and Session Data in PHP - php

I'm using PHP to clear all cookie data, specifically clear session data, clean session id, and delete the cookies for the session. I have the following code as part of my coding, but when I click the Clear All button, nothing happens. The rest of my buttons in the cases work as intended.
<?php
$lifetime = 60 * 60 * 24 * 365;
session_set_cookie_params ( $lifetime, '/' );
session_start ();
if (isset ( $_SESSION ['tasklist'] )) {
$task_list = $_SESSION ['tasklist'];
} else {
$task_list = array ();
}
$action = filter_input ( INPUT_POST, 'action' );
$errors = array ();
switch ($action) {
case 'add' :
$new_task = filter_input ( INPUT_POST, 'newtask' );
if (empty ( $new_task )) {
$errors [] = 'The new task cannot be empty.';
} else {
$task_list [] = $new_task;
}
break;
case 'delete' :
$task_index = filter_input ( INPUT_POST, 'taskid', FILTER_VALIDATE_INT );
if ($task_index === NULL || $task_index === FALSE) {
$errors [] = 'The task cannot be deleted.';
} else {
unset ( $task_list [$task_index] );
$task_list = array_values ( $task_list );
}
break;
case 'clear':
$_SESSION = array();
session_destroy();
$name = session_name();
$expire = strtotime('-1 year');
$params = session_get_cookie_params();
$path = $params['path'];
$domain = $params['domain'];
$secure = $params['secure'];
$httponly = $params['httponly'];
setcookie($name, '', $expire, $path, $domain, $secure, $httponly);
include('task_list.php');
break;
}
$_SESSION ['tasklist'] = $task_list;
include ('task_list.php');
?>
And in the main page:
<!DOCTYPE html>
<html>
<head>
<title>Task List Manager</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<header>
<h1>Task List Manager</h1>
</header>
<main> <!-- part 1: the errors -->
<?php if (count($errors) > 0) : ?>
<h2>Errors</h2>
<ul>
<?php foreach($errors as $error) : ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<!-- part 2: the tasks -->
<h2>Tasks</h2>
<?php if (count($task_list) == 0) : ?>
<p>There are no tasks in the task list.</p>
<?php else: ?>
<ul>
<?php foreach($task_list as $id => $task) : ?>
<li><?php echo $id + 1 . '. ' . $task; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<br>
<!-- part 3: the add form -->
<h2>Add Task</h2>
<form action="." method="post">
<input type="hidden" name="action" value="add"> <label>Task:</label> <input
type="text" name="newtask" id="newtask"><br> <label> </label> <input
type="submit" value="Add Task">
</form>
<br>
<!-- part 4: the delete form -->
<?php if (count($task_list) > 0) : ?>
<h2>Delete Task</h2>
<form action="." method="post">
<input type="hidden" name="action" value="delete"> <label>Task:</label>
<select name="taskid">
<?php foreach($task_list as $id => $task) : ?>
<option value="<?php echo $id; ?>">
<?php echo $task; ?>
</option>
<?php endforeach; ?>
</select> <br> <label> </label> <input type="submit"
value="Delete Task">
</form>
<?php endif; ?>
<br><input type="hidden" name="action" value="clear"><label> </label><input type="submit" value="Clear All">
</main>
<footer>
<p>Session ID: <?php echo session_id() ?>
</footer>
</body>
</html>

Put a form tag around the clear-all burton as well as you did for the other values.
Currently, the click doesn't have any action associated, so it will do nothing.

Related

How to set unset sequence in php

there are two inputs that should show interactions. Everything works, but when I want to refresh the page I add unset($_SESSION['one'], $_SESSION['second']) an error appears
Without unset($_SESSION['one'], $_SESSION['second'])
But you still need to reset everything when you refresh the page
search.php
<?php
session_start();
?>
<body>
<form action="new.php" method="post">
<div>
<input type="search" name='search1' list="doc" id="inp1">
<datalist id='doc'>
<option value="diclo">diclo</option>
<option value="keto">keto</option>
</datalist>
</div>
<div>
<input type="search" name='search2' list="doc2" id="inp2">
<datalist id='doc2'>
<option value="diclo">diclo</option>
<option value="keto">keto</option>
</datalist>
</div>
<div>
<button name='btn'>Save</button>
</div>
</form>
<?php
if(isset($_SESSION['error'])) { ?>
<div> <?= $_SESSION['error'] ?></div>
<?php }
unset($_SESSION['error']);
if(isset($_SESSION['one']) && isset($_SESSION['second'])) { ?>
<div>
<div>
<p><?= $_SESSION['one'] ?></p>
</div>
<p><?= $_SESSION['second'] ?></p>
<form action="del.php" method='post'>
<button name='btn1'>INTERACTION</button>
</form>
</div>
<?php }
?>
<?php
if (isset($_SESSION['yes'])) {
$getDrugInt = $model->getDrugInt($_SESSION['one'], $_SESSION['second']);
for ($i = 0; $i < count($getDrugInt); $i++) { ?>
<div>
<p> <?= $getDrugInt[$i]['profDescription']?> </p>
</div>
<?php }
}
unset($_SESSION['yes']);
?>
<?php
unset($_SESSION['one'], $_SESSION['second']); ?>
new.php
session_start();
$arr = array('diclo', 'keto');
if(isset($_POST['btn'])) {
unset($_SESSION['one'], $_SESSION['second']);
$inputone = $_POST['search1'];
$inputsecond = $_POST['search2'];
if(in_array($inputone, $arr) && in_array($inputsecond, $arr)) {
$_SESSION['one'] = $inputone;
$_SESSION['second'] = $inputsecond;
header('location: search.php');
} else {
$_SESSION['error'] = 'No results found';
unset($_SESSION['one'], $_SESSION['second']);
header('location: search.php');
}
}
del.php
session_start();
if(isset($_POST['btn1'])) {
$_SESSION['yes'] = true;
header('location: search.php');
} else {
$_SESSION['yes'] = false;
}
Thank you.

I'm struggling with integrating recaptcha in multipage form

Background info:
I have made a test form containing multiple pages. When recaptcha isn't intergrated I receive the info in my database. But when trying to integrate recaptcha (checkbox v2) it keeps failing and the info isn't sent to the database no more. I have tried to intergrate recaptcha on page2.php because it's the last page of the form the user has to fill in. I left my recaptcha keys in because it's just made as test.
Question:
How can I make it work? How can I integrate recaptch in a correct way?
Thanks!
The included pages are:
footer.php
<!-- Bootstrap Javascript-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>function goBack() {window.history.back();}</script>
<!-- recaptcha -->
<script src='https://www.google.com/recaptcha/api.js'></script>
</body>
</html>
header.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('config.php');
require_once('functions.php');
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Multi-Page Form</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<!-- recaptcha -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container">
</div>
</nav>
index.php
<?php include_once('header.php'); ?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">Questionnaire</h3>
<p> Beste user,</p>
<p> Please fill in form A or B</p>
<br>
<p>Form A</p>
<br>
<p>Form B</p>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
page1.php
<?php include_once('header.php');?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">Step 1/2</h3>
<form action="page2.php" method="post">
<?php
echo "<br>";
email('Email', 'Email', '<b>Email</b>', ' ');
echo "<br>";
text('Firstname', 'Firstname', '<b>Firstname</b>', ' ');
echo "<br>";
?>
<br>
<br>
<center>
<div class="btn-group">
<button class="btn btn-dark" onclick="goBack()">« Go back</button>
<button class="btn btn-dark" type="reset" value="reset">Reset</button>
<button class="btn btn-dark" type="submit">Continue »</button>
</div>
</center>
</form>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
page2.php
<?php
include_once('header.php');
// Store data from page 1 in SESSION
if ( ! empty( $_POST ) ) {
$_SESSION['Email'] = $_POST['Email'];
$_SESSION['Firstname'] = $_POST['Firstname'];
}
// recaptcha
$public_key = "6LdojMIUAAAAAH8uQNeM8lW5pmP_T_NlWlb5_-9S";
$private_key = "6LdojMIUAAAAALhEfrQFR3jExbPLubKjys6CZL_9";
$url = "https://www.google.com/recaptcha/api/siteverify";
?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">Step 2/2</h3>
<form action="page3.php" method="post">
<?php
// choices for checkbox
$options = array(
'No ' => 'No ',
'Neutral ' => 'Neutral ',
'Yes ' => 'Yes ',
);
// choices for checkbox2
$options2 = array(
'Internet ' => 'Internet ',
'Friends ' => 'Friends ',
'Work ' => 'Work ',
'Other' => 'Other' ,
);
echo "<br>";
checkbox2( 'Info_media', 'Info_media', '<b>How do you know this?</b>', $options2 );
echo "<br>";
text_non_required('Other', 'Other', 'Explain "Other"?', ' ');
echo "<br>";
checkbox( 'Question_1', 'Question_1', '<b>Do you agree with the answer?</b>', $options );
echo "<br>";
text('Remark', 'Remark', 'Do you have remarks?', ' ');
?>
<br>
<br>
<center>
<!-- recaptcha -->
<div class="g-recaptcha" data-sitekey="<?php print $public_key; ?>"></div>
<br>
<div class="btn-group">
<button class="btn btn-dark" onclick="goBack()">« Go back</button>
<button class="btn btn-dark" type="reset" value="reset">Reset</button>
<button class="btn btn-dark" name="submit_form" type="submit">Continue »</button>
<!-- recaptcha -->
<?php
/* Check if the form has been submitted */
if(array_key_exists('submit_form',$_POST))
{
$response_key = $_POST['g-recaptcha-response'];
$response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
/* json decode the response to an object */
$response = json_decode($response);
/* if success */
if($response->success == 1)
{
header("Location: http://localhost/recaptcha_test/page3.php");
}
else
{
echo "You are a robot.";
}
}
?>
</div>
</center>
</form>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
page3.php
<?php
include_once('header.php');
// Store data in session
if ( ! empty( $_POST ) ) {
$_SESSION['Info_media'] = $_POST['Info_media'];
$_SESSION['Other'] = $_POST['Other'];
$_SESSION['Question_1'] = $_POST['Question_1'];
$_SESSION['Remark'] = $_POST['Remark'];
}
?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">You are done.</h3>
<br>
<br>
<center>Thank you.</center>
<br>
<?php
whitelist_convert_send ();
?>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
functions.php
<?php
function __($text) {
return htmlspecialchars($text, ENT_COMPAT);
}
function checked($value, $array) {
if ( in_array( $value, $array ) ) {
echo 'checked="checked"';
}
}
function text( $name, $id, $label, $placeholder, $type = 'text' ) {?>
<div class="form-group">
<label for="<?php echo $id; ?>"><?php echo $label; ?></label>
<input type="<?php echo $type; ?>" required name="<?php echo $name; ?>" class="form-control"
id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
</div>
<?php }
function text_non_required( $name, $id, $label, $placeholder, $type = 'text' ) {?>
<div class="form-group">
<label for="<?php echo $id; ?>"><?php echo $label; ?></label>
<input type="<?php echo $type; ?>" name="<?php echo $name; ?>" class="form-control"
id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
</div>
<?php }
function email( $name, $id, $label, $placeholder, $type = 'email' ) {?>
<div class="form-group">
<label for="<?php echo $id; ?>"><?php echo $label; ?></label>
<input type="<?php echo $type; ?>" required name="<?php echo $name; ?>" class="form-control"
id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
</div>
<?php }
function checkbox( $name, $id, $label, $options = array() ) {?>
<div class="form-group">
<p><?php echo $label; ?></p>
<?php foreach ($options as $value => $title ) : ?>
<label class="checkbox-inline" for="<?php echo $id; ?>">
<input type="radio" required name="<?php echo $name; ?>[]" value="<?php echo $value; ?>" <?php isset($_SESSION[$id]) ? checked($value, $_SESSION[$id]) : ''; ?>>
<span class="checkbox-title"><?php echo $title; ?></span>
</label>
<?php endforeach; ?>
</div>
<?php }
function checkbox2 ($name, $id, $label, $options2 = array() ) {?>
<div class="form-group">
<p><?php echo $label; ?></p>
<?php foreach ($options2 as $value => $title) :
?>
<label class="checkbox-inline" for="<?php echo $id; ?>">
<input type="radio" required name="<?php echo $name; ?>[]"
value="<?php echo $value; ?>"
<?php isset($_SESSION[$id]) ? checked($value, $_SESSION[$id]) : ''; ?>
>
<span class="checkbox-title"><?php echo $title; ?></span>
</label>
<?php endforeach; ?>
</div>
<?php
}
function whitelist_convert_send () {
//globalise variables
global $Email;
global $Firstname;
global $Info_media;
global $Other;
global $Question_1;
global $Remark;
global $MCQ_0;
global $MCQ_1;
// Whitelist
$Email = $_SESSION['Email'];
$Firstname = $_SESSION['Firstname'];
$Info_media = $_SESSION['Info_media'];
$Other = $_SESSION['Other'];
$Question_1 = $_SESSION['Question_1'];
$Remark = $_SESSION['Remark'];
// arrays to value in string for performing statistics
foreach ($Info_media as $value) {
$MCQ_0 = $value;}
foreach ($Question_1 as $value) {
$MCQ_1 = $value;}
// Connectie database (naam server, gebruikersnaam, wachtwoord, naam database)
$conn = new mysqli('localhost', 'root', '', 'Wolf');
/*Testing databaseconnection
if ($conn){
echo "we are connected";}
else {
die ('database connection failed');} */
if (!$conn){ die ('database connection failed' . msqli_error ());}
$stmt = $conn->prepare("INSERT INTO test_database (Email, Firstname, Info_media, Other, Question_1, Remark) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $Email, $Firstname, $MCQ_0, $Other, $MCQ_1, $Remark);
// Execute
$insert = $stmt->execute();
// Einde sessie
session_destroy();
}
You probably misunderstood how recaptcha is working.
You integrate the recaptcha code (js + div) in your form
On the result page you check if the captcha check was sucessful (php)
Currently you are doing both things in page2.php. When this page is loading, it checks if recaptcha was successful, but the recaptcha was not even included and the user didn't had the opportunity to solve it yet :-)
So you should integrate it in page1 and check it in page2.
page1.php
Integrate the recaptcha div in your form
<form action="page2.php" method="post">
<div class="g-recaptcha" data-sitekey="6LdojMIUAAAAAH8uQNeM8lW5pmP_T_NlWlb5_-9S"></div>
<?php
echo "<br>";
email('Email', 'Email', '<b>Email</b>', ' ');
...
ofc you can integrate the site key with php too (like you have done it on page2.php) or change the position inside the form
page2.php
Remove the recaptcha div from this page.
The recaptcha success check should be somewhere in the beginning of this page. You should render the whole form only when $response->success == 1 succeed (see the attached code). This probably requires some additional restructuring of page2.php
<?php
//recaptcha check
$response_key = "";
//get submitted recaptcha "user response" from last page
if(array_key_exists('g-recaptcha-response',$_POST)){
$response_key = $_POST['g-recaptcha-response'];
}
$response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
/* json decode the response to an object */
$response = json_decode($response);
if($response->success == 1){
//render form from page 2
?>
<form action="page3.php" method="post">
...
<?php
}
else{
echo "You are a robot.";
//
}
?>
As an alternative you could integrate recaptcha in page2.php and check the result in page3.php - it just depends in which step you want the recaptcha checkbox

Add items to the array through a form using Php

I need to add items to my existing array through a form on the site i made.
Basically once i submit something on my form it needs to add the item to the array, i can only use php and html for this problem.
i tried array_push but it doesnt give me what i need because it doesnt use the form
<form action="" method="post">
<input type="text" name="boodschappen"><br><br>
<input type="submit" value="Verstuur">
</form>
<ul>
<?php
$boodschappen = ["aardappelen","aardbeien","3 pakken melk","yoghurt"];
foreach ($boodschappen as $boodschap) {
echo "<li>".$boodschap."</li>";
}
?>
</ul>
</body>
</html>
<?php
$post = $_POST;
$boodschappen = ["aardappelen","aardbeien","3 pakken melk","yoghurt"];
$result = array_merge($post, $boodschappen);
foreach ($result as $item) {
echo "<li>".$item."</li>";
}
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
echo "<pre>";
print_r($a);
?>
If I understand your code correctly, you'll need some sort of persistent storage to store all the previous submission in the listing. A database would be ideal for long term storage. Session would be the minimal requirement:
<?php
session_start();
if (!isset($_SESSION['past_submission']) || !is_array($_SESSION['past_submission'])) {
$_SESSION['past_submission'] = [];
}
if (!empty($_POST) && isset($_POST['boodschappen']) && !empty(trim($_POST['boodschappen']))) {
array_push($_SESSION['past_submission'], $_POST['boodschappen']);
}
$past_submission = $_SESSION['past_submission'];
?>
<html>
<body>
<form action="" method="post">
<input type="text" name="boodschappen"><br><br>
<input type="button" value="Verstuur">
</form>
<ul>
<?php
$boodschappen = ["aardappelen","aardbeien","3 pakken melk","yoghurt"];
array_push($boodschappen, ...$past_submission);
foreach ($boodschappen as $boodschap) {
echo "<li>".$boodschap."</li>";
}
?>
</ul>
</body>
</html>
Please note that Session only works for the visitor session alone. The data is not available to other visitors or you.
As described before, you'd probably need a MariaDB / MySQL / PostgreSQL to store the submissions for long term. You'd probably need to use PDO to insert data into, or retrieve data from database.
Perhaps like this?
<html>
<head><title></title></head>
<body>
<form action="" method="post">
<input type="text" name="boodschappen"><br><br>
<input type="submit" value="Verstuur">
</form>
<ul>
<?php
$boodschappen = ["aardappelen","aardbeien","3 pakken melk","yoghurt"];
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['boodschappen'] ) ){
$boodschappen=array_merge( $boodschappen, explode(' ', $_POST['boodschappen'] ) );
}
foreach( $boodschappen as $boodschap ) {
echo "<li>".$boodschap."</li>";
}
?>
</ul>
</body>
</html>
To update the array with persistance you can use a session variable like so:
<?php
session_start();
if( !isset( $_SESSION['boodschappen'] ) ){
$_SESSION['boodschappen']=["aardappelen","aardbeien","3 pakken melk","yoghurt"];
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="post">
<input type="text" name="boodschappen"><br><br>
<input type="submit" value="Verstuur">
</form>
<ul>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['boodschappen'] ) ){
$items=explode(' ', $_POST['boodschappen'] );
foreach( $items as $item )$_SESSION['boodschappen'][]=$item;
}
foreach( $_SESSION['boodschappen'] as $boodschap ) {
echo "<li>".$boodschap."</li>";
}
?>
</ul>
</body>
</html>
<?php session_start(); ?>
<ul>
<?php
if (!empty($_POST['submit'])) {
$_SESSION['boodschappen'][] = $_POST['boodschap'];
foreach ($_SESSION['boodschappen'] as $boodschap) {
echo "<li>".$boodschap."</li>";
}
} else {
$_SESSION['boodschappen'] = [];
}
?>
</ul>
<form action="" method="post">
<input type="text" name="boodschap"><br>
<input type="submit" name="submit" value="Verstuur">
</form>

Wordpress Custom PHP failing at wpdb object

I am trying to create a form on wordpress that automatically updates a custom table in the database. The form works with the "POST" method and calls the PHP file fine, and any code (such as echos) I enter at the beginning work fine. The problem is every time I try and use the wpdb object, the screen is just white and the code stops. It won't run anything including or past where I call wpdb. I have tried both using insert and get results and neither is working. Also, I am getting absolutely no errors in the console output even though I turned debugging on and everything.
This is my php file (which has a permission value of 755):
<?php
global $wpdb;
error_reporting(E_ALL);
echo "New Plant has been submitted.\n";
$plantname = $_POST["name"];
echo "Before";
$myrows = $wpdb->get_results( "SELECT * FROM wp_users" );
exit( var_dump( $wpdb->last_query ) );
echo " After: " . $myrows;
$wpdb->insert('Plants',array('PlantName' => $plantname),array('%s'));
echo $plantname . " has been submitted.";
?>
</body>
</html>
Also, this is my form:
<form action="cgi-bin/add_plant.php" method="post">
Plant Name: <input name="name" type="text" />
Lowest Ideal Temperature: <input name="IdealTempLow" type="text" />
Highest Ideal Temperature: <input name="IdealTempHigh" type="text" />
Lowest Ideal pH: <input name="IdealpHLow" type="text" />
Highest Ideal pH: <input name="IdealpHHigh" type="text" />
Lowest Ideal Humidity Level: <input name="IdealHumLow" type="text" />
Highest Ideal Humidity Level: <input name="IdealHumHigh" type="text" />
Lowest Ideal Moisture Level: <input name="IdealMoistLow" type="text" />
Highest Ideal Moisture Level: <input name="IdealMoistHigh" type="text" />
<input type="submit" />
</form>
By the way, I know I need to sanitize my code, but for right now I just want to be able to get it to work in the first place. I know that nothing is getting added because I logged in to PHPMyAdmin and there is nothing in the table. I also tried getting results from the standard wp tables, but that failed as well.
Edit 1
I have moved everything into a custom template file. I had gotten it working with the separate php file, but I moved it so that I could do form validation and everything all without switching pages. However, now I am having the same error. I had used "require_once" to include wp-load.php in the original and it worked, however now wpdb is still failing and I can't figure out how to include wp-load without it also failing. Originally loading up the page works: I can submit the form however on submit the page fails.
<?php
require_once(ABSPATH . '/wp-config.php');
require_once(ABSPATH . '/wp-load.php');
?>
<?php global $asteria;?>
<?php
get_header();
?>
<?php global $wpdb;?>
<?php
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function selfURL()
{
$ret = substr(strtolower($_SERVER['SERVER_PROTOCOL']),0,strpos( strtolower($_SERVER['SERVER_PROTOCOL' ]), "/") );
$ret .= ( empty($_SERVER['HTTPS']) ? NULL : ( ($_SERVER['HTTPS'] == "on") ? "s" : NULL) );
$ret .= "://" . $_SERVER['SERVER_NAME'];
$ret .= ( $_SERVER['SERVER_PORT'] == 80 ? "" : ":".$_SERVER['SERVER_PORT'] );
$ret .= $_SERVER['REQUEST_URI'];
return $ret;
}
function submitPlant($a, $b, $c, $d, $e, $f, $g, $h, $i)
{
$wpdb->show_errors();
// $wpdb->replace('Plants',
// array(
// 'PlantName' => $a,
// 'IdealTempLow' => $b,
// 'IdealTempHigh' => $c,
// 'IdealPHLow' => $d,
// 'IdealPHHigh' => $e,
// 'IdealHumidityLow' => $f,
// 'IdealHumidityHigh' => $g,
// 'IdealMoistureLow' => $h,
// 'IdealMoistureHigh' => $i
// ),
// array(
// '%s',
// '%f',
// '%f',
// '%f',
// '%f',
// '%f',
// '%f',
// '%f',
// '%f'
// )
// );
// $a = $wpdb->insert_id;
// if ($a == false) {
// $SubmitMsg = "Plant entry failed. Please contact system admin.";
// echo "Error: " . $wpdb->print_error();
// } else {
$SubmitMsg = "New Plant has been submitted.";
// }
return $SubmitMsg;
}
... Validation Functions...
?>
<?php
$PlantName = $IdealTempLow = $IdealTempHigh = $IdealpHLow = $IdealpHHigh = $IdealHumLow = $IdealHumHigh = $IdealMoistLow = $IdealMoistHigh = "";
$NameErr = $LTempErr = $HTempErr = $LpHErr = $HpHErr = $LHumErr = $HHumErr = $LMoistErr = $HMoistErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$SubmitMsg = "";
...Form Validation...
if (($NameErr == "") && ($LTempErr == "") && ($HTempErr == "") && ($LpHErr == "") && ($HpHErr == "") && ($LHumErr == "") && ($HHumErr == "") && ($LMoistErr == "") && ($HMoistErr == ""))
{
$SubmitMsg = submitPlant($PlantName, $IdealTempLow, $IdealTempHigh, $IdealpHLow, $IdealpHHigh, $IdealHumLow, $IdealHumHigh, $IdealMoistLow, $IdealMoistHigh);
}
}
?>
<!--Content-->
<div class="fixed_site">
<div class="fixed_wrap singlefx">
<?php if(($asteria['page_type_id']) == '1'){ ?>
<div class="page_tt">
<div class="center"><h1 class="postitle"><?php the_title(); ?></h1></div>
</div>
<?php } ?>
<div id="content">
<div class="center">
<div class="single_wrap no_sidebar">
<div class="single_post">
<?php if(have_posts()): ?>
<?php while(have_posts()): ?><?php the_post(); ?>
<div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
<?php if ( is_user_logged_in() || is_admin() ) { ?><div class="edit_wrap"><i title="<?php _e('Edit This','asteria'); ?>" class="fa-edit"></i></div><?php } ?>
<div class="single_post_content">
<?php if(($asteria['page_type_id']) == '2'){ ?><h1 class="postitle"><?php the_title(); ?></h1><?php } ?>
<div class="thn_post_wrap"><?php the_content(); ?> </div>
<div style="clear:both"></div>
<div class="thn_post_wrap"><?php wp_link_pages('<p class="pages"><strong>'.__('Pages:').'</strong> ', '</p>', 'number'); ?></div>
</div>
</div>
<?php endwhile ?>
</div>
<?php endif ?>
<span style="color:blue"><?php echo $SubmitMsg;?></span>
<form action="<?php echo selfURL(); ?>" method="POST">
Plant Name: <input name="PlantName" type="text" value="<?php echo $PlantName;?>"/><span style="color:red"> * <?php echo $NameErr;?></span>
</br><div height="5"> </div>
Lowest Ideal Temperature: <input name="IdealTempLow" type="text" value="<?php echo $IdealTempLow;?>"/><span style="color:red"> * <?php echo $LTempErr;?></span>
</br><div height="5"> </div>
Highest Ideal Temperature: <input name="IdealTempHigh" type="text" value="<?php echo $IdealTempHigh;?>"/><span style="color:red"> * <?php echo $HTempErr;?></span>
</br><div height="5"> </div>
Lowest Ideal pH: <input name="IdealpHLow" type="text" value="<?php echo $IdealpHLow;?>"/><span style="color:red"> * <?php echo $LpHErr;?></span>
</br><div height="5"> </div>
Highest Ideal pH: <input name="IdealpHHigh" type="text" value="<?php echo $IdealpHHigh;?>"/><span style="color:red"> * <?php echo $HpHErr;?></span>
</br><div height="5"> </div>
Lowest Ideal Humidity Level: <input name="IdealHumLow" type="text" value="<?php echo $IdealHumLow;?>"/><span style="color:red"> * <?php echo $LHumErr;?></span>
</br><div height="5"> </div>
Highest Ideal Humidity Level: <input name="IdealHumHigh" type="text" value="<?php echo $IdealHumHigh;?>"/><span style="color:red"> * <?php echo $HHumErr;?></span>
</br><div height="5"> </div>
Lowest Ideal Moisture Level: <input name="IdealMoistLow" type="text" value="<?php echo $IdealMoistLow;?>"/><span style="color:red"> * <?php echo $LMoistErr;?></span>
</br><div height="5"> </div>
Highest Ideal Moisture Level: <input name="IdealMoistHigh" type="text" value="<?php echo $IdealMoistHigh;?>"/><span style="color:red"> * <?php echo $HMoistErr;?></span>
</br><div height="5"> </div>
<input type="submit" name="submitted"/>
</form>
</div>
<!--PAGE END-->
</div>
</div>
</div>
</div>
<?php get_footer(); ?>

php code doesn`t work on form submit on ie (but works fine on chrome, ff)

I made a login/register page. It works fine on chrome and firefox, but doesnt work on internet explorer (8, 9). After clicking any submit button ie redirect to index page. I have the same problem on another page based on this code.
Here is html code:
<?php
$log_in=false;
$token_sent=0;
$errors1 = array();
$missing1 = array();
$errors = array();
$missing = array();
if(isset($_POST['submit'])){
$expected = array('login', 'email', 'pwd');
$required = array('login', 'email', 'pwd');
require('./rejestracja.inc.php');
}
if ($token_sent) {
header('Location: (..) ');
exit;
}
if(isset($_POST['submit1'])) {
$expected=array('login1','pwd1');
$required=array('login1','pwd1');
require('./login.inc.php');
if($log_in) {
if (isset($_SESSION['name']) && !empty($_SESSION['name'])) {
unset($_SESSION['login1']);
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-86400, '/');
}
session_destroy();
}
if (isset($_POST['login1'])) {
session_start();
$_SESSION['name'] = $login1 ;
}
header('Location: http:// (...) ');
exit;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<meta name="description" content="">
<meta name="copyright" content="Copyright (c) 2012 k">
<meta name="author" content="">
<link href="style.css" rel="stylesheet" type="text/css" media="screen">
<link href="login.css" rel="stylesheet" type="text/css" media="screen">
</head>
<body>
<div id="wrap">
<?php include('./login_menu.inc.php');?>
<div id="header">
<h1></h1>
</div>
<?php include('./fb.inc.php');?>
<?php include('./menu.inc.php');?>
<?php include('./w_budowie.inc.php');?>
<div id='left'>
<div id='info'>
<h1 class='title'>LOGIN</h1> <br/>
<form class='form' name="login1" action=" " method="post">
<?php if ($missing1) { ?>
<span class="warning">...</span><br/>
<?php } ?>
<?php if(isset($errors1['wrong'])){ ?>
<span class="warning">...</span><br/>
<?php } ?>
<?php if(isset($errors1['not_verified'])){ ?>
<span class="warning">...</span><br/>
<?php } ?>
<label for="login1">Login: </label>
<input type="text" name="login1"
<?php if ($missing1 || $errors1) {
echo 'value="' . htmlentities($login1, ENT_COMPAT, 'UTF-8') . '"';
} ?>
/>
<br/>
<label for="pwd1">Password:</label>
<input type="password" name="pwd1" /> <br/>
<br/>
<span class='submit'><input name="submit1" type="submit" value="LOGIN" /></span>
</form>
<br/>
</div>
</div>
<div id='right'>
<div id='info'>
<h1 class='title'>REGISTRATION</h1> <br/>
<form class='form' name="register" action=" " method="post">
<label for="login">Login: </label>
<input type="text" name="login"
<?php if ($missing || $errors) {
echo 'value="' . htmlentities($login, ENT_COMPAT, 'UTF-8') . '"';
} ?>
/>
<?php if ($missing && in_array('login', $missing)) { ?>
<span class="warning">...</span>
<?php
} elseif(isset($errors['login_mini'])){ ?>
<span class="warning">...</span>
<?php
} elseif(isset($errors['login_maxi'])){ ?>
<span class="warning">...</span>
<?php
} elseif(isset($errors['login'])){ ?>
<span class="warning"> A-Z, a-z, 0-9.</span>
<?php
} elseif(isset($errors['login_exist'])){ ?>
<span class="warning">...</span>
<?php } ?>
<br/>
<label for="email">Email: </label>
<input type="text" name="email"
<?php if ($missing || $errors) {
echo 'value="' . htmlentities($email, ENT_COMPAT, 'UTF-8') . '"';
} ?>
/>
<?php if ($missing && in_array('email', $missing)) { ?>
<span class="warning">...</span>
<?php } elseif(isset($errors['email'])){ ?>
<span class="warning">...</span>
<?php } elseif(isset($errors['email_exist'])){ ?>
<span class="warning">...</span>
<?php } ?>
<br/>
<label for="pwd">Password:</label>
<input type="password" name="pwd" />
<?php if ($missing && in_array('pwd', $missing)) { ?>
<span class="warning">...</span>
<?php
} elseif(isset($errors['pwd_mini'])){ ?>
<span class="warning">...</span>
<?php
} elseif(isset($errors['pwd_maxi'])){ ?>
<span class="warning">...</span>
<?php } ?>
<br/>
<span class='submit'><input type="submit" name="submit" value="REGISTER" /></span>
</form>
<br/>
</div>
</div>
<?php include('./footer.inc.php'); ?>
</div>
</body>
</html>
Here is 'login.inc.php' code:
<?php
$login1 = "";
$pwd1 = "";
$salt = "(...)";
/*---------------con------------------------*/
include('./sql_connect.inc.php');
/*---------------------------------------------*/
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (empty($temp) && in_array($key, $required)) {
$missing1[] = $key;
} elseif (in_array($key, $expected)) {
${$key} = $temp;
}
}
if(!$missing1){
$login1 = mysql_real_escape_string($login1);
$hash = $salt . $pwd1;
for ( $i = 0; $i < 100; $i ++ ){
$hash = hash('sha256', $hash);
}
/*---------------COMPARE-----------------*/
$result = mysql_query("SELECT user_nick='$login1' FROM users WHERE user_password='$hash'") or die('Sorry, we could not count the number of results: ' . mysql_error());
if($result){
if(mysql_result($result, 0)){
/*-------IS ACTIVATED?------------------------------*/
$verified = mysql_query("SELECT user_verified='yes' FROM users WHERE user_nick='$login1'");
if($verified){
if(mysql_result($verified, 0)){
$log_in=true;
}else{
$errors1['not_verified'] = true;
}
}
}else{
$errors1['wrong'] = true;
}
}
}
mysql_close($con);
?>
Are you really using <form class='form' name="register" action=" " method="post"> ?
It could come from here, try with action="#"
There won't have any cross browser problem with PHP, it comes from HTML (generated or not)

Categories