If I'm trying to execute the code below.
I get errors when the user isn't online on TS.
but I want it to return false is this possible somehow?
code:
$client = $ts3_VirtualServer->clientGetByName($input);
if ($client == true) {
$TSonline = "true";
}
else {
$TSonline = "false";
}
}
echo $TSonline;
Try something like this..
try {
$client = $ts3_VirtualServer->clientGetByName($input);
if ($client){
$tsOnline = true;
} else {
$tsOnline = false;
}
} catch (Exception $e) { // or whatever exception is available...
$tsOnline = false;
}
if ($tsOnline){
/* do your stuff */
}
Related
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;
}
}
Guys i have this code:
class Test {
public function __construct($valore) {
if ($valore != TRUE ) {
return false;
} else {
return true;
}
}
}
and in another page this:
$test = new Test("");
if ($test) {
echo "result is: TRUE";
} else {
echo "result is: FALSE";
}
Why is all the time true??
Sorry and thank you!
Constructors don't have return values. So if you want a to test that value you need to have a method do this for you.
class Test
{
private $valore;
public function __construct($valore) {
$this->valore = $valore;
}
public function test() {
return (bool) $valore;
}
}
$test = new Test("");
if ($test->test()) {
echo "result is: TRUE";
} else {
echo "result is: FALSE";
}
Demo
It's always true because the $test object is always NOT false, it's an object. The return value of the constructor isn't what you're testing.
class Test {
var $valore;
public function __construct($valore) {
if ($valore != TRUE ) {
$this->valore = false;
} else {
$this->valore = true;
}
}
}
$test = new Test(FALSE);
if ($test->valore === TRUE) {
echo "result is: TRUE";
} else {
echo "result is: FALSE";
}
I have a code Like this
function deletes2()
{
foreach ($_POST['selector'] as $id)
{
$this->retailer_model->deletes($id);
}
}
Now i want to echo message like
echo"success"; or "error"
How can i do this??
you need to return flag to check from function like
function deletes($id) {
// your queries
if query run suceess.
return true
else
return false;
}
then check in foreach
foreach ($_POST['selector'] as $id){
$return = $this->retailer_model->deletes($id);
if($return) {
echo "success";
}
else {
echo "error";
}
}
As per assumption. here will be condition:
function deletes2() {
$status = false;
foreach ($_POST['selector'] as $id){
$this->retailer_model->deletes($id);
$status = true;
}
if($status) {
return "success";
} else {
return "error";
}
}
If your foreach loop will execute then it will return success else will return error. Hope so you are finding such condition.
cheers.
im not sure on how i am going to explain this correctly.
I wanted a function to validate a string which i figured correctly.
But i want the function to return a boolean value.
And outside a function i need to make a condition that if the function returned false, or true that will do something. Here's my code.
i am not sure if this is correct.
<?php
$string1 = 'hi';
function validatestring($myString, $str2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
}
}
else {
return false;
}
}
if(validatestring == FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
EDIT : Now what if there are more than 1 condition inside the function?
<?php
$string1 = 'hi';
function validatestring($myString, $myString2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
return true;
}
else {
retun false;
}
}
else {
return false;
}
}
if(validatestring($myString, $myString2) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Functions need brackets and parameter. You dont have any of them.
This would be correct:
if(validatestring($myString) === false) {
//put some codes here
}
An easier and more elegant method would be this:
if(!validatestring($myString)) {
//put some codes here
}
<?php
$string1 = 'hi';
function validatestring($myString) {
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring($string1) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Sidenote, since empty() already returns false ,you could simplify by doing:
function validateString($string){
return !empty($string);
}
if(validateString($myString){
// ok
}
else {
// not ok
}
To make a check and test later:
$check = validateString($myString);
if($check){ }
There's no need to check == false or === false, the function already returns a boolean, it would be redundant.
store $string1 to $myString in the function
myString=string1
<?php
$string1 = 'hi';
function validatestring($myString) {
myString=string1;
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring() === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
This is a problem I come accross fairly regularly and I've never found / figured out a best practices situation. Exceptions are probably the way to go however the application I'm working makes no use of them so I'm trying to stick to the currently used methods.
What is the best way to lay out if statements, returns, messages etc. in the event that 3, 4, 5 or more different conditions are required to be checked and either an error message is set or the processing continues. Is it best practice to have all error checking physically at the start of the code?
Here's an example with some real-world type conditions.
function process($objectId,$userId,$newData)
{
$error = '';
if(($object = $this->getObject($objectId)) && $object->userOwnsObject($userId))
{
if($this->isValid($newData))
{
if($object->isWriteable())
{
if($object->write($newData))
{
// No error. Success!
}
else
{
$error = 'Unable to write object';
}
}
else
{
$error = 'Object not writeable';
}
}
else
{
$error = 'Data invalid';
}
}
else
{
$error = 'Object invalid';
}
return $error;
}
OR
function process($objectId,$userId,$newData)
{
$error = '';
if((!$object = $this->getObject($objectId)) && !$object->userOwnsObject($userId))
{
$error = 'Object invalid';
}
elseif(!$this->isValid($newData))
{
$error = 'Data invalid';
}
elseif(!$object->isWriteable())
{
$error = 'Object not writeable';
}
elseif(!$object->write($newData))
{
$error = 'Unable to write to object';
}
else
{
// Success!
}
return $error;
}
It's clear to me that in this case option 2 is the way to go. It's much clearer. Now, we can make it a bit more complex:
function process($objectId,$userId,$newData)
{
$error = '';
if(($object = $this->getObject($objectId)) && $object->userOwnsObject($userId))
{
$this->setValidationRules();
$parent = $object->getParentObject();
$parent->prepareForChildUpdate();
if($this->isValid($newData,$parent))
{
$newData = $this->preProcessData($newData);
if($object->isWriteable())
{
// doServerIntensiveProcess() has no return value and must be done between these two steps
$this->doServerIntensiveProcess();
if($object->write($newData))
{
// No error. Success!
$parent->childUpdated();
}
else
{
$error = 'Unable to write object';
}
}
else
{
$error = 'Object not writeable';
}
}
else
{
$error = 'Data invalid';
}
}
else
{
$error = 'Object invalid';
}
return $error;
}
OR this which has some issues with it
function process($objectId,$userId,$newData)
{
$error = '';
if((!$object = $this->getObject($objectId)) && !$object->userOwnsObject($userId))
{
$error = 'Object invalid';
}
// Is it wrong to hate multi-line conditionals?
elseif(!$this->setValidationRules() || (!$parent = $object->getParentObject()) ||
!$parent->prepareForChildUpdate() || !$this->isValid($newData,$parent))
{
$error = 'Data invalid';
}
elseif((!$newData = $this->preProcessData($newData)) || !$object->isWriteable())
{
$error = 'Object not writeable';
}
// Where does doServerIntensiveProcess() with no return value go??
elseif(!$object->write($newData))
{
$error = 'Unable to write to object';
}
else
{
// Success!
$parent->childUpdated();
}
return $error;
}
I'm just not sure of the best way to handle this nested if-this-then-do-that-then-if-this-then-do-that kind of functionality. Thank you indvance for any insight you can provide!
What I tend to do to keep code clean is like so:
function process($objectId,$userId,$newData)
{
$object = $this->getObject($objectId);
if($object === false)
{
return "message";
}
if($object->userOwnsObject($userId) === false)
{
return "message";
}
if($this->setValidationRules() === false)
{
return "unable to set validation rules";
}
if(false !== ($parent = $object->getParentObject()))
{
return "unable to get parent object";
}
/*... etc ...*/
//if your here the all the checks above passed.
}
by doing it this way your also saving resources as your your directly returning in place, the code looks cleaner and no need for 2 many nests
but if your building the function from scratch I don't see why you cant use exceptions in in your new code, it will not interfere with the current app, and makes live simpler
function process($objectId,$userId,$newData)
{
if(false !== ($parent = $object->getParentObject()))
{
throw Exception("unable to get parent object");
}
/*... etc ...*/
}
and
try
{
$this->process(....);
}
catch(Exception $e)
{
show_error_page('invalid.php',$e);
}
or another way is to create an error handling class with a static method called InternalError like so
abstract class Error
{
public static InternalError(Exception $Ex)
{
Logger::LogException($Ex);
//Then flush all buffers and show internal error,
}
}
so instead of of the show_error_page above you can do:
try
{
$this->process(....);
}
catch(Exception $e)
{
Error::InternalError($e); //this provides user with an interface to report the error that has just been logged.
}
this way all your Exception(s) are logged and can be viewed within your administration system, meaning you can track errors faster and not rely on members to visibly see errors, but get a nice apology with an email form asking them to describe what they was trying to do, the error ID will be attached to the form, so you can trace the user to the error.
That's the best form of error handling IMO.
What about this?
function process($objectId,$userId,$newData)
{
if((!$object = $this->getObject($objectId)) && !$object->userOwnsObject($userId))
return 'Object invalid';
elseif(!$this->isValid($newData))
return 'Data invalid';
elseif(!$object->isWriteable())
return 'Object not writeable';
elseif(!$object->write($newData))
return 'Unable to write to object';
// Success!
}
For the more complex example::
function process($objectId,$userId,$newData)
{
if(!($object = $this->getObject($objectId)) || !$object->userOwnsObject($userId))
return 'Object invalid';
$this->setValidationRules();
$parent = $object->getParentObject();
$parent->prepareForChildUpdate();
if(!$this->isValid($newData,$parent))
return 'Data Invalid';
$newData = $this->preProcessData($newData);
if(!$object->isWriteable())
return 'Object not writable';
// doServerIntensiveProcess() has no return value and must be done between these two steps
$this->doServerIntensiveProcess();
if(!$object->write($newData))
return 'Unable to write object';
// No error. Success!
$parent->childUpdated();
return '';
}
I would completely omit
if($object->isWriteable())
{
if($object->write($newData))
{
// ..
}
}
And throw Exceptions when calling object-write() (without a return value) instead. Same for the other examples
if ($something->isValid($data)) {
$op->doSomething($data); // throws XyException on error
}
If you really want to use such constructs, you can also use the swtch-Statement
switch (true) {
case !$something->isValid($data):
$errors = "error";
break;
// and so an
}
But I really recommend Exceptions.
I don't think it is wrong per se to write multi-line conditionals, but you can make it more readable by putting conditions into a variable and use that in your if-statment. I think the elseif constuct is better.