PHP function echoes unexpected HTML value - php

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

Related

how do i clear the screen of a calculator in php

i'm trying to find a way to erase the text screen from my calculator when you press the +/- button so it acts more like a real calculator.
i'm pretty new to php (a week or two) so i'm still learning but i cant figure this out.
the php file returns html code where in i have a <input type='text' named result value='$value'>
(calculator screen).
and a series of submit buttons with a name and value of 1,2,3,+,...
when i press a button a char gets added to the string in result.
when i press on the '=' button it reads the string with eval();
and calculates it.
iv'e tried with a function but i cant figure it out some ideas or tips would be very much welcome.
$value = '';
if(isset($_GET['result']))
$value.=$_GET['result'];
if(isset($_GET['1']))
$value .='1';
if(isset($_GET['2']))
$value .='2';
//and so on ...
if(isset($_GET['+']))
$value .='+';
if(isset($_GET['-']))
$value .='-';
if(isset($_GET['='])){
eval('$result = '.$value.';');
$value = $result;}
return "<form action='index.php' method='get'>
<br><input type='text' name='result' value='$value'><br>
<input type='submit' name='1' value='1'>
<input type='submit' name='2' value='2'>
//and so on ...
(the rest of the html code is loaded somewhere else)
This PHP code below will execute JavaScript code to clean the input field,
echo"<script>document.getElementsByName('result')[0].value = '';</script>
This should resolve your question but i have to tell you that PHP isn't suitable choice to make a web calculator, You need to use JavaScript to make a real calculator without refreshing the page.
Please copy this code below to an HTML file and try it so you can get an idea how it works.
First Number
<input type="text" id="firstNumber" value="6" /><br>
Second Number
<input type="text" id="secondNumber" value="5" /><br>
Result
<input type="text" id="result" /><br>
<button type="button" onclick="Calculate();">Calculate</button>
<script>
function Calculate(){
let firstNumber;
let secondNumber;
firstNumber = document.getElementById("firstNumber").value;
secondNumber = document.getElementById("secondNumber").value;
document.getElementById("result").value = Number(firstNumber) + Number(secondNumber);
// "Number" is to tell javascript its a number not a string/text,
// without "Number" it will concat both numbers
}
</script>
You should use brackets for your conditions, especially if you nest them:
if(isset($_GET['result'])) {
$value .= $_GET['result'];
}
And your indentation makes it look like Python, someone reading it would mistake it for a condition nested in another condition and believe that your if(isset($_GET['2'])) is true only if if(isset($_GET['1'])) is also true.
A switch is a better solution here (and even better for the operators since you probably only have four of them), but in any case, you should assign each term of your operation in a single variable.

How $_POST variable/operation is managed in PHP?

When I do something like:
foreach($_POST as $post_key => $post_value){
/* Any code here*/
}
So, something like:
$varSomething = $_POST['anything'];
$varSomethingElse = $_POST['somethingElse'];
Is it possible? When I catch a $_POST[' '], isn't that variable already consumed?
The main reason why I would do this is because after a form submission, I want to check wether some items of some type got certain value or not.
Is there aything else more appropiate?
Firstly the html code don't use variable types, for example, if you have
<input id="check" type="checkbox" />
without a established value, after that you have echo $_POST['chek'], you could think that the result would be a boolean value (false or true), but the correct result will be "on" or "off", you can coding this case. Also, if you want to know the type of your data, you can use regular expression on server side, for example:
<input type="text" id="number" value="1350" />
.....
PHP code
$data = $_POST['number'];
$regularExpression = "/^\d{1,10}$/";
if (preg_match($regularExpression, $data)) {
echo "Is numeric";
}
Good lucky.
if you don't know what is the name of element which is sending the data. the first method is ohk . but if know the name like password or username you can use second one
in html
<input type="password" name ="password" />
in php
$pass_recvd=$_POST['password'];
there is no way to check the type i.e. text/password/checkbox/select etc. you have to do it on client side BEST WAY IS USING Jquery
if you wanna check whether a variable is set or not simple check by using isset method
if( isset($_POST['someVariableName'])) {}else{}

PHP Variable Variables don't work... Why?

I'm using a function that returns a Fetched Array from a Database ( PDO::fetch(PDO::FETCH_ASSOC) ).
this function returns A LOT OF COLUMNS and when I am editing all those columns in a Form, obviously I need the fields to be populate with the current data.
Code (modified for the question):
//returns something like $owner["name"], $owner["lastname"],
//$owner["phone1"] ... and 53 fields more.
$owner = controllerGetOnwer($ownerID);
//So I used a foreach to create VARIABLE VARIABLES
foreach($owner as $key=>$value) {
${$key} = $value; //you get something like $name = <what is in that column>
}
I am gonna use this form in a lot of pages, not only for owners, but also for customers, administrators, and so on... That's why I decided to put the form in a function inside a static class I already used to 'render' all the HTML I will use a lot of times (such as Headers, logos, menus, etc)
//This is inside the HTMLRenderClass
renderTheEditForm() {
?>
<form>
Name: *<br/>
<input type="text" name="personalname" value="<?php if(isset($name)) echo $name; ?>"/><br/><br/>
Last Name: *<br/>
<input type="text" name="personallastname" value="<?php if(isset($lastname)) echo $lastname; ?>"/><br/><br/>
Phone Number 1:<br/>
<input type="text" name="personalphone1" value="<?php if(isset($phone1)) echo $phone1; ?>"/><br/><br/>
<!-- AND 53 FIELDS MORE -->
</form>
<?PHP
}
All the variables that you see inside the VALUE attribute are the same as the ones that are being created dinamically in the FOREACH. When I paste the form HTML code below the Foreach, I can see the data being loaded, but when I use the Function from the HTMLRenderClass I get nothing... I haven't been able to find the reason.
I hope I explained well, thanks beforehand!
It appears that you need to define your variables inside the function or pass them into the function.

PHP pass variable through URL

I understand how a PHP URL works - I think ... but I'm having problems getting the actual value of the variable to be passed in the example below.
Example
Note: I am adding the below form into a data cell (as part of a table being read via PHP).
$currentrowid = 1;
echo '<td>
<div class="editdelete">
<form action="phpindex.php?page=edit&thisrow=<?php echo $currentrowid;?>" method="post">
<input type="submit" value="Edit" >
</form>
</div>
</td>';
... Some other section of code to read the URL output by the form above:
$val = $_POST['thisrow'];
echo "the value is: " .$val; //Outputs "$currentrowid"
So, as you can see the code returns the actual name of the variable being passed, NOT the value of the variable being passed.
Any ideas here?
Since you are already within a PHP block, you should not wrap your variable within <?php ... ?>. This will give you an error.
To make this work, you can choose 1 of 2 options:
1) String Concatenation:
echo '... <form action="phpindex.php?page=edit&thisrow='.$currentrowid.'" method="post"> ...';
2) Wrap your string in " (double quotes) instead of ' (single quotes):
echo "... <form action=\"phpindex.php?page=edit&thisrow=$currentrowid\" method=\"post\"> ...";
Note that the second method forces you to escape all the double quotes inside of your string.
2 point.
<form action="index.php?thisrow=<?php echo $currentrowid ?>"
method="post">
You should use $_POST not $_GET to get the post value.
As what was answered above,
<form action="index.php?thisrow=<?php echo $currentrowid; ?>" method="post">
is correct.
The reason behind this is you are passing HTML and you have to use an echo from php to output to the html. Otherwise you just get exactly what you put, which is $currentrowid.
Not the easiest, but a quick way to solve your problem. Change your form method to get method="get">, then
$val = $_GET['thisrow'];

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