After registering a new user, I receive a selector and token for account verification.
I want to be able to know whether or not a confirmation mail was sent, but I'm having troubles returning the value from the callback. Here's what I have:
try {
$callback = function ($selector, $token) {
$msg = "some message";
if(mail($_POST['email'],"Please verify your account",$msg))
{
return "success";
}
else
{
return "mail_not_sent";
}
};
$auth->registerWithUniqueUsername($_POST['email'], $_POST['password'], $_POST['username'], $callback);
$output['result']=$callback; //this is the array where I want to store the result in ("success" of "mail_not_sent").
}
catch ($e) {
}
It doesn't look like Auth::registerWithUniqueUsername() gives you access to the result of the callback, so if I had to do this, I would do something like this:
$callback_result = '';
$callback = function ($selector, $token) use (&$callback_result) {
/* Other code here */
$callback_result = 'whatever';
/* Other code here */
};
$auth->registerWithUniqueUsername(/* Other args here */, $callback);
$output['result'] = $callback_result;
This is a bit odd way but:
try {
$mailFlag = null;
$callback = function ($selector, $token) use (&$mailFlag) {
$msg = "some message";
if(mail($_POST['email'],"Please verify your account",$msg))
{
$mailFlag = "success";
}
else
{
$mailFlag = "mail_not_sent";
}
};
$auth->registerWithUniqueUsername($_POST['email'], $_POST['password'], $_POST['username'], $callback);
$output['result'] = $mailFlag; //this is the array where I want to store the result in ("success" of "mail_not_sent").
}
catch ($e) {
}
Related
There are 3 queues in redis.
If I insert a data at a same time with different browsers, both requests are accepted.
I get 2 duplicated records. Any helps?
For example, the first request is on the 1st queue.
At the second request, 2nd queue is searched for finding the data.
But the data doesn't exist in the queue.
The second request is inserted on the queue.
Is it understandable?
public function save($evt_no, $type = "redis") {
$name = '';
$res = true;
try{
$headers = getallheaders();
$bodys = $_REQUEST;
$session = $_SESSION;
foreach ($_FILES as $fileKey=>$fileVal) {
if ($fileVal['error'] == 0) {
try {
$uploaded_row = $this->fileL->upload('queueEventParticipant', $fileKey, array() ,'queue');
} catch (\Exception $ex) {
throw $ex;
}
$bodys['file'][_return_numeric($fileKey)] = $uploaded_row;
}
}
$data = array(
'header' => $headers,
'body' => $bodys,
'session' => $session
);
$data['body']['evt_no'] = $evt_no;
$data = json_encode($data);
if($type == "redis"){
$name = $this->attendQueueRedisService->setNewRsvp($data);
} else {
throw new \Exception("No exist");
}
} catch (\Exception $ex){
log_message("error", $ex->getMessage());
throw $ex;
}
if($res){
return $name;
} else {
return "Error";
}
}
class AttendQueueRedisService extends CI_Model {
private $redisClient;
private $redisConfig;
const PREFIX_DONE = 'done_';
const PREFIX_ERROR = 'error_';
public function __construct() {
parent::__construct();
if ($this->load->config('redis', true, true)) {
$this->redisConfig = $this->config->config['redis'];
}
$this->redisClient = new Redis();
$this->redisClient->connect($this->redisConfig['hostname'], $this->redisConfig['port']);
$this->redisClient->auth($this->redisConfig['auth']);
$this->redisClient->select($this->redisConfig['queue']);
}
public function setNewRsvp($data) {
$key = uniqid('rsvp_'.gethostname().'_',true).':redis';
$this->redisClient->set($key, $data, 60 * 30);
return $key;
}
}
I defined my postParams where I want to pass "hash" value from db.
What I am trying to accomplish is that if hash exists in my Session table to return TRUE and if not to return FLASE.
Problem is my code always returns TRUE.
What I am missing?
$postData = $this->requirePostParams(['hash']);
$this->container->get('app')->formService(
$this->data['hash']
);
if ($postData['hash']) {
$hash = $this->get('app')->getSessionRepository()->find($this->data['hash']);
if (!$hash) return false;
} else {
return true;
}
And my requirePostParams works fine! (tested on other functions)
protected function requirePostParams($params) {
$currentRequest = $this->get('request_stack')->getCurrentRequest();
$postData = $currentRequest->request->all();
$postContent = json_decode($currentRequest->getContent(), true);
if(!empty($postContent)) $postData = $postContent;
$this->data = $postData;
$missingParams = [];
foreach ($params as $param) {
if (!array_key_exists($param, $postData)) {
$missingParams[] = $param;
}
}
}
And my service:
$findHash = $this->getSessionRepository()->findOneBy([
'hash' => $hash
]);
As xmike mentioned in comments, function requirePostParams returns nothing. That's why $postData['hash'] is never set.
Try to replace $postData['hash'] with $this->data['hash']:
$this->requirePostParams(['hash']);
$this->container->get('app')->formService(
$this->data['hash']
);
if ($this->data['hash']) {
$hash = $this->get('app')->getSessionRepository()->find($this->data['hash']);
if (!$hash) return false;
} else {
return true;
}
I'm trying to load a website url from a textfile, then unset this string from an array and pick a random website from the array.
But once I try to access the array from my function the array would return NULL, does someone know where my mistake is located at?
My current code looks like the following:
<?php
$activeFile = 'activeSite.txt';
$sites = array(
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
);
function getActiveSite($file)
{
$activeSite = file_get_contents($file, true);
return $activeSite;
}
function unsetActiveSite($activeSite)
{
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
function updateActiveSite($activeFile)
{
$activeWebsite = getActiveSite($activeFile);
if(!empty($activeWebsite))
{
$unsetActive = unsetActiveSite($activeWebsite);
if($unsetActive == true)
{
$randomSite = $sites[array_rand($sites)];
return $randomSite;
}
else
{
echo 'Could not unset the active website.';
}
}
else
{
echo $activeWebsite . ' did not contain any active website.';
}
}
$result = updateActiveSite($activeFile);
echo $result;
?>
$sites is not avaliable in unsetActiveSite function you need to create a function called "getSites" which return the $sites array and use it in unsetActiveSite
function getSites(){
$sites = [
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
];
return $sites;
}
function unsetActiveSite($activeSite)
{
$sites = getSites();
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
I was working in one Laravel Project using 92Five App. when access user List. its goto Something Went Wrong Page. Its Display Array to string conversion Error in Error Log.
In User Controller Following Functions are Defined.
Error :
[2016-08-09 13:13:12] log.ERROR: Something Went Wrong in User
Repository - getAllUsersData():Array to string conversion [] []
My Code :
public function getAllUsersData()
{
try{
$users = array();
$tempUsers = \User::all()->toArray();
$users = $this->getGroupBaseRole($tempUsers);
return $users;
}
catch (\Exception $e)
{
\Log::error('Something Went Wrong in User Repository - getAllUsersData():'. $e->getMessage());
throw new SomeThingWentWrongException();
}
}
public function getGroupBaseRole($groupMembersInfo) {
$data = [];
if(!empty($groupMembersInfo) && isset($groupMembersInfo)) {
foreach($groupMembersInfo as $user)
{
$banned = false;
$suspended = false;
$loginAttempt = 0;
$usersThrottle = \Throttle::where('user_id',$user['id'])->get()->toArray();
// print_r($usersThrottle); exit;
if(sizeof($usersThrottle) != 0)
{
foreach($usersThrottle as $userThrottle)
{
if($userThrottle['banned'] == true)
{
$banned = true;
}
if($userThrottle['suspended'] == true)
{
$suspended = true;
}
$loginAttempt = $loginAttempt + $userThrottle['attempts'];
}
$user['banned'] = $banned;
$user['suspended'] = $suspended;
$user['loginAttempt'] = $loginAttempt;
}
else
{
$user['banned'] = false;
$user['suspended'] = false;
$user['loginAttempt'] = 0;
}
$groupUser = \Sentry::findUserById($user['id']);
$groups = $groupUser->getGroups()->toArray();
if(sizeof($groups)!=0)
{
$user['role'] =$groups[0]['name'];
}
else
{
$user['role'] = '';
}
$data[] = $user;
}
}
return $data;
}
It seeems getGroupBaseRole() method accepts string, but you're trying to pass an array $tempUsers as first argument.
I have a function A which loads the data from db if the user has liked the image. I have another function B which loads the count for the total number of likes for the image. Both these functions return response using JSON.
If I call them individually, everything works fine, but if I call function B in function A, I get no JSON response and nothing happens although firebug does show two JSON arrays being outputted.
What is wrong with the code?
Function A:
public function loadLikes() {
//sql query
try
{
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $imageid, ':author' => $author);
$query->execute($params);
//calling function B
$this->countLikes($imageid);
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
if ($row['like'] == '1') {
$response = json_encode(array('like' => true));
echo $response;
return TRUE;
}
elseif ($row['like'] == '2') {
$response = json_encode(array('unlike' => true));
echo $response;
return TRUE;
}
else {
$error = "Invalid";
$response = json_encode(array('like' => false, 'text' => $error));
echo $response;
return FALSE;
}
}
}
else {
$response = json_encode(array('unlike' => true));
echo $response;
return FALSE;
}
}
catch(PDOException $ex)
{
echo json_encode(array('like' => false, 'text' => $ex));
return FALSE;
}
}
Function B:
public function countLikes($i) {
//sql query
try
{
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $i);
$query->execute($params);
if ($query->rowCount() > 0) {
$count = $query->fetchColumn();
$response = json_encode(array('count' => $count));
echo $response;
return TRUE;
}
}
catch(PDOException $ex)
{
return FALSE;
}
}
jQuery:
$.ajax({
type: "POST",
url: url,
data: postData,
dataType: "json",
success: function(data){
$(".count-like").show(600).text(data.count);
if(data.like) {
$("a#alike").attr('class', 'starred');
}
else if (data.unlike) {
$("a#alike").attr('class', 'unlike');
}
else {
alert(data.text);
}
}
});
If you invoke both functions, then each will output a JSON array. This will result in a HTTP response with following content:
{"like":1}{"count":2}
Both arrays would be valid separately. But if concatenated like this, it's no longer valid JSON.
Instead of outputting the json serialization with echo you should collect it in a temporary variable, merge the two arrays, and then output the combined array with a single:
echo json_encode(array_merge($countArray, $likeArray));
Example adaptions of your code
Function B should become:
public function countLikes($i) {
//sql query
try
{
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $i);
$query->execute($params);
if ($query->rowCount() > 0) {
$count = $query->fetchColumn();
/* JUST RETURN HERE */
return (array('count' => $count));
}
}
catch(PDOException $ex)
{
/* INSTEAD OF FALSE use an empty array,
which is interpreted as false in boolean context*/
return array();
}
}
Then when you call the function:
//calling function B
$countArray = $this->countLikes($imageid);
This will always be an array. Which you then can use in the output code:
$response = json_encode(array('like' => true) + $countArray);
(It's still inadvisable to have an echo right there. But too much code, too little context to propose a nicer rewrite. And if it works, ..)