Add items to the array through a form using Php - 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>

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.

my php diff checker code works fine on a single word but not in the sentences

I am writing a php program to compare two strings of equal length and highlight the difference.
My code works fine on single words. But when I enter a sentence to compare, then it prints out the html parts of my code in unusual manner.
<form action="#" method="post">
<input type="text" name="first"><br>
<input type="text" name="second"><br>
<input type="submit" name="">
</form>
<?php
$var1=$_POST['first'];
$var2=$_POST['second'];
echo $var1;
echo "<br>";
$var3=$var2;
$temp =$var2;
$diff_char1='';
for ($i=0;$i<strlen($var1);$i++) {
// code...
if ($var1[$i]==$var2[$i]) {
// code...
// echo "true<br>";
}
else{
// code...
$diff_char = substr($var2, $i,1);
//echo"<br>".$diff_char;
$diff_char1='<span style="background:red">'.$diff_char.'</span>';
//echo $diff_char1.'<br>';
$temp= str_replace($diff_char,$diff_char1,$temp);
//echo $temp."<br>";
}
}
echo $temp;
?>
Rather than modifying the content as you process the string you could simply build a new string that reflects the differences and present that at the end to show the differences - perhaps like this:
<?php
error_reporting( E_ALL );
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<style>
output span{color:red}
</style>
</head>
<body>
<form method="post">
<input type="text" name="first" />
<input type="text" name="second" />
<input type="submit" />
</form>
<output>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['first'],
$_POST['second']
)){
$first=$_POST['first'];
$second=$_POST['second'];
$message='';
if( substr_compare( $first, $second, 0 )===0 ){
$message='Strings are identical';
} elseif( strlen( $first )!=strlen( $second ) ){
$message='Strings are of different lengths';
}else{
for( $i=0; $i < strlen( $first ); $i++ ){
$chr1=substr($first,$i,1);
$chr2=substr($second,$i,1);
if( $chr1!==$chr2 )$message.=sprintf('<span>%s</span>',$chr2);
else $message.=$chr1;
}
}
echo $message;
}
?>
</output>
</body>
</html>

What am I doing wrong with this phone SESSION I'm trying to print to screen?

I am testing a SESSION where the three prior pages prints to the last page. But I'm have trouble getting it to work. Everything goes well until the last page. Here is the code:
<?php
session_start();
if (isset($_POST['submit'])) {
$_SESSION['name'] = $_POST ['name'];
$_SESSION['email'] = $_POST ['email'];
$_SESSION['age'] = $_POST ['age'];
echo $_SESSION['name'];
echo $_SESSION['email'];
echo $_SESSION['age'];
}
?>
I'm getting a blank or a index error for the session variable. Can anyone help with the correct way to print user inputted session data?
These are the 1st, 2nd and 3rd pages:
<html>
<head>
<title>phpsession</title>
</head>
<body>
<form method="POST" action="test_2_page_1.php">
<input type="text" name="name" placeholder="enter name"></input>
<input type="submit"> next</input>
</form>
<?php
//Set session variables
if (isset($_POST['submit'])) {
$_SESSION['name'] = $_POST ['name'];
}
?>
</body>
</html>
<?php
session_start();
if (isset($_POST['submit'])) {
$_SESSION['name'] = $_POST ['name'];
$_SESSION['email'] = $_POST ['email'];
}
?>
<html>
<head>
<title>phpsession</title>
</head>
<body>
<form method="POST" action="test_2_page_2.php">
<input type="text" name="email" placeholder="enter email"></input>
<input type="submit"> next</input>
</form>
<?php
// Set session variables
?>
</body>
</html>
<?php
session_start();
if (isset($_POST['submit'])) {
$_SESSION['name'] = $_POST ['name'];
$_SESSION['email'] = $_POST ['email'];
$_SESSION['age'] = $_POST ['age'];
}
?>
<html>
<head>
<title>phpsession</title>
</head>
<body>
<form method="POST" action="post_test.php">
<input type="text" name="age" placeholder="enter age"></input>
<input type="submit"> next</input>
</form>
<?php
// Set session variables
?>
</body>
</html>
The input element is self-closing in that you do not need </input> - rather the tag is simply closed using />
To display Next as the submit button you would use the value attribute - ie: <input type='submit' value='Next' />
Once the session variable is assigned you do not need to keep trying to set it and will encounter errors if the variable is not available in the POST array - so use isset to test prior to creating a variable
<?php
session_start();
if ( isset( $_POST['submit'], $_POST['name'] ) ) {
$_SESSION['name'] = $_POST['name'];
}
?>
<html>
<head>
<title>phpsession</title>
</head>
<body>
<form method="POST" action="test_2_page_1.php">
<input type="text" name="name" placeholder="enter name" />
<input type="submit" name='submit' value='Next'>
</form>
</body>
</html>
<?php
session_start();
if ( isset( $_POST['submit'], $_POST['email'] ) ) {
$_SESSION['email'] = $_POST['email'];
}
?>
<html>
<head>
<title>phpsession</title>
</head>
<body>
<form method="POST" action="test_2_page_2.php">
<input type="text" name="email" placeholder="enter email" />
<input type="submit" name='submit' value='Next'>
</form>
</body>
</html>
<?php
session_start();
if( isset( $_POST['submit'],$_POST['age'] ) ) {
$_SESSION['age'] = $_POST['age'];
}
?>
<html>
<head>
<title>phpsession</title>
</head>
<body>
<form method="POST" action="post_test.php">
<input type="text" name="age" placeholder="enter age" />
<input type="submit" name='submit' value='Next'>
</form>
</body>
</html>
To further help you solve your issues I quickly put together a single page demo of getting and setting the session variables based upon form submissions.. hope it'll help
<?php
session_start();
#https://stackoverflow.com/questions/54194496/what-am-i-doing-wrong-with-this-phone-session-im-trying-to-print-to-screen/54194890?noredirect=1#comment95217192_54194890
if( !empty( $_GET['reset'] ) ){
unset( $_SESSION['name'] );
unset( $_SESSION['email'] );
unset( $_SESSION['age'] );
header( sprintf('Location: %s', $_SERVER['SCRIPT_NAME'] ) );
}
/*
as each form only submits two values ( submit being one ) we can
simply remove it from the POST array and use the remaining field/value
to generate the session variables using simple array techniques
The below could easily be replaced with pre-defined variables, such as:
if( isset( $_POST['name'] ) )$_SESSION['name']=$_POST['name']; etc
*/
if ( isset( $_POST['submit'] ) ) {
/* remove the submit button & value from the array */
unset( $_POST['submit'] );
/* there will now be one item, with index = 0 */
$keys=array_keys( $_POST );
$values=array_values( $_POST );
/* set the session variable */
$_SESSION[ $keys[0] ]=$values[0];
}
?>
<html>
<head>
<title>phpsession</title>
</head>
<body>
<form method='POST'>
<?php
if( empty( $_SESSION['name'] ) ){
echo "<input type='text' name='name' placeholder='enter name' />";
}
if( !empty( $_SESSION['name'] ) && empty( $_SESSION['email'] ) ){
echo "<input type='text' name='email' placeholder='enter email address' />";
}
if( !empty( $_SESSION['name'] ) && !empty( $_SESSION['email'] ) && empty( $_SESSION['age'] ) ){
echo "<input type='text' name='age' placeholder='enter your age' />";
}
if( empty( $_SESSION['age'] ) ){
echo "<input type='submit' name='submit' value='Next'>";
} else {
if( empty( $_POST['finish'] ) ) echo "<input type='submit' name='finish' value='Finish'>";
}
if( isset( $_POST['finish'] ) ){
/*
Once the user has completed each form, send them off to their final destination?
or do something else....
*/
printf(
'Do some interesting stuff now ....
<pre>%s</pre>Reset',
print_r( $_SESSION, true )
);
}
?>
</form>
</body>
</html>
You have no input element in your HTML with the name submit so the following part of your PHP code will always evaluate to false:
if (isset($_POST['submit'])) {
Change the submit button in your HTML to the following and the line above will evaluate to true when the form is posted:
<input name="submit" type="submit"> next</input>

Clear Cookies and Session Data in 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.

php Post txt file content to textarea on another page

I am writing an app to delete and modify files in a directory. I deleted files successfully. And now I want to modify and update content to the same file using textarea on another page.
<form enctype="multipart/form-data" method="post">
<div class="span7">
<table>
<thead>
<tr>
<th> List of files </th>
<tr>
</thead>
<?php
$files = glob("UploadFile/"."*");
foreach($files as $txt)
{
if(mime_content_type($txt)=="text/plain")
{
$txtname = basename($txt);
echo "<tr><td><input type='radio' name='txt' value='$txtname'/> ".$txtname."</td></tr>";
}
}
?>
</table>
</div>
<div class="span8">
<button type="submit" name="submit" value="Edit">Edit</button>
<button type="submit" name="submit" value="Delete">Delete</button>
</div>
<?php
global $txtname;
$val = $_POST["submit"];
$txtname = $_POST["txt"];
if($val=="Delete")
unlink("UploadFile/".$txtname);
else if($val=="Edit")
{
$content=file_get_contents("UploadFile/".$txtname);
header('Location:/edit.php');
/* send content to this 'edit.php' page */
}
?>
</form>
And the edit.php page, i simply checked if the code is working. It works fine.
<?php
if($_POST['append'])
{
$file_open = fopen("UploadFile/file.txt","a+");
fwrite($file_open, $_POST['append']);
fclose($file_open);
}
?>
<form enctype="multipart/form-data" action="<?=$PHP_SELF?>" method="post">
<textarea name="append" value="">
<?php
echo $content;
$datalines = file ("UploadFile/file.txt");
foreach ($datalines as $zz)
{
echo $zz;
}
?>
</textarea>
<button type="submit" name="submit" value="save"> Save </button>
How do I get the contents of the file to textarea for modifying it.Update: I want to save changes to the same file. Thank you
<?php
if(isset($_POST['text']))
{
file_put_contents("file.txt",$_POST['text']);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
$text = file_get_contents("file.txt");
?>
<form method="post">
<textarea name="text"><?=$text?></textarea>
<input type="submit">
</form>
with listing
if(isset($_POST['text']))
{
file_put_contents("UploadFile/".basename($_POST['file']),$_POST['text']);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
if(isset($_GET['file']))
{
$text = file_get_contents("UploadFile/".basename($_GET['file']));
?>
<form method="post">
<input type="hidden" name="file" value="<?=urlencode($_GET['file'])?>">
<textarea name="text"><?=$text?></textarea>
<input type="submit">
</form>
<?
} else {
$files = glob("UploadFile/*");
foreach ($files as $f)
{
$f=basename($f);
?><?=htmlspecialchars($f)?><br><?
}
}

Categories