Saving to a file in PHP - 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";
}

Related

Update XML element text with PHP

I'm trying to update XML element text based upon a form submission. It is a userdatabase and im using the user's password as a reference to update their user id. The passwords all all unique so I thought it would be an easy element to reference. However whenever I attempt to edit a UID it fails and sends me to my error page I created if the function fails. Im not sure where I went wrong any assistance would be great.
Update UID Function
function updateUID($pass, $file, $new)
{
$xml = new DOMDocument();
$xml->load($file);
$record = $xml->getElementsByTagName('UniqueLogin');
foreach ($record as $person) {
$password_id = $person->getElementsByTagName('Password')->item(0)->nodeValue;
//$person_name=$person->getElementsByTagName('name')->item(0)->nodeValue;
if ($password_id == $password) {
$id_matched = true;
$updated = $xml->createTextNode($new);
$person->parentNode->replaceChild($person, $updated);
break;
}
}
if ($id_matched == true) {
if ($xml->save($file)) {
return true;
}
}
}
Code that calls the function
session_start();
include_once "includes/functions.inc.php";
include_once "includes/jdbh.inc.php";
include_once "includes/dbh.inc.php";
include_once "includes/ftpconn2.inc.php";
$file = $_SESSION['fileNameXML'];
if (file_exists($file)) {
if (isset($_POST['submit'])) {
$pass = $_POST['id'];
//$uid = $_SESSION['userid'];
$new = $_POST['uid'];
//$entry = getUsername($jconn, $uid)." deleted a server ban for".$name;
//if (isset($_GET['confirm'])) {
if (updateUID($pass, $file, $new)) {
//createLogEntry($conn, $uid, $entry);
if (1 < 2) { //This is intentional to get around the $message varible below that is not required.
$message = $affectedRow . " records inserted";
try {
$ftp_connection = ftp_connect($ftp_server);
if (false === $ftp_connection) {
throw new Exception("Unable to connect");
}
$loggedIn = ftp_login($ftp_connection, $ftp_user, $ftp_password);
if (true === $loggedIn) {
//echo "Success!";
} else {
throw new Exception('unable to log in');
}
$local_file1 = "HostSecurity.xml";
$remote_file1 = "HostSecurity.xml";
if (ftp_put($ftp_connection, $local_file1, $remote_file1, FTP_BINARY)) {
//echo "Successfully written to $local_file\n";
} else {
echo "There was a problem";
}
ftp_close($ftp_connection);
header("location: ../serverPasswords.php");
}
catch (Exception $e) {
echo "Failure:" . $e->getMessage();
}
}
header("location: ../serverPasswords.php");
} else {
header("location: ../serverPasswords.php?e=UIDNPD");
}
} else {
echo "id missing";
}
} else {
echo "$file missing";
}
<Unique_Logins>
<UniqueLogin>
<UID>AA23GHRDS657FGGRSF126</UID>
<Password>iMs0Az2Zqh</Password>
</UniqueLogin>
<UniqueLogin>
<UID>AA23GSDGFHJKDS483FGGRSF126</UID>
<Password>Ab7wz77kM</Password>
</UniqueLogin>
</Unique_Logins>
I believe the issue was caused by the undeclared variable $password in the logic test and the fact that the function never returns an alternative value if things go wrong.
As per the comment regarding XPath - perhaps the following might be of interest.
<?php
$pass='xiMs0Az2Zqh';
$file='logins.xml';
$new='banana';
function updateUID( $pass=false, $file=false, $new=false ){
if( $pass & $file & $new ){
$dom = new DOMDocument();
$dom->load( $file );
# attempt to match the password with this XPath expression
$expr=sprintf( '//Unique_Logins/UniqueLogin/Password[ contains(.,"%s") ]', $pass );
$xp=new DOMXPath( $dom );
$col=$xp->query( $expr );
# We have a match, change the UID ( & return a Truthy value )
if( $col && $col->length===1 ){
$xp->query('UID', $col->item(0)->parentNode )->item(0)->nodeValue=$new;
return $dom->save( $file );
}
}
# otherwise return false
return false;
}
$res=updateUID( $pass, $file, $new );
if( $res ){
echo 'excellent';
}else{
echo 'bogus';
}
?>
I'm still not clear on exactly what's wrong, but if I understand you correctly, try making these changes in your code and see if it works:
#just some dummy values
$oldPass = "Ab7wz77kM";
$newUid = "whatever";
$record = $xml->getElementsByTagName('UniqueLogin');
foreach ($record as $person) {
$password_id = $person->getElementsByTagName('Password');
$user_id = $person->getElementsByTagName('UID');
if ($password_id[0]->nodeValue == $oldPass) {
$user_id[0]->nodeValue = $newUid;
}
}

Login checks user and passowrd from json file(php). How to read file from json file

I have that problem that just throws me a mistake to try again, it doesn't check json file.
here is my php code:
<?php
if (isset($_SERVER["PHP_AUTH_USER"]) && isset($_SERVER["PHP_AUTH_PW"])) {
$json = file_get_contents("user-data.json");
$json_data = json_decode($json, true);
$user = $_SERVER["PHP_AUTH_USER"];
$pw = $_SERVER["PHP_AUTH_PW"];
$flag =false;
foreach ($json_data as $key => $value) {
if ($value['PHP_AUTH_USER'] == $user && $value['PHP_AUTH_PW'] == $pw) {
$flag = true;
**echo "<p>Pozdrav $user, unijeli ste $pw kao zaporku.</p>\n";**
break;
}
if($flag){
header('location: index.php');
} else {
http_response_code(401);
header("WWW-Authenticate: Basic realm=\"SECRET\"");
echo "<p>Try again.</p>\n";
}
}
}
here is my .json file
{
"user":"admin",
"password":"admin"
},
{
"user":"login",
"password":"login"
}
it just throws me a mistake to try again, it doesn't check json file.
Please add a pair of square brackets to enclose your "json data" , which contains an array of data (multiple username and password pairs).
Hence, the following will be one of a ways to get the username and password from the json data (I commented out the file_get_contents part and use a string to store it so that it is more straight forward)
<?php
//$json = file_get_contents("./user-data.json");
$json='[{
"user":"admin",
"password":"admin"
},
{
"user":"login",
"password":"login"
},
{
"user":"stackoverflow",
"password":"goodpassword"
}
]';
$json_data = json_decode($json, true);
foreach ($json_data as $key=>$getdata) {
echo $getdata["user"] . "-" . $getdata["password"];
echo "<hr>";
}
?>
See the result in this sandbox (click execute please):
https://wtools.io/php-sandbox/b7Qv
Hence, please amend the above code to perform comparison with $_SERVER["PHP_AUTH_USER"] and $_SERVER["PHP_AUTH_PW"] to suit your case.
So, change the block:
$user = $_SERVER["PHP_AUTH_USER"];
$pw = $_SERVER["PHP_AUTH_PW"];
$flag =false;
foreach ($json_data as $key => $value) {
if ($value['PHP_AUTH_USER'] == $user && $value['PHP_AUTH_PW'] == $pw) {
$flag = true;
**echo "<p>Pozdrav $user, unijeli ste $pw kao zaporku.</p>\n";**
break;
}
to
$user = $_SERVER["PHP_AUTH_USER"];
$pw = $_SERVER["PHP_AUTH_PW"];
$flag =false;
foreach ($json_data as $key=>$getdata) {
if ($user == $getdata["user"] && $pw == $getdata["password"]) {
$flag = true;
**echo "<p>Pozdrav $user, unijeli ste $pw kao zaporku.</p>\n";**
break;
}
}

PHP weird comparison

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';
}
}

PHP Issue - function output is 000

I've been trying to make a CLI application that logs Yahoo! messenger login dates/times for certain users using a third party, but this isn't really getting anywhere. Even though checking iself works when used individually, it does not seem to when using the while & foreach too. checkAvailability outputs "000". Could anyone please fix this and perhaps optimize it?
<?php
error_reporting(E_ALL);
$users[0] = "|59|62|157|85|218|78|135|43|63|145|151|173|157|93|107|90|84|129|140|110|55|28|210|212|80|128|252|127|15|192|223|154|177|39|129|191|62|17|113|236|2|168&t=0.23704720849047";
$users[1] = "|70|255|229|124|194|244|242|223|73|250|184|237|222|251|8|243|104|4|70|125|205|177|229|255|178|244|123|251|13|157|220|47|88|247|15|0&t=0.04614829820959876";
function checkAvailability($user){
$dataGot = file_get_contents("http://www.imvisible.ro/getstatus.php?id=".$user);
$fullText = explode("|", $dataGot);
$status_coded = $fullText[0];
echo $status_coded;
return $status_coded;
}
while(true) {
foreach($users as $user) {
$user['oldstatus'] = $user['status'];
if (checkAvailability($user) == "1" and $user['oldstatus'] != "online") {
$user['status'] = "online";
echo "online";
} elseif (checkAvailability($user) == "3" and $user['oldstatus'] != "invisible") {
$user['status'] = "invisible";
echo "invisible";
} elseif (checkAvailability($user) == "2" and $user['oldstatus'] != "offline") {
$user['status'] = "offline";
echo "offline";
} else {
$user['status'] = "error";
echo "error";
}
if ($user['status'] != $user['oldstatus']) {
echo $user." a fost detectat ca ".$user['status']." la ".date(DATE_RFC822).".\n";
}
}
sleep(60);
sleep(60);
}
An endless runing CLI application in PHP in not the best solution. Its better when you make a cronjob and run the script every one or every to minutes. Then you can store the status or what you need in a database or a file.
I have looked at your scripted and test the script:
<?php
error_reporting(E_ALL);
$users[0] = "|59|62|157|85|218|78|135|43|63|145|151|173|157|93|107|90|84|129|140|110|55|28|210|212|80|128|252|127|15|192|223|154|177|39|129|191|62|17|113|236|2|168&t=0.23704720849047";
$users[1] = "|70|255|229|124|194|244|242|223|73|250|184|237|222|251|8|243|104|4|70|125|205|177|229|255|178|244|123|251|13|157|220|47|88|247|15|0&t=0.04614829820959876";
function checkAvailability($user){
$dataGot = file_get_contents("http://www.imvisible.ro/getstatus.php?id=".$user);
$fullText = explode("|", $dataGot);
$status_coded = $fullText[0];
return $status_coded;
}
while(true) {
foreach($users as $key => $user) {
$userStatus[$key] = checkAvailability($user);
if(!isset($userStatusRet[$key]['oldstatus'])) {
$userStatusRet[$key]['oldstatus'] = '';
}
if(!isset($userStatusRet[$key]['status'])) {
$userStatusRet[$key]['status'] = '';
}
$userStatusRet[$key]['oldstatus'] = $userStatusRet[$key]['status'];
if ($userStatus[$key] == "1" and $userStatusRet[$key]['oldstatus'] != "online") {
$userStatusRet['status'] = "online";
echo "User ".$key.": online\n";
} elseif ($userStatus[$key] == "3" and $userStatusRet[$key]['oldstatus'] != "invisible") {
$userStats['status'] = "invisible";
echo "User ".$key.": invisible\n";
} elseif ($userStatus[$key] == "2" and $userStatusRet[$key]['oldstatus'] != "offline") {
$userStatusRet[$key]['status'] = "offline";
echo "User ".$key.": offline\n";
} else {
$userStatusRet[$key]['status'] = "error";
echo "User ".$key.": error\n";
}
}
sleep(5);
}
Its not the best solution but the problem in your case is, that you can't write in the $user output. I have made here a new variable with the user id as iterator. When you run the script you can see the output:
User 0: online
User 1: offline
User 0: online
User 1: error
User 0: online
User 1: offline

Making code more efficient and less a copy and paste

I've been working on a piece of code that that pulls the name of a guild and with it the information of boss/monsters said guild has killed in an online game. There are many many monsters in this game and every one has three difficulty settings. I have managed to get the code to do what i want however it has an enormous amount of copy and paste and ive only done about 1/5 of the total amount of enteries. I really cant think how to make this code less of a giant bloat. This is the code for just one monster for the 3 difficulty settings as you can see it's alot just for one. there are probably another 60 of these!. Can anybody help me understand better ways to do this. Thanks!
$sql = 'SELECT * FROM `phpbb_profile_fields_data`';
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result))
{
/////////////////////////////////// START - 8 MAN BONETHRASHER
$normal = '';
$hard = '';
$nightmare = '';
/////// START - CHECK NORMAL
if ($row['pf_kp_em_no_bonethr'] == '1')
{
$normal = ' <img src="/styles/subsilver2/theme/images/soap/no.png" />';
}
else if ($row['pf_kp_em_no_bonethr'] == '2')
{
$normal = '';
}
else if (is_null($row['pf_kp_em_no_bonethr']))
{
echo "Boss was set as NULL This should not happen!";
}
else
{
echo "Sosia messed up go hit him in the face.";
}
/////// END - CHECK NORMAL
/////// START - CHECK HARD
if ($row['pf_kp_em_ha_bonethr'] == '1')
{
$hard = ' <img src="/styles/subsilver2/theme/images/soap/ha.png" />';
}
else if ($row['pf_kp_em_ha_bonethr'] == '2')
{
$hard = '';
}
else if (is_null($row['pf_kp_em_ha_bonethr']))
{
echo "Boss was set as NULL This should not happen!";
}
else
{
echo "Sosia messed up go hit him in the face.";
}
/////// END - CHECK HARD
/////// START - CHECK NIGHTMARE
if ($row['pf_kp_em_kn_bonethr'] == '1')
{
$nightmare =' <img src="/styles/subsilver2/theme/images/soap/kn.png" />';
}
else if ($row['pf_kp_em_kn_bonethr'] == '2')
{
$nightmare = '';
}
else if (is_null($row['pf_kp_em_kn_bonethr']))
{
echo "Boss was set as NULL This should not happen!";
}
else
{
echo "Sosia messed up go hit him in the face.";
}
/////// END - CHECK NIGHTMARE
if ($normal == '' && $hard == '' && $nightmare == '')
{
}
else
{
$template->assign_block_vars('8m_bonethrasher', array(
'VAR1' => $row['pf_guild_name'],
'VAR2' => $normal,
'VAR3' => $hard,
'VAR4' => $nightmare,
));
}
}
$db->sql_freeresult($result);
I'm still slightly fuzzy at what you are trying to do, but I'll give helping you out a shot.
You could probably get away will creating a class that does all of this.
For example:
class checks {
public function checkBosses($normalBoss, $hardBoss, $nightmareBoss) {
$difficulties = array();
$difficulties['normal'] = array('boss' => $normalBoss);
$difficulties['hard'] = array('boss' => $hardBoss);
$difficulties['nightmare'] = array('boss' => $nightmareBoss);
foreach ($this->difficulties as $difficulty -> $boss) {
$this->difficulties[$difficulty]['result'] = checkDifficulty($boss['boss'], $difficulty);
}
$normal = $this->difficulties['normal']['result'];
$hard = $this->difficulties['hard']['result'];
$nightmare = $this->difficulties['nightmare']['result'];
if ($normal == '' && $hard == '' && $nightmare == '') {
return null;
} else {
return array(
'normal' => $normal,
'hard' => $hard,
'nightmare' => $nightmare,
);
}
}
protected function checkDifficulty($boss, $difficulty) {
if ($difficulty == 'normal') {
$image = ' <img src="/styles/subsilver2/theme/images/soap/no.png" />';
} else if ($difficulty == 'hard') {
$image = ' <img src="/styles/subsilver2/theme/images/soap/ha.png" />';
} else if ($difficulty == 'nightmare') {
$image = ' <img src="/styles/subsilver2/theme/images/soap/kn.png" />';
}
if ($boss == '1') {
return $image;
} else if ($boss == '2') {
return '';
} else if (is_null($boss)) {
echo "Boss was set as NULL This should not happen!";
} else {
echo "Sosia messed up go hit him in the face.";
}
}
}
Then all you would need to do is call:
$checkResult = checks::checkBosses($row['pf_kp_em_no_bonethr'], $row['pf_kp_em_ha_bonethr'], $row['pf_kp_em_kn_bonethr']);
if ($checkResult != null) {
$template->assign_block_vars('8m_bonethrasher', array(
'VAR1' => $row['pf_guild_name'],
'VAR2' => $normal,
'VAR3' => $hard,
'VAR4' => $nightmare,
));
}
If you can retrieve an array of bosses, you can do a foreach loop on them to run that same bit of code for each boss like this:
foreach ($bosses as $boss) {
//Full code to be repeated for each boss here
}

Categories