trying to create a chat and keep getting Undefined index i've tried adding ? $_POST['chat'] : null; but doesn't work
Notice: Undefined index: chat in /Applications/MAMP/htdocs/chat/chat.php on line 8
Line 8:
$sent = $_POST['chat'];
the variable is used here:
if (isset($_POST['chat'])) {
if (!empty($sent)) {
fwrite($myfile, $first.': '.$txt.'=');
fclose($myfile);
} else if (empty($sent)) {
if(isset($_POST['chat'])){
echo 'Cant send an empty message','<br />';
}
}
}
HTML:
<body>
<iframe id='reload' src='refresh.php'>
<fieldset class="field">
<div id="list"><p><?php
$filename = 'chat.txt';
$handle = fopen($filename, 'r');
$detain = fread($handle, filesize($filename));
$chat_array = explode('=', $detain);
foreach($chat_array as $chat) {
echo $chat.'<br />';
}
?></p></div>
</fieldset>
</iframe>
<form action="chat.php" method="POST">
<input type="text" name="chat" class="textbox">
<input type="submit" value="Send" class="button">
</form>
</body>
Variables:
$sent = $_POST['chat'];
$myfile = fopen("chat.txt", 'a') or die("Unable to open file!");
$txt = ($sent."\n");
$first = getuserfield('username');
$active = ($first.":".$ip_addr);
$activef = fopen("ip-user.txt", 'a');
$myFile = "domains/domain_list.txt";
Edit: This is not a duplicate because this is for a very specific piece of code, i've also already used empty and I would not like to ignore the problem because it is a possible cause of another problem.
Thank you.
Use this code :
<?php
$sent = '';
if(isset($_POST['chat']))
{
$sent = $_POST['chat'];
if (!empty($sent))
{
$txt = ($sent."\n");
fwrite($myfile, $first.': '.$txt.'=');
fclose($myfile);
}
else
{
echo 'Cant send an empty message','<br />';
}
}
?>
You said you tried a ternary conditional, but didn't post an example of what you tried. It should look like this:
$sent = isset($_POST['chat']) ? $_POST['chat'] : null;
In PHP 7.0 or higher, you can simplify this expression with the null coalesce operator:
$sent = $_POST['chat'] ?? null;
did you submit the form ?
PHP:
if (isset($_POST['chat'])) {
if (!empty($sent)) {
fwrite($myfile, $first.': '.$txt.'=');
fclose($myfile);
} else if (empty($sent)) {
if(isset($_POST['chat'])){
echo 'Cant send an empty message','<br />';
}
}
}
HTML:
<form action="" method="POST">
<input type="text" name="chat">
<input type="submit" name="submit">
</form>
Do something like $sent = isset($_POST['chat']) ? $_POST['chat'] : '';
btw.: There is much redundance in you code.
if (isset($_POST['chat'])) {
if (!empty($sent)) {
fwrite($myfile, $first.': '.$txt.'=');
fclose($myfile);
} else {
echo 'Cant send an empty message','<br />';
}
}
If you don't want to write an isset() condition every time, you could define a short function:
function get(&$var, $default = null)
{
return isset($var) ? $var : $default;
}
Use it like that:
$sent = get($_POST['chat'], '');
or just
$sent = get($_POST['chat']);
Related
Can someone help me to figure out how to replace a defined string value with user input value? I am quite new in PHP programming and could not find an answer. I saw a lot of ways to replace string on the internet by using built-in functions or in arrays, but I could not find out the right answer to my question.
Here is my code:
$text = "Not found";
if ( isset($_GET['user'])) {
$user_input = $_GET['user'];
}
// from here I I tried to replace the value $text to user input, but it does not work.
$raw = TRUE;
$spec_char = "";
if ($raw) {
$raw = htmlentities($text);
echo "<p style='font-style:bold;'> PIN " . $raw . "</p>"; *# displays "Not found"*
} elseif (!$raw == TRUE ) {
$spec_char = htmlspecialchars($user_input);
echo "<p>PIN $spec_char </p>";
}
<form>
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
I appreciate your answers.
Lets run over your code, line by line.
// Set a default value for $text
$text = "Not found";
// Check if a value has been set...
if (isset($_GET['user'])) {
// But then create a new var with that value.
// Why? Are you going to change it?
$user_input = $_GET['user'];
}
// Define a few vars
$raw = TRUE;
$spec_char = "";
// This next line is useless - Why? Because $raw is always true.
// A better test would be to check for $user_input or do the
// isset() check here instead.
if ($raw) {
// Basic sanity check, but $text is always going to be
// "Not found" - as you have never changed it.
$raw = htmlentities($text);
// render some HTML - but as you said, always going to display
// "Not found"
echo "<p style='font-style:bold;'> PIN " . $raw . "</p>";
} elseif (!$raw == TRUE ) {
// This code is never reached.
$spec_char = htmlspecialchars($user_input);
echo "<p>PIN $spec_char </p>";
}
// I have no idea what this HTML is for really.
// Guessing this is your "input" values.
<form>
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
Just a guess I think you really wanted to do something more like this:
<?php
// Check if a value has been posted...
if (isset($_POST['user'])) {
// render some HTML
echo '<p style="font-style:bold"> PIN '.htmlspecialchars($_POST['user']).'</p>';
}
?>
<form method="post" action="?">
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
I have a checkbox that I'm looking to update a contacts details with. At the moment it's not updating the contact in Send in Blue... I don't think that's the problem though.
There's 3 issues I'm not sure I'm doing correctly:
Checking if the data has been sent.
Checking the field data that already uses square brackets.
Checking to see if the checkbox is checked or not.
Here's my php:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
global $SendInBlue;
if(isset($_POST['data[newsletter_sub]']) == "on") {
$data_in['ONETIME_NEWSLETTER'] = true;
$data_in['PROMOS'] = true;
$data_in['SUB_NEWSLETTER'] = true;
} else {
$data_in['ONETIME_NEWSLETTER'] = false;
$data_in['PROMOS'] = false;
$data_in['SUB_NEWSLETTER'] = false;
}
// Update SiB contact
$data = array(
'attributes'=> $data_in
);
try {
$updateContact = new \SendinBlue\Client\Model\UpdateContact($data);
$result = $SendInBlue->updateContact($email, $updateContact);
return true;
} catch (Exception $e) {
}
}
?>
Here's some of the form with one checkbox:
<form method="POST" class="" id="communication_preferences" action="/event" name="communication_preferences">
<input type="checkbox" name="data[newsletter_sub]" id="newsletter_sub" <?php if($newsletter_sub == 'yes'){ echo 'checked';}?>>
<button class="button button--pink button--uppercase text--three js-profile-item-submit landmark ">
Save Changes
</button>
</form>
The page just reloads when you submit the form.
The problem with checkboxes is that they do not appear in the $_POST when not checked.
Your receiving script can simple do this:
$bMyCheckOn = isset($_POST["someCheckBoxName"]); // true/false
Please make sure that if (!empty($_POST['newsletter_sub'])) { matches your input.
Here, i rewrote your entire script:
<?php
if (!empty($_POST['submit'])) {
global $SendInBlue;
$data_in = [];
foreach(['ONETIME_NEWSLETTER', 'PROMOS', 'SUB_NEWSLETTER'] as $data) {
if (!empty($_POST['newsletter_sub'])) { //Checkbox set?
$data_in[$data] = true;
} else {
$data_in[$data] = false;
}
}
$data = ['attributes' => $data_in];
$attempt = new \SendinBlue\Client\Model\UpdateContact($data);
$result = $SendInBlue->updateContact($email, $attempt) ? true : false;
print_r($result);
} else {
echo 'Form not submitted.';
}
?>
<form method="POST" id="communication_preferences" action="">
<input type="checkbox" name="newsletter_sub" id="newsletter_sub" <?=($newsletter_sub == 'yes' ? 'checked' : '')?>>
<button type="submit" class="button button--pink button--uppercase text--three js-profile-item-submit landmark" name="submit" value="submit">
Save changes
</button>
</form>
I will admit immediately that this is homework. I am only here as a last resort after I cannot find a suitable answer elsewhere. My assignment is having me pass information between posts without using a session variable or cookies in php. Essentially as the user continues to guess a hidden variable carries over all the past guesses up to that point. I am trying to build a string variable that holds them all and then assign it to the post variable but I cannot get anything to read off of the guessCounter variable i either get an undefined index error at the line of code that should be adding to my string variable or im just not getting anything passed over at all. here is my code any help would be greatly appreciated as I have been at this for awhile now.
<?php
if(isset($_POST['playerGuess'])) {
echo "<pre>"; print_r($_POST) ; echo "</pre>";
}
?>
<?php
$wordChoices = array("grape", "apple", "orange", "banana", "plum", "grapefruit");
$textToPlayer = "<font color = 'red'>It's time to play the guessing game!(1)</font>";
$theRightAnswer= array_rand($wordChoices, 1);
$passItOn = " ";
$_POST['guessCounter']=$passItOn;
$guessTestTracker = $_POST['guessCounter'];
$_POST['theAnswer'] = $theRightAnswer;
if(isset($_POST['playerGuess'])) {
$passItOn = $_POST['playerGuess'];
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$guessTestTracker = $_GET['guessCounter'];
$theRightAnswer = $_GET['theAnswer'];
}
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['playerGuess'])) {
if(empty($_POST['playerGuess'])) {
$textToPlayer = "<font color = 'red'>Come on, enter something(2)</font>";
}
else if(in_array($_POST['playerGuess'],$wordChoices)==false) {
$textToPlayer = "<font color = 'red'>Hey, that's not even a valid guess. Try again (5)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if(in_array($_POST['playerGuess'],$wordChoices)&&$_POST['playerGuess']!=$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>Sorry ".$_POST['playerGuess']." is wrong. Try again(4)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if($_POST['playerGuess']==$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>You guessed ".$_POST['playerGuess']." and that's CORRECT!!!(3)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
}
}
}
$_POST['guessCounter'] = $passItOn;
$theRightAnswer=$_POST['theAnswer'];
for($i=0;$i<count($wordChoices);$i++){
if($i==$theRightAnswer) {
echo "<font color = 'green'>$wordChoices[$i]</font>";
}
else {
echo $wordChoices[$i];
}
if($i != count($wordChoices) - 1) {
echo " | ";
}
}
?>
<h1>Word Guess</h1>
Refresh this page
<h3>Guess the word I'm thinking</h3>
<form action ="<?php echo $_SERVER['PHP_SELF']; ?>" method = "post">
<input type = "text" name = "playerGuess" size = 20>
<input type = "hidden" name = "guessCounter" value = "<?php echo $guessTestTracker; ?>">
<input type = "hidden" name = "theAnswer" value = "<?php echo $theRightAnswer; ?>">
<input type = "submit" value="GUESS" name = "submitButton">
</form>
<?php
echo $textToPlayer;
echo $theRightAnswer;
echo $guessTestTracker;
?>
This is a minimal functional example of what you need to do. There are still a couple of minor bugs (like duplicate entries in the history), but I've left these as an exercise for you. Treat this as a starting point and build up what you need from it.
I've added comments to explain what's happening, so hopefully it is clear to you.
$answer = null;
$history = [];
$choices = ['apple', 'grape', 'banana'];
$message = '';
// check if a guess has been made.
if (!empty($_POST) && !empty($_POST['guess'])) {
// check if previous guesses have been made.
if (!empty($_POST['history'])) {
$history = explode(',', $_POST['history']);
}
// check guess.
if (!empty($_POST['answer']) && !empty($_POST['guess'])) {
// check guess and answer are both valid.
if (in_array($_POST['guess'], $choices) && isset($choices[$_POST['answer']])) {
if ($_POST['guess'] == $choices[$_POST['answer']]) {
// correct; clear history.
$history = [];
$message = 'correct!';
} else {
// incorrect; add to history and set previous answer to current.
$history[] = $_POST['guess'];
$answer = $_POST['answer'];
$message = 'incorrect!';
}
} else {
// invalid choice or answer value.
}
}
}
if (empty($answer)) {
// no answer set yet (new page load or correct guess); create new answer.
$answer = rand(0, count($choices) - 1);
}
?>
<p>Guess the word I'm thinking:</p>
<p><?php echo implode(' | ', $choices) ?></p>
<form method="POST">
<input type="hidden" name="answer" value="<?php echo $answer; ?>">
<input type="hidden" name="history" value="<?php echo implode(',', $history); ?>">
<input type="text" name="guess">
<input type="submit" name="submit" value="Guess">
</form>
<p><?php echo $message; ?></p>
Hello i want to call a function using jquery. I tried a lot of ways and I can't get it.
This my principal webpage.
I'am uploading a file csv and pressing 'Crear' button, it uplaod the file while call the function.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<SCRIPT type="text/javascript">
$(function (){
$('#btnxml').click(function (){
alert("aki");
$('#contenidos').load('csv.php');
});
});
</SCRIPT>
</head>
<body>
<form action="index.php" id="filecsv" method="post" enctype="multipart/form-data">
<input type="file" multiple="multiple" id="file" name="up_csv[]"/>
<input type="submit" value="Cargar" name="btnxml" id="btnxml" /><br />
</form>
<?php
global $archivocsv;
//tipos de archivos permitidos
$extensionxml = array('csv','txt');
//destino
$rutaupcsv = './csv/';
//multicargador de archivos
$vt=0;
for($i=0;$i<count($_FILES['up_csv']['size']);$i++){
for ($j=-1; $j<count($extensionxml); $j++) {
if (strripos($_FILES['up_csv']['name'][$i], $extensionxml[$j])!== false) {
$filename = 'lista';
$destino = $rutaupcsv.$_FILES['up_csv']['name'][$i];
$archivocsv = basename($_FILES['up_csv']['name'][$i]);
move_uploaded_file($_FILES['up_csv']['tmp_name'][$i],$destino);
$vt=$vt+1;
break;
}
$ns=1;
}
}
?>
<div id="contenidos"></div>
csv.php
<?php
echo '<html>';
echo '<head>';
echo '<meta content="text/html;charset=utf-8" http-equiv="Content-Type">';
echo '<meta content="utf-8" http-equiv="encoding">';
echo '</head>';
function makecsv() {
global $archivocsv;
$csv = './csv/' . $archivocsv;
$doc = new DOMDocument();
$row = 1;
$handle = fopen($csv, "r");
# Rows Counter
$csvxrow = file($csv);
$csvxrow[0] = chop($csvxrow[0]);
$anzdata = count($csvxrow);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
#Load Predefined XML Template
$xml2 = $xml;
$xmlruta = './Templates/';
$xml = $xmlruta.$data[1].'.xml';
$doc->load($xml);
$xp = new DOMXPath($doc);
for ($c=0; $c < $num; $c++) {
foreach($xp->query('/ROOT/HEADER/#KEY[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[0];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#AUFNR[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[0];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#MATNR[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[1];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#GAMNG[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[2];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1AFFLL/E1FVOL/#MGVRG[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[2];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#GSTRS[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[3];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#GLTRS[. != ""]') as $attrib)
{
$fecha = new DateTime($data[3]);
$fecha->add(new DateInterval('P1M'));
$attrib->nodeValue = $fecha->format('Y-m-d');
}
}
$name = $data[0] .'-'. $data[1];
$doc->formatOutput = true;
echo $doc->saveXML();
$rutafinal = './XML/';
$doc->save($rutafinal.$name.'.xml');
}
fclose($handle);
echo $anzdata . " XML Creados" . "<br />";
return $data;
}
makecsv();
echo '</html>';
?>
I can't call the function.
it doesn't do anything when i try to call it.
EDIT: I think the problem is in my function. function edite
Javascript canĀ“t play with php directly because JS is client side (only in browser) and PHP is server side (only in browser). What you can do is a PHP file that has the code you want to invoke, and make JS call that page.
Separate the CVS code from the form and make JS call the new php with the CVS php functionality.
jQuery runs in the client's browser whereas your PHP is running on your web server. If you wish to call a PHP function from your jQuery code, your best option is to do so using AJAX.
You can find documentation for implementing an AJAX call in jQuery here: https://api.jquery.com/jQuery.ajax/
You'll need to print the actual hmtl to do the function.
PHP
<?php
print '<script> makecsv() </script>';
?>
I want to validate an HTML form in either HTML or PHP. By validate, I mean ensuring there is at least 1 character of text entered into each of the 2 textboxes. And either only alpha numeric characters entered, or have something that ensures that any punctuation doesn't end up with "/" before it.
At the moment my form is made up of 2 php pages (copied below), and then posted to a txt file.
I'm either after some (very basic) instructions on how to do it, or suggestions on my script below.
//HTML
<form style="" method="post" action="addtopic2.php">
Topic:<input name="topic" id="topicbox" maxlength="100" type="text"><br>
Outline: <textarea input wrap="nowrap" rows="10" cols="120"
name="outline"></textarea>
<br><input name="submit" value="Submit" type="submit">
</form>
//HTML
<?php
$t = "Topic:";
$o = "Outline:";
$topic = $_POST['topic'];
$outline = $_POST['outline'];
$data = "$t $topic | $o $outline |\n";
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
fclose($fh);
?>
//ATTEMPTED TO USE FOLLOWING, BUT DOESNT SEEM TO WORK WHEN INSERTING INTO EITHER PAGES.
<?php
if($_POST['Submit'] == "submit")
{
$errorMessage = "";
if(empty($_POST['topic']))
{
$errorMessage .= "<li>A topic needs to be entered</li>";
}
if(empty($_POST['outline']))
{
$errorMessage .= "<li>An outline needs to be entered</li>";
}
$vartopic = $_POST['formtopic'];
$varoutline = $_POST['formoutline'];
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
<?php
if (isset($_POST['topic']) && isset($_POST['outline'])) {
$topic = trim($_POST['topic']);
$outline = trim($_POST['outline']);
}
else {
echo '<p>Fill the form</p>';
}
?>
Try
$file = "users.txt";
$errorMessage = array ();
if ($_POST ['Submit'] == "submit") {
if (empty ( $_POST ['topic'] )) {
$errorMessage [] = "A topic needs to be entered<";
}
if (empty ( $_POST ['outline'] )) {
$errorMessage [] = "An outline needs to be entered";
}
if (count ( $errorMessage ) == 0) {
$data = $_POST ['topic'] . "|" . $_POST ['outline'] . "\n";
$fh = fopen ( $file, "a" );
fwrite ( $fh, $data );
fclose ( $fh );
} else {
print ("<p>There was an error with your form:</p>\n") ;
print ("<ul>") ;
foreach ( $errorMessage as $error ) {
print "<li>" . $error . "<li>";
}
print ("</ul>") ;
}
}
// To Read Your File
$content = file ( $file );
print ("<p>File Details</p>\n") ;
foreach ( $content as $info ) {
list ( $topic, $outline ) = explode ( "|", $info );
print ("<ul>") ;
print "<li>Topic: " . $topic . "<li>";
print "<li>Outline:" . $outline . "<li>";
print ("</ul>") ;
}
Try this (single file) solution:
<form style="" method="post">
Topic:<input name="topic" id="topicbox" maxlength="100" type="text" value='<?= $_REQUEST['topic'] ?>><br>
Outline: <textarea input wrap="nowrap" rows="10" cols="120" name="outline"><?= $_REQUEST['outline'] ?></textarea>
<p/>
<input name="submit" value="Submit" type="submit">
</form>
<?php
if ($_REQUEST['submit'] !== 'submit')
{
exit;
}
if ($_REQUEST['topic'] == '')
{
echo "<p>Missing Topic.</p>\n";
exit;
}
if ($_REQUEST['outline'] == '')
{
echo "<p>Missing Outline.</p>\n";
exit;
}
$t = "Topic:";
$o = "Outline:";
$topic = $_POST['topic'];
$outline = $_POST['outline'];
$data = "$t $topic | $o $outline |\n";
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
fclose($fh);
?>