I'm first checking if a function returns a valid result, and then, if the result is valid, I need to use that in my script. But instead of checking once, and then coming back again to the function for its result, is there a way to do it all in one go? Here, $strVal is the variable I need to use in an querystring later.
$conn = connect();
encrypt('HIs#$%.-','x');
decrypt('6507A27EB0521AFA0776F1A4F8033041','x');
//If the function returns a valid result,
if (encrypt('Tom','x'))
{
echo 'Success'.$strVal;//I'll use this in a querystring later.
}
else
{
echo 'An error occurred';
}
//Encrypt string
function encrypt($strToEncrypt,$salt)
{
global $conn;
$elements = $conn->prepare("select hex(aes_encrypt(:what,:salt)) as encValue");
$elements->bindParam(':what', $strToEncrypt);
$elements->bindParam(':salt', $salt);
$elements->execute();
$row = $elements->fetch();
$strVal = $row['encValue'];
if(is_null($strVal)){return false;}else{return $strVal;}
}
//Decrypt string
function decrypt($strToDecrypt,$salt)
{
global $conn;
$elements = $conn->prepare("select aes_decrypt(unhex(:what),:salt) as decValue");
$elements->bindParam(':what', $strToDecrypt);
$elements->bindParam(':salt', $salt);
$elements->execute();
$row = $elements->fetch();
if(is_null($row['decValue']))
{echo "Null";}else{echo $row['decValue'];}
}
Yes, you could do the variable assignment inside the condition:
/* single 'equal' operator intended */
if( $strVal = encrypt( 'Tom', 'x' ) )
{
echo 'Success' . $strVal;
}
Related
I am trying to check whether a generated string is in my database table or not.
If there is no duplicate I want to return and save it.
If there is a duplicate I want to generate a new string and save it
currently this function does not return me the generated token:
public function checkForHashDuplicate($string)
{
$newToken = '';
$inquiries = DB::table('inquiries')->get();
foreach($inquiries as $inquiryKey => $inquiryValue)
{
while($inquiryValue->android_device_token == $string)
{
$newToken = generateAlphanumericString();
if($newToken != $inquiryValue->android_device_token)
{
return $newToken;
}
}
}
}
$inquiry->android_device_token = $this->checkForHashDuplicate($hash);
A simplified version of your code is:
public function checkForHashDuplicate($string)
{
do {
// generate token
$newToken = generateAlphanumericString();
// find token in a DB
$duplicate = DB::table('inquiries')
->where('android_device_token', '=', $newToken)->first();
// if token is FOUND `$duplicate` has truthy value
// and `do-while` keeps running
// else `$duplicate` is falsy and `do-while` breaks
} while ($duplicate);
return $newToken;
}
Instead of using:
$inquiries = DB::table('inquiries')->get();
and loop, use where like:
$inquiries = DB::table('inquiries')->where('android_device_token', '=', $string)->get();
if( count($inquiries ) == 1 )
{
// found
}
else
{
// Not found, generate new one
}
You can check like this:
public function checkDuplicate($string){
$count = DB::table('inquiries')->where('android_device_token',$string)->count();
if($count==0){
// $string exists
return generateAlphanumericString();
}else{
// $string doesn't exists
return $string;
}
}
Now, use this function to assign value of $string or new token as
$inquiry->android_device_token = $this->checkForHashDuplicate($hash);
Hope you understand.
I wanted to make a login script for my program but its not working. The error is on the bind_param.
Can you please explain why it's not working and teach me how to do it right?
Code:
<?php
$username = $_GET['username'];
$key = $_GET['key'];
$hwid = $_GET['hwid'];
$istKorrekt = istKorrekterSchluessel($username, $key, $hwid);
if($istKorrekt) {
echo 'true';
} else {
echo 'false';
}
mysqlTrennen();
function mysqlVerbinden() {
global $mysqlVerbindung;
$mysqlHost = "localhost";
$mysqlBenutzer = "ts3botauth";
$mysqlPasswort = "nope";
$mysqlDatenbank = "ts3botauth";
$mysqlTabelle = "ts3botauth";
$mysqlVerbindung = new mysqli($mysqlHost, $mysqlBenutzer, $mysqlPasswort, $mysqlDatenbank);
if($mysqlVerbindung->connect_errno)
return false;
return true;
}
function mysqlTrennen() {
global $mysqlVerbindung;
$mysqlVerbindung->close();
}
function istKorrekterSchluessel($username, $key , $hwid) {
global $mysqlVerbindung;
$mysqlTabelle = "ts3botauth";
$stmtPruefung = $mysqlVerbindung->prepare("SELECT EXISTS(SELECT * FROM " . $mysqlTabelle . " WHERE `Key`=? AND `Username`=? AND `HWID`=?) AS schluesselKorrekt");
if(!$stmtPruefung) {
return false;}
$stmtPruefung->bind_param("s",$username);
$stmtPruefung->bind_param("s", $key);
$stmtPruefung->bind_param("s", $hwid);
$stmtPruefung->execute();
$stmtPruefung->bind_result($schluesselKorrekt);
$stmtPruefung->fetch();
return ($schluesselKorrekt == 1);
}
?>
That's not how bind_param works in mysqli. Maybe you were thinking of PDO? In mysqli you have to bind them all at once with one statement.
$stmtPruefung->bind_param("sss",$username, $key, $hwid);
Line 64 will be $stmtPruefung->bind_param("s",$username);, and you're getting that "Number of variables doesn't match" error because it's expecting all three and you're giving it one.
i have this inside a php function:
$result = new stdClass();
$result->domainname = $domainName;
$result->element = $element;
$result->availability = $availability;
return ($result);
so its returning all of the values in the $result variable
when i do a print_r on the function, the results display like this:
stdClass Object
(
[domainname] => domain.com
[element] =>
[availability] => false
)
i am calling the function with this code:
$domain = domainNameCheck($_GET["domain"].'.'.$_GET["tld"]);
so i tried to get the returned by doing $domain->availability but its not returning the value, example:
if($domain->availability) {
echo 'yes';
} else {
echo 'no';
}
am i trying to get the data the incorrect way?
UPDATE
the full function is:
if(!function_exists("domainNameCheck")) {
function domainNameCheck($domainName, $element) {
$result = '';
$client = new IcukApiClient();
$client->username = "username";
$client->key = "pass";
$client->encryption = "SHA-512";
$req = new IcukApiRequest();
$req->url = "/domain/availability/" . $domainName;
$req->method = "GET";
$res = $client->send($req);
$availability = 'unknown';
if ($res->success) {
$obj = json_decode($res->response);
$availability =($obj->available) ? 'true' : 'false';
}
else {
$availability = 'unknown';
}
$result = new stdClass();
$result->domainname = $domainName;
$result->element = $element;
$result->availability = $availability;
return ($result);
}
}
Your main problem seems to be that you are calling a function with 2 parameters but passing only one parameter
function domainNameCheck($domainName, $element) {}
// called like this (one parameter)
$domain = domainNameCheck($_GET["domain"].'.'.$_GET["tld"]);
This should be generating a compile error!
Also here
if ($res->success) {
$obj = json_decode($res->response);
// check what $obj->available is set to
// it may also be a string and not a boolean
print_r($obj);
$availability =($obj->available) ? 'true' : 'false';
}
else {
$availability = 'unknown';
}
Please note that there are two error/warning messages PHP is giving:
E_WARNING : type 2 -- Missing argument 2 for domainNameCheck()
E_NOTICE : type 8 -- Undefined variable: element
You should fix those errors, and make sure you are informed of errors during development.
Secondly, you have defined your availability as a string by assigning "false", "true", or "unknown". So when you do this:
if($domain->availability) {
... that will be true for all three values, because strings are true for PHP when converted to boolean (except when empty). To illustrate, this will echo "hello":
if ("false") echo "hello";
So you need to change your test like this:
if($domain->availability === "true") {
Or, If you want to define $domain->availability as a true boolean, then you need to alter the assignments in your function, like this:
....
$availability = $obj->available; // assuming that is a boolean!
}
else {
$availability = null; // unknown
}
... and then you can do what you had:
if($domain->availability) {
Likely because $domain->availability is boolean
To output you can first check whether its true or false and output accordingly
here's a simple example:
if ($domain->availability){
echo 'Available';
}
else {
echo 'Not Available';
}
i think i need a second pair of eyes.
I have some ajax calling a php file, and it's returning json. This all works fine. I'm then alerting the data elements i return for testing purposes. In doing this i narrowed down my function is not being called.
<?php
// database functions
$response = array();
$count = 1;
// connect to db
function connect() {
$response['alert'] = 'connect ran'; // does not get alerted
}
// loop through query string
foreach ($_POST as $key => $value) {
switch ($key) {
case 'connect':
$response['alert'] = 'case ran';
if ($value == 'true') {
$response['alert'] = 'if ran'; // this is what gets alerted, should be overwriten by 'connect ran'
connect(); // function call does not work?
} else {
$response['alert'] = 'false';
$mysqli->close();
}
break;
case 'otherstuff':
break;
}
++$count;
}
$response['count'] = $count;
echo json_encode($response);
?>
Any ideas? Thanks.
your $response variable is out of scope.. use global keyword inside your function to registering your outer variable(s)
function connect() {
global $response;
$response['alert'] = 'connect ran';
}
or SDC's edit:
function connect($response) {
$response['alert'] = 'connect ran';
}
connect($response);
actually you defined the result variable but in another type and you also have another result variable at the top so you put data in $result[] but you try to use $result so your code may not give you the expected result.
I have 2 classes that return a json encoded array if an error message is added to the $_error array:
Validate.class.php:
public function showResponse()
{
if(!empty($this->_error)) {
return json_encode($this->_error);
}
else {
return true;
}
}
UserTools.class.php:
public function showResponse()
{
if(!empty($this->_error)) {
return json_encode($this->_error);
}
else {
return true;
}
}
Then in ajax.php I check if either of those classes return true, if so a new user can be added by a User class, then the user class will return a success response, if they don't return true, the json encoded errors in either UserTools.class.php or Validate.class.php are returned by either of those classes:
ajax.php
if($validate->showResponse() === true && $user_tools->showResponse() === true) {
$user = new User($username, $password, $email);
$user->save();
echo $user->showResponse();
}
else {
echo $user_tools->showResponse();
echo $validate->showResponse();
}
Firebug shows that everything get's returned as expected, UserTools.class.php returns the usernameexists error and Validate.class.php returns the others:
{"error":{"usernameexists":"Username already taken"}}
{"error":{"password":"This field is required","password_again":"This field is required","email":"This field is required"}}
Yet I can't display either of those messages via jQuery, if I remove 'echo $user_tools->showResponse();' from 'else' in ajax.php, the error messages do get appended correctly, when I want to display both errors, nothing get's appended.
jQuery file:
if(msg.error) {
if(msg.error['usernameexists']) {
$('#msg-username').show().html('<p></p>').addClass('error');
$('#msg-username p').append(msg.error['username']);
}
if(msg.error['username']) {
$('#msg-username').show().html('<p></p>').addClass('error');
$('#msg-username p').append(msg.error['username']);
}
if(msg.error['password']) {
$('#msg-password').show().html('<p></p>').addClass('error');
$('#msg-password p').append(msg.error['password']);
}
if(msg.error['password_again']) {
$('#msg-password_again').show().html('<p></p>').addClass('error');
$('#msg-password_again p').append(msg.error['password_again']);
}
if(msg.error['email']) {
$('#msg-email').show().html('<p></p>').addClass('error');
$('#msg-email p').append(msg.error['email']);
}
}
The reason its not working is because there are 2 seperate json objects
One way is to combine them, for that put this in your ajax.php
if($validate->showResponse() === true && $user_tools->showResponse() === true) {
$user = new User($username, $password, $email);
$user->save();
echo $user->showResponse();
}else {
$r1 = $user_tools->showResponse();
$r2 = $validate->showResponse();
if($r1 !== true && $r2 !== true){
$r1 = json_decode($r1);
$r2 = json_decode($r2);
foreach($r2['error'] as $k => $v)
$r1['error'][$k] = $v;
$r1 = json_encode($r1);
}else if($r1 === true){
$r1 = $r2;
}
echo $r1;
}
Other easier way would be to return the error object itself instead of json_encoded one from Validate.class.php and UserTools.class.php and combine them in ajax.php then output the json_encoded string. this would save the 2 json_decode calls in the above code.
Your return string contains two objects and i think that is what (rightly) confuses the json parser. Try prepending a { and appending a } to the else output, and separate the two objects with a comma