PHP weird comparison - php

I've got two inputs in registration form, one with login, one with password. After calling AJAX I'm trying to validate those data and I'm using function below:
function test_input($data) {
if( $data == $_POST["login"] && $data == "" ){
$GLOBALS["message"] .= "<p>Empty login.</p>";
return;
}
elseif( $data == $_POST["pwd"] && $data == "" ){
$GLOBALS["message"] .= "<p>Empty password.</p>";
return;
}
echo 'Good job.';
}
When I click submit button without writing anything I've got answer:
Empty login
Empty login
When I write something in one of them or both of them validation's ok. Why?
Edit - Missing code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$login = test_input($_POST["login"]);
$pwd = test_input($_POST["pwd"]);
if($message!= ""){
echo $message;
}
else{
echo 'OK';
}
}

Perhaps refactor it something like:
function test_input($data, $field) {
if( $field == "login" && $data == "" ){
return "<p>Empty login.</p>";
}
elseif( $field == "pwd" && $data == "" ){
return "<p>Empty password.</p>";
}
echo 'Good job.';
}
and
$message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$message .= test_input($_POST["login"], "login");
$message .= test_input($_POST["pwd"], "pwd");
if($message!= ""){
echo $message;
}
else{
echo 'OK';
}
}

Related

PHP unreachable if statement in foreach

I have this code I have set up that is supposed to read from JSON and output each array. Except when I use my foreach loop, I have an unreachable if statement. It's supposed to reach it if "type" is "rawbr".
I have confirmed that this has nothing to do with foreach by placing the same message in a row.
I wish to output this:
UnknownUser3: hey hxor? [To you]
Welcome to chat!
Here is my code:
innerchat.php:
<?php
session_start();
function tf($oz){
if($oz == 0){
return false;
} else if($oz == 1){
return true;
}
}
if(isset($_GET["room"]) && file_exists("data/".$_GET["room"].".json")){
$jsonF = file_get_contents("data/".$_GET["room"].".json");
$jsonD = json_decode($jsonF, true);
echo count($jsonD["msg"]);
// echo $jsonD["msg"][1]["type"];
foreach($jsonD["msg"] as $key => $message){
if($message["visibility"] !== "all"){
if(isset($_SESSION["ts_user"]) && $_SESSION["ts_user"] == $message["visibility"] && $message["type"] != "rawbr"){
echo "<font color='".$message["color"]."'><b><u>".$message["from"].":</u></b></font> ".htmlspecialchars($message["cont"])." [To you]<br />";
} else if($message["type"] === "message" && $message["visibility"] === "all"){
echo "<font color='".$message["color"]."'><b><u>".$message["from"].":</u></b></font> ".htmlspecialchars($message["cont"])." [normal message]<br />";
} else if($message["type"] === "rawbr" && $message["visibility"] === "all"){
echo $message["cont"]."<br />";
}
}
}
}
kb6k.json (the room we're working with)
{"name":"KillerBot 6000","desc":"A room with very harsh moderation. Proceed with caution!","max":600,"color":"#e0e0e0","whispersenabled":true,"forbiddenCommands":["/milk", "/bal"],"msg":[{"cont":"hey, hxor?","time":1,"color":"black","type":"message","visibility":"HxOr1337","from":"UnknownUser1"},{"cont":"Welcome to the chat!","time":0,"type":"message","color":"black","visibility":"HxOr1337","from":"Test"}]}
I know it couldn't possibly do anything to do with the JSON itself, since the other values are nearly identical apart from "visibility"
Ok, so I figured out that I put those if statements in $message["visibility"] !== "all"
The code:
<?php
session_start();
if(isset($_GET["room"]) && file_exists("data/".$_GET["room"].".json")){
$jsonF = file_get_contents("data/".$_GET["room"].".json");
$jsonD = json_decode($jsonF, true);
// echo $jsonD["msg"][1]["type"];
foreach($jsonD["msg"] as $key => $message){
if($message["visibility"] !== "all"){
if(isset($_SESSION["ts_user"]) && $_SESSION["ts_user"] == $message["visibility"] && $message["type"] != "rawbr"){
echo "<font color='".$message["color"]."'><b><u>".$message["from"].":</u></b></font> ".htmlspecialchars($message["cont"])." [To you]<br />";
}
} else {
if($message["type"] === "message" && $message["visibility"] === "all"){
echo "<font color='".$message["color"]."'><b><u>".$message["from"].":</u></b></font> ".htmlspecialchars($message["cont"])." [normal message]<br />";
} else if($message["type"] === "rawbr" && $message["visibility"] === "all"){
echo $message["cont"]."<br />";
}
}
}
}

How do I let an error-message only appear after the $_POSTS are sent?

On a blog I'm coding the admin can edit existing posts.
I want to let an error-message appear when the $_POST['title'] for e.g is empty(There will be displayed:"Your post should have a title"). I also do it if the subheading, content or category are empty.
The errors work just fine if one or some of them is/are empty. As soon I load the page to edit a post every error is displayed from the beginning.
How do I make them only appear when one or some $_POST's are empty after the <input type="submit .../> is clicked (they shouldn't be there when the site has loaded)?
This is the function in the PostsAdminController.php that checks the $_POST's and renders the site:
public function edit()
{
$error = "";
$id = $_GET['id'];
$entry = $this->postsRepository->find($id);
$categoryFId = $this->categoryRepository->getOneCatFromId($entry->c_Id);
$savedSuccess = false;
$abort = false;
if ($this->loginService->check()) {
if (!empty($_POST['title'])) {
$entry->title = $_POST['title'];
} else {
$error .= "Your post should have a title.";
$abort = true;
}
if (!empty($_POST['subheading'])) {
$entry->subheading = $_POST['subheading'];
} else {
$error .= "A good subheading is nothing you should just leave out.";
$abort = true;
}
if (!empty($_POST['content'])) {
$entry->content = $_POST['content'];
} else {
$error .= "Your post should have content, you know, it wouldn't be a 'post' then.";
$abort = true;
}
if (!empty($_POST['category'])) {
$entry->c_Id = $_POST['category'];
}
if ($abort == false){
$this->postsRepository->update($entry);
$savedSuccess = true;
}
} else {
$error = "You have no permission to do this, how the hell did you get here?";
}
$this->render("post/admin/edit", [
'entry' => $entry,
'error' => $error,
'savedSuccess' => $savedSuccess,
'categoryFId' => $categoryFId
]);
}
I really hope someone can help me with this, I don't know what I could to to let them only disappear when the POSTS have already been send..
You have to check if there was a POST action use:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
in your case
...
if ($this->loginService->check()) {
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['title'])) {
...
}
}
}

complete form validation in php

I have this php code associated with a database and I need here to make a complete email and name validation
based on this code how can I do that because my code has some issues here
1)name key doesn't have (//) or any symbols to be a correct name
2)email key is valid email because what we did here just make ensure that there is # symbol and if I type the email hhhh#hhh.com or even without( .com ) it will be valid also ?!!
if(array_key_exists("submit",$_POST)){
$link = mysqli_connect("localhost","root","123456789","users");
if(mysqli_connect_error()){
die("There is a problem in connecting to database");
}
if(!$_POST['name']){
$error .="<p>Your Full name is required</p><br>";
}
if(!$_POST['email']){
$error .="<p>Your email address is required</p><br>";
}
if(!$_POST['password']){
$error .="<p>Your password is required</p><br>";
}
if($error !=""){
$error = "<p>There were errors in your form</p><br>".$error;
}
}
You can use this function for the validation:
function filtervariable($string,$type,$method) {
//function for sanitizing variables using PHPs built-in filter methods
$validEmail = false;
if ($method == 'sanitize') {
$filtermethod = 'FILTER_SANITIZE_';
} elseif ($method == 'validate') {
$filtermethod = 'FILTER_VALIDATE_';
} else {
return;
}
switch ($type) {
case 'email':
case 'string':
case 'number_int':
case 'int':
case 'special_chars':
case 'url':
$filtertype = $filtermethod.strtoupper($type);
break;
}
if ($filtertype == 'FILTER_VALIDATE_EMAIL' && !empty($string)) {
list($local,$domain) = explode('#',$string);
$localLength = strlen($local);
$domainLength = strlen($domain);
$checkLocal = explode('.',$domain);
if (($localLength > 0 && $localLength < 65) && ($domainLength > 3 && $domainLength < 256) && (checkdnsrr($domain,'MX') || checkdnsrr($domain,'A') || ($checkLocal[1] == 'loc' || $checkLocal[1] == 'dev' || $checkLocal[1] == 'srv'))) { // check for "loc, dev, srv" added to cater for specific problems with local setups
$validEmail = true;
} else {
$validEmail = false;
}
}
if (($filtertype == 'FILTER_VALIDATE_EMAIL' && $validEmail) || $filtertype != 'FILTER_VALIDATE_EMAIL') {
return filter_var($string, constant($filtertype));
} else {
return false;
}
}
And use it like this:
$email = filtervariable($registeremail,'email','validate');
It will return "true" on success and "false" on failure.

Saving to a file in PHP

I have to save unique passwords and usernames to a file, but my code duplicate the first two entries, then start working properly from there. here's my code. What am I missing? I using Mac with MAMP. I'm testing the code using curl with this command curl -d login=tenten -d passwd=peter -d submit=OK 'http://localhost:8080/php/create.php'
function user_exist($user_array, $user_name)
{
foreach ($user_array as $user) {
if ($user['login'] === $user_name)
return (TRUE);
}
return (FALSE);
}
if ($_POST['submit'] === 'OK')
{
if ($_POST['passwd'] != "" && $_POST['login'] != "")
{
create_file('../private');
if (file_exists('../private/passwd'))
{
$hash_passwd = hash('whirlpool', $_POST['passwd']);
$passwds = unserialize(file_get_contents('../private/passwd'));
if (!user_exist($passwds, $_POST['login']))
{
$passwds[] = array('login' => $_POST['login'], 'passwd' => $hash_passwd);
$serialize = serialize($passwds);
file_put_contents('../private/passwd', $serialize);
echo "OK\n";
}
else
{
echo "ERROR\n";
}
}
else
{
$hash_passwd = hash('whirlpool', $_POST['passwd']);
$user_cred = array('login' => $_POST['login'], 'passwd' => $hash_passwd);
$serialize = serialize($user_cred);
file_put_contents('../private/passwd', $serialize);
echo "OK\n";
}
}
else
{
echo "ERROR\n";
}
}
else
{
echo "ERROR\n";
}

Email validation, Am I doing the right thing?

I am writing some PHP code where I end it with a email validation checking. Can someone review it and confirm if it's a good solution?
<?php
function isTrue($var) {
return (isset($var)) ? TRUE : FALSE;
}
function len($str) {
$i;
for($i=0; isTrue($str[$i]); $i++) {
/* count me */
}
return $i;
}
function parsMe($str) {
$at; $dot; $isvalid=0; $isnotvalid=0;
for ( $at=0; isTrue($str[$at]); $at++) {
if ( $str[$at] == "#" ) {
for ( $dot=$at+1; isTrue($str[$dot]); $dot++ ) {
if ( $str[$dot] == "." ) $isvalid += 1;
if ( $str[$dot] =="#" || $str[len($str)-1] == "#" || $str[len($str)-1] == "." ) {
die("Error email entered");
}
}
}
if ( $str[$at] != "#" ) {
$isnotvalid+=1;
}
}
/* exit cond */
if ( $isnotvalid == len($str) ) die("Error mail usage");
else if ( $isvalid == 0 ) die("Error mail");
else echo "Mail is OK ";
}
$eml = "dotdot#com.";
parsMe($eml);
?>
parsMe() should produce error.
There are built in functions for checking validity of emails:
<?php
$email ='dotdot#com';
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "E-mail is not valid";
}else{
echo "E-mail is valid";
}
?>

Categories