else Statement not being triggered after if(empty($var)) - php

I've tried searching for a solution to my problem on stackoverflow but can't seem to find one that fits my situation.
<?php
if (empty($userName)){
print <<<HERE
<form>
Please enter your name:
<input type="text" name="userName">
<br>
<input type="submit">
</form>
HERE;
}
else {
print "<h3>Hi there, $userName!</h3>";
} //end
?>
When I enter a value into the form field it is assigned to the variable $userName but the issue occurs when the else statement is not being triggered after that value has been added.
I hope I've been clear enough, looking forward to a possible solution.
Thank You.

this code only works if register_globals is enabled, and register_global was removed since PHP 5.4.0, so this code won't work in PHP 5.4+, nor will it work if register_globals is disabled in PHP.ini (and it has been disabled-by-default since PHP 4.2.0), try
if (empty($_GET['userName'])){
instead. also, seems you're wide open to XSS here, the variable needs to be escaped before being echoed back to the user, or you open your website to xss attacks by hackers.
try
function hhb_tohtml(string $str):string
{
return htmlentities($str, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE | ENT_DISALLOWED, 'UTF-8', true);
}
print "<h3>Hi there, ".hhb_tohtml($_GET['userName'])."!</h3>";

How are you retrieving your value from your variable? I don't see that in your question.
<?php
if(isset($_POST['userName'])) {
$userName = $_POST['userName']; //This will take the userName input and put it into a variable for you to test.
}
if (empty($userName)){
print <<<HERE
<form>
Please enter your name:
<input type="text" name="userName">
<br>
<input type="submit">
</form>
HERE;
}
else {
print "<h3>Hi there, $userName!</h3>";
} //end
?>

Related

PHP function echoes unexpected HTML value

I have a piece of php code inside html tag which is supposed to change the tag's style in accordance with the contents of the URL.
There is an html login form which looks like this:
<form class="userdata" action="login.php" method="post">
<input type="text" name="email" placeholder="E-mail" <?php fillin('email'); enlight_unfilled('email');?>><br>
<input type="password" name="pwd" placeholder="Password"><br>
<button type="submit" name="login-submit">Login</button>
</form>
Here are the functions fillin and enlight_unfilled:
<?php
function fillin($key) {
if (isset($_GET[$key])) echo "value=".$_GET[$key];
else echo NULL;
}
function enlight_unfilled($key) {
if (isset($_GET['error']))
if (isset($_GET[$key]) and $_GET[$key] !== "") echo NULL;
else echo "style='border-color: red'";
else echo NULL;
}
?>
If I only apply one of the functions within the tag, they both do what they are expected to – either save the email in the field if it has been already typed in or enlighten the email field if it has been left empty. But if I apply them together, when the field is empty, php assigns the field value 'style='border-color:. I also tried to use functions like print and printf, but the result is the same:
I am a beginner at php coding and mixing it with html, so the question may appear to be dumb, but I did not manage to find any sort of a solution to this issue, so thanks for help and patience in advance!
It looks like you don't properly encase value in quotes, so it just renders the 'style='border-color:.
Let's assume that $_GET[$key] has a value of hello#hello.com. What your PHP & HTML renders is the following:
value=hello#hello.com
See the problem? There are no quotes. That's why the renderer goes forward searching for a valid value. To fix the issue you must add quotes around your $_GET[$key] in the fillin function. Something like this should do the job:
if (isset($_GET[$key])) echo "value='".$_GET[$key] . "'";
It works when ran alone because it reaches the end > and just assumes the value to be hello#hello.com

Button Value Not Changing when Text Field Isn't Empty

Having a small issue getting my submit button to change the value when the php variable isn't empty. So the way I have it set up is that when the button "GO" is pressed it will set the value of the text field to "1234567890" meaning it is no longer empty. Now when the page first loads the text field will be empty and the button should say "GO" once pressed the text field value will change and the button should now say "REFRESH" however it stays saying "GO" can anyone see where I'm going wrong here?
Thanks.
PHP
<?
if (!$HostKey){
$HostBtn = 'GO';
}
else{
$HostBtn = 'REFRESH';
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['Go'])) {
$HostKey = "123567890";
}
}
}
?>
HTML
<form action="Home.php" method="post">
<p><strong>HOST:</strong>
<input name="Host" id="Host" type="text" value="<? echo $HostKey; ?>" maxlength="10" disabled>
<input name="Go" id="Go" type="submit" value="<? echo $HostBtn; ?>"></p>
</form>
Your issue is a logical one, as $HostKey isn't defined prior to you doing your check - so $HostKey is null. You define it after that. Then, because the variable is effectively null, when you apply the not-operator !, that condition is always true.
You should refactor your code to check if the form was submitted, and define the value of the variable based on that instead. All you need in PHP would be
$HostBtn = isset($_POST['Go']) ? 'REFRESH' : 'GO';
$HostKey = isset($_POST['Go']) ? 123567890 : '';
This would also fix the "Undefined variable..." notices you should have been getting if you enabled error-reporting,
error_reporting(E_ALL);
ini_set("display_errors", 1);
Which should be enabled while in development. In a live environment, you shouldn't display the actual errors though - but its fine to do that under development.
You should try something like :
<?
if (isset($_POST['Go'])) {
$HostKey = "123567890";
$HostBtn= "REFRESH";
}else{
$HostKey="";
$HostBtn="GO";
}
?>

Get input from HTML form in PHP

I'm learning MySQL and PHP and got a problem with the input of the form. So I wrote a small test code, but it still cannot work. My PHP version is 5.6.
The code:
<html>
<body>
<form action ="2.php" method ="post">
Name: <input type="text" name="username" />
<input type ="submit" value="ok" />
</form>
</body>
</html>
and
<html>
<?php
if(isset($_POST['username'])){
$user=$_POST['username'];
echo $user;
echo " is your name";
}
else{
$user=null;
echo "error";
}
?>
</html>
The output of the project is always error, can't output the input before.
I tried single quote and double quote for username, both can't work.
I also tried to set always_populate_raw_post_data in php.ini to 0, -1, 1, all can't work.
I don't know where the problem is, though it might be very silly.
As what it look it is correct and should run without any problem. Make sure the above code is what you actually have. From my experience most of the form submission can be
you don't have correct name (username)
you might send incorrect http verb (post)
you submit to wrong endpoint (2.php)
From you code above everything look fine. if you still don't have the right result, you better debug it with var_dump, or print_r function with these built-in
$_POST, $_GET, $_REQUEST and check whether they contains you form variable name username
You are using isset as a variable, but it is a function that returns a boolean.
Change $user=isset($_POST['username']); to $user=$_POST['username'];
Another thing is that in both case you will end up in the IF condition even if there is no value added to the field so you can do something like this too:
<html>
<?php
if(isset($_POST['username']) && !empty($_POST['username'])){
$user=$_POST['username'];
echo $user;
echo " is your name";
}
else{
$user=null;
echo "error";
}
?>
</html>

give a user X number of chances to input a value in PHP

Hi I am a newbie learning PHP ( & on stackoverflow too)- I am trying to solve a simple problem but unable to do. I hae already searched on google and stackoverflow before posting a question as I didnt want to waste other time but for a week now am unable to solve this issue.
I am writing a simple program in php that lets user input a number and checks if the value entered is 5. If true it echo's "you win" else "try again". I am able to do this
The tricky part for me is I want to give him only 10 chances and try as I might using basic PHP am unable to do this. Have tried using if, for, do while but am unable to "loop the html"..I dont know jquery etc and am trying to accomplish this with PHP only. I havent yet progessed to learning sessions etc. Thanks in advance
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<form method="POST" action="gullible.php">
Please enter any number :<input type="text" name="num">
<input type="hidden" name="cnt" value=<?php $cnt=0 ?>>
<input type="submit" name="go">
</body>
</html>
<?php
$i=0;
if ($_POST['num']!=5)
{
$i++;
echo $i;
echo " Please try again";
}
else
echo "You win the game";
?>'
You need to store the variable in some manner such that it persists. in your script, you are setting $i to 0 each time it runs. Plus you are setting the value incorrectly in your hidden input.
One way of doing this is using a Session variable, such as $_SESSION['cnt']
My PHP is a bit rusty, but here's an example using Session variables:
$max_guesses = 10;
if( !isset($_SESSION['cnt']) ){
$_SESSION['cnt'] = 0;
}
if( $_SESSION['cnt']++ > $_max_guesses ){
echo "Maximum tries exceeded";
} else {
echo "Try again";
}
If you don't want to, or can't use a session variable, you could use the hidden input field, like you tried to:
<?php
if( !isset($_POST['cnt']) ){
$cnt = 0;
} else {
$cnt = $_POST['cnt'];
}
if( $cnt++ > $_max_guesses ){
echo "Maximum tries exceeded";
} else {
echo "Try again";
}
?>
<input type='hidden' name='cnt' value='<?php echo $cnt ?>' />
(Note if your form uses GET instead, just replace $_POST with $_GET or you can use $_REQUEST if you're not sure, but probably better not to.
After successful login of the user set the chances variable to 10 like this.
$_SESSION['nofchances']=10;
After setting this flag on the successful authentication page. Redirect to your PLAIN html code.
EDITED :
question.html
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<form method="POST" action="gullible.php">
Please enter any number :<input type="text" name="num">
<input type="submit" name="go">
</body>
</html>
gullible.php
<?php
if($_SESSION['nofchances']!=0)
{
if ($_POST['num']!=5)
{
$_SESSION['nofchances'] = $_SESSION['nofchances'] - 1;
echo "You have ".$_SESSION['nofchances']." no of chances to try";
echo "<br>Please try again";
header("location:question.html");
}
else
{
echo "You won the game";
$_SESSION['nofchances']=10; // resetting back
}
}
else
{
echo "Your chances expired";
}
?>
You can call a function in onBlur/onChange
<script>
function test()
{
var count=<?php echo $count;?>;
var guess=parseInt($('#hid_num').val())+1;
if(guess>count)
{
alert('Your chances over!');
}
else
{
$('#hid_num').val(guess);
}
}
</script>
<input type="text" onblur="test();" id="chk_estimate" />
<input type="hidden" value="0" id="hid_num" /></body>
If you dont want to use sessions yet you could define a hidden input field which stores the current try then incriment "+1" it whenever the submit is pressed / the site is reloaded. Something like:
if( isset($_POST['try']) ) {
$try = $_POST['try'];
$try += 1;
} else {
$try = 0;
}
add the hidden field in your form like:
$hiddenTry = '<input type="hidden" value="'. $try .'" name="try"/>';
and add a if clause to when to show the form like:
if ( $try <= 10 ) {
//your form
}
i made this for you i hope it can help you learn something new (i edited it a couple of times to make variable names easier to understand make sure you check it again - i added a cheat also :) )
<?php
session_start(); // with this we can use the array $_SESSION to store values across page views of a user.
mt_srand(time()); // this is to ensure mt_rand function will produce random values. just ignore it for now. it's another story :)
$max_tries = 10; // limit of guesses
$_SESSION['the_magic_number']=!isset($_SESSION['the_magic_number'])?mt_rand(0,100):$_SESSION['the_magic_number'];
// the previous line is a one-liner if then else statement. one-liners works like this:
// $my_name_will_be=($isBoy==true)?"George":"Mary";
if(isset($_POST['num'])) // if this pageview is from a valid POST then...
{
$_SESSION['current_try']=isset($_SESSION['current_try'])?$_SESSION['current_try']+1:1;
// one-line if then else again. This increases the try user is now, or resets it to one
}
?>
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<?php
if ($_SESSION['current_try']<=$max_tries) // if user has more tries available
{
if(intval($_POST['num'])==$_SESSION['the_magic_number']) // did he found it?
{
echo "You found it! Gongratulations! Click <a href=''>here</a> to try again!";
// oh and do not forget to reset the variables (you found this bug, well done!)
$_SESSION['current_try']=1;
$_SESSION['the_magic_number']=NULL;
}
else
{
// if he didn't found it, display the status of tries left, and the form to try again
echo "This is your try ".($_SESSION['current_try'])." of ".$max_tries." Good Luck!";
?>
<form method="POST" action="mygame.php">
Please enter any number :
<input type="text" name="num"/>
<input type="hidden" name="tries" value="<?php echo (isset($_POST['tries']))?$_POST['tries']-1:$max_tries; ?>"/>
<input type="submit" name="go"/>
</form>
<span style="color:white;background-color:white;"><?php echo "You bloody cheater! The magic number is ".$_SESSION['the_magic_number'];?></span>
<?php
}
}
else
{
// here we are if no tries left! An empty href to reload the page, and we resetting our variables.
// the_magic_number gets NULL so at the start of script it will be "not set" and will get a mt_rand(0,100) value again
echo "You lost! Sorry! Click <a href=''>here</a> to try again!";
$_SESSION['current_try']=1;
$_SESSION['the_magic_number']=NULL;
}
?>
</body>
</html>
the span at the end is a cheat ;) press ctrl+a to use it !!!

Why doesn't this email-address-submitting code work with Opera and Internet Explorer?

I've just discovered the email-address-saving form on my website does not work on Opera and Internet Explorer (7 at any rate), and possibly other browsers. Works fine with Firefox. Unfortunately I'm not a developer and no longer have any contact with the guy who wrote the code for the form so I've no idea how to fix it. I assume the problem has something to do with the code below:
<?php
$str = '';
if (isset($_POST['submit']))
{
if(!eregi("^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$", $_POST['email'])) {
$str = "<span style='color: red'>Not a valid email address</span>";
} else {
$file = 'emails.txt';
$text = "$_POST[email]\n";
if (is_writable($file)) {
if (!$fh = fopen($file, 'a')) {
exit;
}
if (fwrite($fh, $text) === FALSE) {
exit;
}
fclose($fh);
}
header('Location: thankyou.html');
}
}
?>
and then the body bit:
<form action="index.php" method="post">
<input type="text" name="email" style="width: 250px;" />
<input type="image" src="img/button-submit.png" name="submit" value="Submit" style="position: relative; top: 5px; left: 10px" />
</form>
<?php echo $str ?>
Anybody feeling pity for a helpless non-dev and have an idea what's not working here?
This is being caused by the fact that the submit input is of type 'image'. On submit, IE7 only returns the x and y coords of the click.
This should do the trick:
Replace:
if (isset($_POST['submit']))
With:
if (isset($_POST['submit']) || isset($_POST['submit_x']))
It is a browser based issue
in your form, you have used <input type="image" />
IE doesn't pass name/value pairs for image type input, instead it only sends the key_x/value_x and key_y/value_y pairs
you probaly want to use <input type="submit" /> as replacement/addition, since this is completely supported on all types of browsers (think also about text browsers please, i still use them.)
Unfortunately, the error, if any at all, is going to be between the Browser and the server, not PHP. If you could provide some details like the HTML form that isn't working in IE7, then we may be able to help out more.
Your form element is self-closed. Remove the trailing / in the opening tag and it should work. (Er, it might work. Either way, there shouldn't be a trailing slash.)
Assuming that the php in your code is in the same file as the form ... you might try adding the name of your php file to the form's action.
<form action="" method="post">
... becomes ...
<form action="name_of_php_file" method="post">
Include a hidden field in your form that will only be valid and present if you submit the form. Something like:
<input type="hidden" name="checkemail" value="1" />
Then, in your PHP, change the if-condition to check for this particular variable:
<?php
$str = '';
if (isset($_POST["checkemail"]))
{
//-- rest of your code
}
?>
This will allow you to keep the image as the submit button and work across browsers which differ in how they send the value, if at all, of the name of image type buttons.
I know this doesn't fix your problem, but I don't like the line:
$text = "$_POST[email]\n";
Is that not bad practice? I haven't used PHP for years, but I think you should change it to
$text = $_POST['email'] . "\n";
or something like that. Using $_POST[email] without the quotes around the array key causes PHP to first look for a constant named 'email'. Only after not finding it will it convert email to a string and then pull the value out of the associative array. Just wasted CPU power.

Categories