Well then, this is likely to be the n-th time someone is asking this, but honestly I didn't grab anything useful spending the last hour or so on Google. What I want to do is rather trivia, or so I thought. I have this working in Java Script but want to move it to PHP. In brief:
declare a var with a static value
add text field into which user is asked to enter value of above var
check if field is a) empty, b) non-empty mismatch, or c) non-empty match
My (limited) PHP wisdom has lead me into believing it ought to be something like the below, but apparently it's not. I'd very much appreciate any insight, tha.
<?php
$coconew = "blah";
if (isset ($_POST["cocosub"])) {
if ($_POST["cocoval"] == "") {
echo "empty";
} else {
if ($_POST["cocoval"] != $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval">
<input type="submit">
</div>
</form>
You need to change
<input type="text" id="cocoval">
to
<input type="text" name="cocoval">
There are other (and probably better) ways to do this, but you are on the right track.
$_POST only looks for the name attribute of form elements, so modify your form as such:
<?php
$coconew = "blah";
if (isset ($_POST["cocoval"])) {
if ($_POST["cocoval"] === "") {
echo "empty";
} else {
if ($_POST["cocoval"] !== $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit">
</div>
</form>
(I made a few other changes, you want to check isset on the element, not the form, it will POST to the same page if you don't give it an attribute [so no need to add the echo], and adding better type checking in your php)
in addition to the other answers already posted, you might also be interested in PHP's session support (depending on how "static" you need your static variables to be). That's where you'd put $cocoval and any other variables if you need to save their values across multiple requests for the same URL by the same user. See here for more info:
http://php.net/manual/en/features.sessions.php and
http://www.php.net/manual/en/book.session.php
This works:
<?php
session_start();
if(isset($_POST["cocosub"])){
$input = trim($_POST["cocoval"]);
if($input == ""){
echo "empty";
} elseif($input != $_SESSION["coconew"]){
echo "mismatch";
} else {
echo "match";
}
}
$_SESSION["coconew"] = substr(md5(uniqid()), 0, 5);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="cocosub" method="post">
<div>
<?php echo $_SESSION["coconew"]; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit" name="cocosub">
</div>
</form>
You needed to add name="cocosub" to the Submit button element in order for the first if(isset(...)) condition to be true. That's why the script didn't work. Also, instead of id, you need to use the name="cocoval" in the input text field as well in order for it to carry over into $_POST.
Related
I am following a tutorial but I keep getting a TRUE result that shouldn't be correct if I click the submit button WITHOUT filling in any value in the name field.
The first test works as expected, but the second and third test keep returning TRUE when they should return FALSE (leaving the input empty).
What am I missing, not understanding, or doing wrong? This should be simple.
Any help or suggestions are appreciated.
Here is the very simple script:
<?php
//This one works correctly
if(!empty($_POST['name'])) {
echo "There is input here <br>";
} else {
echo "You have not input any info yet. <br>";
}
//This returns true even if I leave the field empty
if(isset($_POST['name'])) {
echo "A name has been input <br>";
} else {
echo "You have not input your name yet. <br>";
}
//This returns true also when it shouldn't
if(filter_has_var(INPUT_POST, 'name')) {
echo $_POST['name'] . ' <- Name Input!<br>';
} else {
echo 'No Name Input.';
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p><label for="name">Name:</label> <input type="text" name="name"
id="name" size="30" value=""></p>
<p><input type="submit" value="SEND"></p>
</form>
empty does what is says, checks if empty (is empty if not existing aswell)
isset checks if the var exists, no if anything has been set
filter_has_var pretty much the same as isset
place a print_r($_POST) at the top of your file, you will understand :)
You need to check the value to see if it's empty:
if(isset($_POST['name']) && !empty($_POST['name'])) {
http://php.net/manual/en/function.empty.php
I am trying to do a find and replace applicaiton the problem is that after cliked submit button all the text fields gets clean nothing displays on the screen What am i doing wrong
<?php
$offset=0;
if(isset($_POST['text'] ) && isset($_POST['searchfor']) && isset($_POST['replacewith'])){
$text=$_POST['text'];
$search=$_POST['searchfor'];
$replace=$_POST['replacewith'];
$searchLength=strlen($search);
if(!empty($text) && !empty($search) &&!empty($replace)){
while ($strpos= strpos($text,$search,$offset)){
echo $offset=$strpos+$searchLength;
}
} else {
echo "<script>alert('errorrrr')</script>";
}
}
?>
<form action="#" method="post">
<textarea name="text" id="" cols="30" rows="10"></textarea><br>
Search For:<br>
<input type="text" name="searchfor"><br>
ReplaceWith<br>
<input type="text"name="replacewith"><br>
<input type="submit" value="Fr..."></>
</form>
Regarding your form, you decided to submit to the same page.
Doing this, the page is obviously fully reloaded when submitted. Hence it is normal that what you typed in has disappeared.
If you want to see it again, you have to display you variables in the HTML code.
For example:
<?php
$myVar = "";
if(isset($_POST['myVar']){
$myVar = $_POST['myVar'];
}
?>
<form>
<input type="text" value="<?php echo $myVar;?>"/>
</form>
NB: I encourage you to filter the user entry.
Regards
there is problems in your code :
1 - echo $offset=$strpos+$searchLength; the echo can't be used in this format. insted use echo $offset; in next line for seeing offset values.
2 - if the text be like 'amir love persepolis' and search for 'amir' to replace it with 'all men's' you will have another issue, because you will have while ( 0 ) situation. think about this too!
Hi I am clearing my basics of php and i am kind of stuck in implementing this guess game. My problem is that I want $num_tries to work as a counter and it increases everytime by 1 whenever the user answers incorrectly.
<?php
$target=58;
$message="";
$num_tries=0;
if(isset($_POST["num_tries"])) {
print "set";
++$num_tries;
} else {
print "not set";
$num_tries=0;
}
if (!isset($_POST["guess"])) {
$message="Welcome to the game of Guess!!!!!!";
} elseif($_POST["guess"]> $target) {
$message= "Try a smaller Number";
} elseif($_POST["guess"] < $target) {
$message= "Try a larger Number";
} else {
$message= "congrats....You got it.";
}
?>
<HTML>
<HEAD><TITLE>Guess Game</TITLE>
</HEAD>
<BODY>
<H1><?php print $message ?></H1>
Guess Number:<?php print $num_tries ?>
<FORM action="<?php print $_SERVER['PHP_SELF'];?>" method="POST">
<INPUT type="text" name="guess">
<INPUT type="hidden" name="num_tries" value="<?php $num_tries?>">
</FORM>
</BODY>
</HTML>
You can solve it in your first lines:
$target=58;
$message="";
$num_tries = (!empty($_POST['num_tries']) ? $_POST['num_tries'] : 0);
That means if the form is not submitted before, $num_tries will be zero, otherwise, the value will be the last submitted value.
And then you need to print in the hidden element
<INPUT type="hidden" name="num_tries" value="<?php echo $num_tries?>">
---------------------------------------------------^^^^
$message="";
$num_tries=0;
change the above declaration to $num_tries=isset($_POST["num_tries"]) ? $_POST["num_tries"] : 0; which means if the post var value is set, then assign post var value, else assign 0.
and next change what you need to make is printing the value under hidden element.
you can use print or print_r or echo.
<INPUT type="hidden" name="num_tries" value="<?php echo $num_tries; ?>">
You are using <?php $num_tries ?> which literally does nothing.
You need to use <?php echo $num_tries ?> (print also works, but for your use case, echo is more efficient) in order to actually place the value into the form.
Additionally, $num_tries = 0; will not bother reading the existing value. You can use $num_tries = $_POST['num_tries'] | 0; although it will generate a PHP notice when the field isn't set, if you care about this, use isset with a ternary operator or if/else.
I am making a form in html. When a person clicks on submit, it checks if certain fields are filled correctly, so pretty simple form so far.
However, i want to save the text which is typed into the fields, if a person refreshes the page. So if the page is refreshed, the text is still in the fields.
I am trying to achieve this using php and a cookie.
// Cookie
$saved_info = array();
$saved_infos = isset($_COOKIE['offer_saved_info']) ? explode('][',
$_COOKIE['offer_saved_info']) : array();
foreach($saved_infos as $info)
{
$info_ = trim($info, '[]');
$parts = explode('|', $info_);
$saved_info[$parts[0]] = $parts[1];
}
if(isset($_SESSION['webhipster_ask']['headline']))
$saved_info['headline'] = $_SESSION['webhipster_ask']['headline'];
// End Cookie
and now for the form input field:
<div id="headlineinput"><input type="text" id="headline"
value="<?php echo isset($_SESSION['webhipster_ask']['headline']) ?
$_SESSION['webhipster_ask'] ['headline'] : ''; ?>"
tabindex="1" size="20" name="headline" /></div>
I am new at using SESSION within php, so my quesiton is:
Is there a simpler way of achieving this without using a cookie like above?
Or what have i done wrong in the above mentioned code?
First thing is I'm pretty sure you're echo should have round brackets around it like:
echo (isset($_SESSION['webhipster_ask']['headline']) ? value : value)
That's not really the only question your asking though I think.
If you're submitting the data via a form, why not validate using the form values, and use the form values in your html input value. I would only store them to my session once I had validated the data and moved on.
For example:
<?php
session_start();
$errors=array();
if($_POST['doSubmit']=='yes')
{
//validate all $_POST values
if(!empty($_POST['headline']))
{
$errors[]="Your headline is empty";
}
if(!empty($_POST['something_else']))
{
$errors[]="Your other field is empty";
}
if(empty($errors))
{
//everything is validated
$_SESSION['form_values']=$_POST; //put your entire validated post array into a session, you could do this another way, just for simplicity sake here
header("Location: wherever.php");
}
}
if(!empty($errors))
{
foreach($errors as $val)
{
echo "<div style='color: red;'>".$val."</div>";
}
}
?>
<!-- This form submits to its own page //-->
<form name="whatever" id="whatever" method="post">
<input type="hidden" name="doSubmit" id="doSubmit" value="yes" />
<div id="headlineinput">
<input type="text" id="headline" value="<?php echo $_POST['headline'];?>" tabindex="1" size="20" name="headline" />
<!-- the line above does not need an isset, because if it is not set, it will simply not have anything in it //-->
</div>
<input type="submit" value="submit" />
</form>
I need to validate an empty field with php and javascript, but both of the methods fail.
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<input type="text" name="pickupaddress" value="<?
if($pickupaddress == ''){
echo "";}
else{echo htmlentities($pickupaddress);}?> " id="pickupaddress"/>
<input type ="submit" name="submit" value"Reserve"/>
</form>
//////// Php validation DOES NOT WORK////////
$pickupaddress ='';
$err ='';
$pickupaddress = $_POST['pickupaddress'];
if($pickupaddress == ''){ //if empty field, I also tried == ""
$err.="Please provide pick up address.";
}
///// Javascript validation does not work.
if(form.pickupaddress ==""){
alert("empty address!");
}
//when I click submit nothing happens.
//I am thinking the problem is with
htmlentities($pickupaddress);
//Thanks for your help.
Here is hopefully simpler answer:
$pickupaddress = trim($_POST['pickupaddress']); //trims the string
if (empty($pickupaddress)){ //if empty field
$err.="Please provide pick up address.";
}
On the php side you can try trimming the value and then using empty() on the next line, though that will also invalidate 0, false, null, and other such values. Or you can try using isset.
For the javascript side you can try this function:
function IsEmpty(aTextField) {
if ((aTextField.value.length==0) ||
(aTextField.value==null)) {
return true;
}
else { return false; }
}
found here: http://www.codetoad.com/javascript/isempty.asp
$cid = $_POST['category'];
if (!empty($_POST['category']))
{
echo "<script>alert('empty field');</script>";
}
Where are you defining pickupaddress? Is it before the form or after? If the variable isn't defined, and depending on your server configuration, the value field of the input could be
Notice: undefined variable pickupaddress
Thus making the value != ''.
View your page source to ensure that the value is indeed empty.
there was a spave " " in your string: echo htmlentities($pickupaddress);}?> "
maybe that was the reason, because it was not an empty string but it was a space?
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<input type="text" name="pickupaddress" value="<?
if($pickupaddress != '') {
echo htmlentities($pickupaddress);
}?>" id="pickupaddress"/>
<input type ="submit" name="submit" value"Reserve"/>
</form>
and i guess you might want to have checked if the post value is set:
if(isset($_POST['pickupaddress'])) {
$pickupaddress = $_POST['pickupaddress'];
}
the php way works for me like that ;) (the message is displayed if i dont write anything)