I started learning PHP 1 week ago, i'm making some form tests to get more apprehension on the language, i get stuck in problem small problem for you guys....
I used in_array function from the PHP manuale to check an array off names at login
The function did not work to check the array tell i add !in_array !!!
Normal in_array did not work to check for names ...
So I used blaindly the operator "!" in front of the function, so why did it work with that operator and not without it ?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Forum</title>
<meta name="Nic" content="" />
<link rel="stylesheet" type="text/css" href="style.css"> </head>
<body>
<?php
if(isset($_POST['submit'])){
$names = array("Nicolaus", "Solo", "Yiu", "Yang", "Darius");
$minimum = 5;
$maximum = 10;
$username = $_POST['username'];
echo '<br>';
$password = $_POST['passwoard'];
if(strlen($username) < $minimum){
echo 'Username needs to be longer then 5 carcaters !';
}
if(strlen($username) > $maximum){
echo "Username can't be longer then 10 carcaters";
}
if(!in_array($username, $names)){
echo "You are not alowed , not in database !";
} else {
echo 'Welcome';
}
echo '<br>';
echo 'Your Username is : ' . "<b>" . $username . '</b>';
echo ' Your Password is : ' . "<b>" . $password . '</b>';
}
?>
<form action="my_from.php" method="post">
<input type="text" name="username" placeholder="username">
<input type="password" name="passwoard" placeholder="password">
<input type="submit" name="submit"> </form>
</body>
Ty
! means NOT, its an operator to make comparisons when you want to check if something is false.
$raining = false;
if (!$raining){
echo "its not raining";
}
Now that you posted your code:
if(!in_array($username, $names)){
echo "You are not allowed , not in database !";
} else {
echo 'Welcome';
}
in_array is a function that checks if some value is inside an array. You are testing if $username is inside $names array.
Your conditional checks if $username is NOT in array, if so, it means that $username is not allowed because it doesn't make part of the permitted $names.
Your ELSE clause identify that it is in the array, and then the user is able to login.
you can invert your logic:
if(in_array($username, $names)){
echo 'Welcome';
} else {
echo "You are not allowed , not in database !";
}
And it will work as well.
! symbol is used for negating the logic of the function.
What you actually want to do is, you want to reject an user with $username, if his/her name is NOT in the $names array. You have got a function to check whether an element is present in an array. So adding ! operator to it negates the logic.
if (!in_array($username, $names))
That means if the $username is NOT present in array $names.
Using ! is similar to checking with condition == FALSE. But we can't directly use that logic on that function so we opted for ! operator.
Another alternative for your example without ! is,
if (in_array($username, $names)) {
echo "Welcome";
} else {
echo "You are not alowed , not in database !";
}
Hope this helps! :)
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'm trying to add the parameter cs with a value of 1 to the url using a form and hidden type input. When I execute this, I have a simple if statement that checks to see if $_GET['cs'] is = to 1, but I get a Notice: Undefined index. I'm a php beginner, any help, explanations, or alternatives is very much appreciated.
echo '<form>';
echo '<input type="hidden" name="cs" value="1">';
echo '</form>';
if($_GET['cs'] == 1) {
echo'working';
}
else {
echo 'not working';
}
Only after form is submitted you will see 'cs' in $_GET array.
The $_GET array contains all parameters on the URL line.
For example if a URL is: https://example.com?param1=1¶m2=2
You will get a $_GET array with two entries ('param1' and 'param2') with values 1 and 2.
You should add a check using the isset function (https://www.php.net/manual/en/function.isset.php). Otherwise it will try to access the parameter if it isn't sent. In your case the parameter was probably not sent.
Url in html:
test the get method
The url test
<?php
if ($_GET['varaible'] == true) {
$varaible = 'Its work';
$value = false;
}else{
$varaible = 'Oooppss';
$value = true;
}
echo $varaible . '<br>';
?>
Full code:
<?php
if ($_GET['varaible'] == true) {
$varaible = 'Its work';
$value = false;
}else{
$varaible = 'Oooppss';
$value = true;
}
echo $varaible . '<br>';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>get varaible</title>
</head>
<body>
test the get method
</body>
</html>
//So i have a php validation external and a html file. I'm trying to validate if //the input boxes are filled out correctly... so far i have one but I can't get it //to run and i tried testing it out doesn't work... do i need to download //something or is my code completely wrong. I just trying to check if its empty and if it has at least 3 characters
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cal5t</title>
</head>
<body>
<?php
$title= $_REQUEST["title"];
if ($title == "" or >3 ) {
echo "<p>5please!</p>";
?>
</body>
</html>
You are probably looking for something like:
if (($title == "") or (strlen($title) < 5))
{
echo "<p>5please!</p>";
}
if(!empty($title= $_POST['title']) && strlen($title) > 5){
echo "valid: $title";
} else {
echo "incorrect title: '$title'";
}
Also, its beter to use $_POST or $_GET over $_REQUEST.
I think you're looking for:
if(strlen($title) < 5){
echo '<p>The title you entered is not long enough.</p>";
}
You can make sure there is a value with the isset() function.
requird validation
$title = trim($_POST['title']); // it will remove stat and end spaces
if(strlen($title) <= 0)
{
echo "Title Field is required";
}
So I have a calculator coded in PHP and I have validated it but there is a problem with this, its not working. I have used server side validation. Validation works well. But it doesn't do any work,for example, when I give an input like 2+8, it gives an output of 8888. This is very confusing. Please help me out with this. Thanks.
HTML page is here:
<html>
<head>
<title>Calculator</title>
</head>
<body>
<form method = "post" action = "calc.php">
<input type = "text" name = "val_1"/>
<select name="operator">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type = "text" name = "val_2"/>
<input type = "submit" value = "calculate" name = "checker"/>
</form>
</body>
</html>
And here is the PHP code.
<?php
if(isset($_POST['checker'])) {
#Clean all values
function cleanStr($str){
$str = trim($str);
$str = addslashes($str);
$str = htmlspecialchars($str);
return $str;
}
$val_1=cleanStr($_POST['val_1']);
$val_2=cleanStr($_POST['val_2']);
$operator=$_POST['operator'];
function emptyFileds($ar){
if(!is_array($ar)){
echo "It must be an array";
return false;
}
#loop through each field to check for empty values
foreach($ar as $key => $value){
$value = CleanStr($value);
if(empty($value)){
echo $key . " must not be empty";
return false;
}
}
return true;
}
if(!emptyFileds($_POST)){
exit();
}
if($operator==="+"){
echo "Sum is " . $val_1+$val_2;
}
}
?>
Please change the original line
echo "Sum is " . $val_1+$val_2;
to
echo "Sum is " . ($val_1+$val_2);
It's a operator precedence issue as . is executed first. Therefore you append 2 to "Sum is " and then increment the string by 8 which results in this odd behavior.
Also, some nitpicking on your code, I will just name 3 issues:
requesting a parameter with cleanStr() is not a good idea, it's better to use
$val_1 = (int)trim($_POST['val_1']);
as $val_1 will be an integer after that line. This might be important for later development e.g. to compare numbers.
indent correctly, reading your code is hurting my eyes
the whole emptyFileds()thing is unnecessary, simply check whether the 3 parameters are filled or not, it's simple and it's readable.
I'm making a simple guestbook script in php. I pretty much have it finished but need help finding the logic errors in my code. One is that when echoing the results from the form content. I am wanting to display the email, whole name and comment, each on different lines.
like this
email: some#email.com
Name: joe somebody
Comment:
hello world.
but for some reason it just displays the first and last name on all lines.
the other 3 issues are sorting(ascending, descending) and removing duplicates.
Thanks in advance for your advice on how to fix this.
I just ask you be detailed so i know what you are talking about.
In any case, heres the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Guest Book</title>
</head>
<body>
<?php
// is there data in the fields
if (isset($_POST['submit'])){
$firstName = addslashes($_POST['first_name']);
$lastName = addslashes($_POST['last_name']);
$wholeName = $firstName . "," . $lastName;
$email = addslashes($_POST['email']);
$comment = addslashes($_POST['comment']);
$guestRecord = "$wholeName~$email~$comment\n";
$guestBook = fopen("guestbook.txt", "ab");
//if not let the user know
if ($guestBook === FALSE)
echo "There was an error saving your entry!\n";
else {
// if there is info add it to the txt file
fwrite($guestBook, $guestRecord);
// close the txt file
fclose($guestBook);
//let the user know info was saved
echo "Your entry has been saved.\n";
}
}
?>
<h2>Enter your name to sign our guest book</h2>
<hr>
<form method="POST" action ="GuestBook1.php">
<p>First Name<input type ="text" name="first_name"/></p>
<p>Last Name<input type ="text" name="last_name"/></p>
<p>Email<input type ="text" name="email"/></p>
<p><textarea name="comment" id="comment"/></textarea></p>
<p><input type ="submit" value ="Submit" name="submit"/></p>
</form>
<hr>
<p>Show Guest Book
<br />
Delete Guest Entry
<br />
Remove Duplicate Entries
<br />
Sort Entries A-Z
<br />
Sort Entries Z-A
<br />
</p>
<?php
// if theres info in the form process info
if (isset($_GET['submit'])) {
if ((file_exists("guestbook.txt")) &&
(filesize("guestbook.txt") != 0)) {
$guestArray = file("guestbook.txt");
//switch to $_Get Method
switch ($_GET['submit']) {
// remove duplicate entries
case 'Remove Duplicates':
$guestArray = array_unique($guestRecord);
$guestArray = array_values($guestRecord);
break;
//sort ascending
case 'Sort Ascending':
$guestArray = sort($guestArray);
break;
//sort Decending
case 'Sort Decending':
$guestArray = ksort($guestArray);
break;
}
//count to see how many entries there are
if (count($guestArray)>0) {
$newGuest = implode($guestArray);
$guestStore = fopen("guestbook.txt", "ab");
if ($guestStore === false)
echo "There was an error updating the message file\n";
else {fwrite($guestStore, $newGuest);
fclose($guestStore);
}
}
else
unlink("guestbook.txt");}
}
if ((!file_exists("guestbook.txt")) ||
(filesize("guestbook.txt") == 0))
echo "<p>There are no entries.</p>\n";
else {
// there isnt anything in the txt file show an error
if ((!file_exists("guestbook.txt")) ||
(filesize("guestbook.txt") == 0))
echo "<p>There are no entries.</p>\n"; else {
//if there is information display the txt file in a table
$guestArray = file("guestbook.txt");
echo "<table style=\"background-color:lightgray\"
border=\"1\" width=\"100%\">\n";
//begin counting number of guest entries
$count = count($guestArray);
for ($i = 0; $i < $count; ++$i) {
$currMsg = explode("~", $guestArray[$i]);
// display results in a table
echo "<td width=\"5%\" style=\"text-align:center;
font-weight:bold\">" . ($i + 1) . "</td>\n";
echo "<td width=\"95%\"><span style=\"font-weight:bold\">
Email:</span> " . htmlentities($currMsg[0]) . "<br />\n";
echo "<span style=\"font-weight:bold\">Name:</span> " .
htmlentities($currMsg[0]) . "<br />\n";
echo "<span style=\"text-decoration:underline;
font-weight:bold\">Comment</span><br />\n" .
htmlentities($currMsg[0]) .
"</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
}
}
?>
</body>
</html>
$firstName = addslashes($_POST['first_name'])."\r\n";
The \r\n\ will put things physically on a new line. Make sure to use double quotes.
Regarding your first issue, you are echoing $currMsg[0] for all of the fields. You need to use the correct index for each of the values (0 for name, 1 for email, 2 for comment). Or even better, use something like:
list($name, $email, $comment) = explode("~", $guestArray[$i]);
That way you have meaningful variable names.
The other issues you'll need to be more specific as to what you're trying to do (and in what way your current code isn't working).
I can see at least one issue though - your links have ?action= but your switch statement is looking at $_GET['submit'], not $_GET['action']. Plus you have a typo in case 'Sort Decending': (missing 's')