below there's a code that I use very often on my website (it's a MyBB forum) and there's a specific web page where I have written it 10+ times.
To make code easier to read I decided to turn it into a function and call it with different arguments each time. Unfortunately it isn't working, for some reason I keep getting the $fail code while without the function I get $success.
It's the first time I use PHP functions but from what I read at w3schools I should be doing good, theoretically. Not much when coming to practice. Mind checking my syntax and tell me if it is wrong?
<?php
//function code
function canviewcheck($allowedgroups)
{
$groups = $mybb->user['usergroup'];
if ($mybb->user['additionalgroups']) {
$groups .= "," . $mybb->user['additionalgroups'];
}
$explodedgroups = explode(",", $groups);
$canview = 0;
foreach ($explodedgroups as $group) {
if (in_array($group, $allowedgroups)) {
$canview = 1;
echo $success;
break;
}
}
if (!$canview) {
echo $fail;
}
}
//Parameters that I want to use
$allowedgroups = [4, 19];
$pid = 'URL';
$success = "<a href=URL><span style='color:green; font-size:20px;'>SUCCESS</span></a>";
$fail = "<span style='color:#DE1603; font-size:20px;'>FAIL</span>;";
//Call to function
canviewcheck($allowedgroups, $pid, $success, $fail);
You need to add all the necessary parameters to the function, and $mybb also needs to be passed as an argument.
$pid isn't used in the function, so you don't need to pass that as an argument.
<?php
//function code
function canviewcheck($allowedgroups, $success, $fail, $mybb)
{
$groups = $mybb->user['usergroup'];
if ($mybb->user['additionalgroups']) {
$groups .= "," . $mybb->user['additionalgroups'];
}
$explodedgroups = explode(",", $groups);
$canview = 0;
foreach ($explodedgroups as $group) {
if (in_array($group, $allowedgroups)) {
$canview = 1;
echo $success;
break;
}
}
if (!$canview) {
echo $fail;
}
}
//Parameters that I want to use
$allowedgroups = [4, 19];
$pid = 'URL';
$success = "<a href=URL><span style='color:green; font-size:20px;'>SUCCESS</span></a>";
$fail = "<span style='color:#DE1603; font-size:20px;'>FAIL</span>;";
//Call to function
canviewcheck($allowedgroups, $success, $fail, $mybb);
Related
I have a PHP class that highlights names mentioned in a text as links.It can search for #character in a given text and check the names that follow that character.
Theproblem is that the return value from class does not get printed out when I echo the method (public function process_text ($text_txt){}) that is responsible for processing the text. But when I change the return language construct to print or echo, then the parsing is successful and the processed string is printed out. I need to return and not print so as to be able to store the return string in a comments table of my CMS.
Kindly see full code below and advise:
class mentions {
public $print_content = '';
private $m_names = array();
private $m_denied_chars = array(
"#",
"#",
"?",
"¿"
);
private $m_link = "http://example.com/"; // + name of the username, link or whatever
/*
* this class can also be used for specific links
* start editing from here
* */
public function add_name ($name) {
array_push($this->m_names, $name);
}
public function process_text ($text_txt) {
$expl_text = explode(" ", $text_txt);
/*
* a character will be ignores which can be specified next this comment
* :)
* */
$sp_sign = "#"; // this is what you can change freely...
for ($i = 0; $i < count($expl_text); ++$i) {
$spec_w = $expl_text[$i];
$print_link = false;
$name_link = "";
if ($spec_w[0] == $sp_sign) { // then can be a mention...
$name = "";
$break_b = false;
for ($x = 1; $x < strlen($spec_w); ++$x) {
if ($spec_w[$x] == '.' || $spec_w[$x] == ",") {
if (in_array($name, $this->m_names)) {
$print_link = true;
$name_link = $name;
break;
}
}
if (in_array($spec_w[$x], $this->m_denied_chars)) {
$break_b = true;
break;
}
$name .= $spec_w[$x];
}
if ($break_b == true) {
$print_link = false;
break;
} else {
if (in_array($name, $this->m_names)) {
$print_link = true;
$name_link = $name;
}
}
}
if ($print_link == true) {
$this->print_content = "".$spec_w."";
if ($i < count($expl_text)) $this->print_content .= " ";
} else {
$this->print_content = $spec_w;
if ($i < count($expl_text)) $this->print_content .= " ";
}
return $this->print_content;
}
}
}
###### create new class object and process raw data ######
$mentions = new mentions;
$raw_data = 'Hello, #Angelina. I am #Bob_Marley.';
$expr = '#(?:^|\W)#([\w-]+)#i';
preg_match_all($expr, $raw_data, $results);
if( !empty($results[1]) ) {
foreach( $results[1] as $user ) {
$mentions->add_name($user);
}
/*
------------------------------------
*/
$commenData = $mentions->process_text($raw_data);
echo $commenData;
}
answer by #Terminus. If you have a return inside of a loop, the loop (and the entire function) will be interrupted and the value being returned will immediately be returned. That's just how it works. Was trying to write that as a good answer but couldn't. Did end up rewriting your class a bit. ideone.com/vaV0d2 note that i left in a test var_dump and that the output provided by ideone doesn't allow link tags to be displayed as html but if you run it from a server, it'll be correct
I have a function inside a class, and I would like to get the result of this function, something like:
Returned dangerous functions are: dl, system
Here is my code
public final function filterFile(){
$disabled_functions = ini_get('disable_functions');
$disFunctionsNoSpace = str_replace(' ', '', $disabled_functions);
$disFunctions = explode(',', $disFunctionsNoSpace);
$this->disFunctions = $disFunctions;
// get file content of the uploaded file (renamed NOT the temporary)
$cFile = file_get_contents($this->fileDestination, FILE_USE_INCLUDE_PATH);
$found = array();
foreach($this->disFunctions as $kkeys => $vvals)
{
if(preg_match('#'.$vvals.'#i', $cFile))
{
array_push($found, $vvals);
}
} // end foreach
} // end filterFile
// calling the class
$up = new uploadFiles($filename);
$fileterringFile = $up->filterFile();
print_r($fileterringFile);
var_dump($fileterringFile);
EDIT: add 2 functions for errors:
// check if any uErrors
public final function checkErrors(){
$countuErrors = count($this->uErrors);
if((IsSet($this->uErrors) && (is_array($this->uErrors) && ($countuErrors > 0))))
{
return true;
}
return false;
} // end checkErrors()
// print user errors
public final function printErrors(){
$countuErrors = count($this->uErrors);
if((IsSet($this->uErrors) && (is_array($this->uErrors) && ($countuErrors > 0))))
{
echo '<ul>';
foreach($this->uErrors as $uV)
{
echo '<li>';
echo $uV;
echo '</li>';
}
echo '</ul>';
}
} // end printErrors()
Thanks in advance
at the end of end filterFile, add:
return 'Returned dangerous functions are: '.implode(',',$found);
I am using a php session-based flash messenger available here. The issue is sometimes I get multiple messages of the same type when I generate errors, display messages, so on and so fourth. This is mostly due to some AJAX issues. Assuming that I wanted to only apply a fix in the display code here:
public function display($type = 'all', $print = true)
{
$messages = '';
$data = '';
if (!isset($_SESSION['flash_messages'])) {
return false;
}
// print a certain type of message?
if (in_array($type, $this->msgTypes)) {
foreach ($_SESSION['flash_messages'][$type] as $msg) {
$messages .= $this->msgBefore . $msg . $this->msgAfter;
}
$data .= sprintf($this->msgWrapper, $this->msgClass, $this->msgClassPrepend.'-'.$type, str_replace('messages', 'autoclose',$this->msgClassPrepend.'-'.$type), $messages);
// clear the viewed messages
$this->clear($type);
// print ALL queued messages
} elseif ($type == 'all') {
$counter = 1;
foreach ($_SESSION['flash_messages'] as $type => $msgArray) {
$count = $counter++;
$messages = '';
foreach ($msgArray as $msg) {
$messages .= $this->msgBefore . $msg . $this->msgAfter;
}
$data .= sprintf($this->msgWrapper, $this->msgClass, $this->msgClassPrepend.'-'.$type, str_replace('messages', 'autoclose', $this->msgClassPrepend.'-'.$type), $messages);
}
// clear ALL of the messages
$this->clear();
// invalid message type?
} else {
return false;
}
// print everything to the screen or return the data
if ($print) {
echo $data;
} else {
return $data;
}
}
How would I make it so that duplicate messages are detected on a 1 for 1 basis. So if the message is "Hello" and "Hello" and "Hello." I can remove one of the first two, and keep the later as it is a different message so to speak. All the workarounds I can think of would be overly complex, and I was wondering if anyone could think of a simple solution.
Additional info: display is encased in class Messages and a new message is created with
$msg = new Messages();
$msg->add('e', 'Some error here.');
You could simply run the message array through array_unique() before the $messages string is built. For example, these two additions to the display method should do the trick...
if (in_array($type, $this->msgTypes)) {
$filtered = array_unique($_SESSION['flash_messages'][$type]);
foreach ($filtered as $msg) {
and...
foreach ($_SESSION['flash_messages'] as $type => $msgArray) {
$count = $counter++;
$messages = '';
$filtered = array_unique($msgArray);
foreach ($filtered as $msg) {
Alternatively, you could override the add method with a unique check. For example
public function add($type, $message, $redirect_to = null, $ignoreDuplicates = true) {
// snip...
// wrap the array push in this check
if (!($ignoreDuplicates && in_array($message, $_SESSION['flash_messages'][$type]))) {
$_SESSION['flash_messages'][$type][] = $message; // this is the existing code
}
// snip...
}
I am trying to store some data as an array in the session but the function does not seem to be working.it does not throw any error but every time i add data to it, it just overwrites the previous data. I am using yii and here is the action
public function actionStoreProducts($name)
{
$name=trim(strip_tags($name));
if(!empty($name))
{
if(!isset(Yii::app()->session['_products']))
{
Yii::app()->session['_products']=array($name);
echo 'added';
}
else
{
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
Yii::app()->session['products'] = $myProducts;
echo 'added';
}
}
Can anyone suggest me how can i achieve the desired result?
Please correct your code like this .
public function actionStoreProducts($name) {
$name = trim(strip_tags($name));
if (!empty($name)) {
if (!isset(Yii::app()->session['_products'])) {
Yii::app()->session['_products'] = array($name);
echo 'added';
} else {
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
Yii::app()->session['_products'] = $myProducts;
echo print_r(Yii::app()->session['_products']);
echo 'added';
}
}
}
session property read-only
i think the correct aproach is :
function actionStoreProducts($name) {
$session = new CHttpSession; //add this line
$session->open(); //add this line
$name = trim(strip_tags($name));
if (!empty($name)) {
if (!isset(Yii::app()->session['_products'])) {
$session->add('_products', array($name)); //replace this line
echo 'added';
} else {
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
$session->add('_products', $myProducts); //replace this line
echo 'added';
}
}
}
first get an variable into $session['somevalue'] ,then sore in array variable, Use Like IT:-
$session = new CHttpSession;
$session->open();
$myval = $session['somevalue'];
$myval[] = $_POST['level'];
$session['somevalue'] = $myval;
I have problem. In my function, return shows only first player from server. I wanted to show all players from server, but i cant get this working. Here is my code:
function players() {
require_once "inc/SampQueryAPI.php";
$query = new SampQueryAPI('uh1.ownserv.pl', 25052); // Zmień dane obok! //
if($query->isOnline())
{
$aInformation = $query->getInfo();
$aServerRules = $query->getRules();
$aPlayers = $query->getDetailedPlayers();
if(!is_array($aPlayers) || count($aPlayers) == 0)
{
return 'Brak graczy online';
}
else
{
foreach($aPlayers as $sValue)
{
$playerid = $sValue['playerid'];
$playername = htmlentities($sValue['nickname']);
$playerscore = $sValue['score'];
$playerping = $sValue['ping'];
return '<li>'.$playername.' (ID: '.$playerid.'), Punkty ('.$playerscore.'), Ping ('.$playerping.')</li>';
}
}
}
}
You're returning from within your loop.
Instead, you should concatenate the results for each iteration and then return that concatenated string outside the loop.
e.g.
$result = "";
foreach($aPlayers as $sValue) {
# add to $result...
}
return $result
function players() {
require_once "inc/SampQueryAPI.php";
$query = new SampQueryAPI('uh1.ownserv.pl', 25052); // Zmień dane obok! //
if($query->isOnline())
{
$aInformation = $query->getInfo();
$aServerRules = $query->getRules();
$aPlayers = $query->getDetailedPlayers();
if(!is_array($aPlayers) || count($aPlayers) == 0)
{
return 'Brak graczy online';
}
else
{
$ret = '';
foreach($aPlayers as $sValue)
{
$playerid = $sValue['playerid'];
$playername = htmlentities($sValue['nickname']);
$playerscore = $sValue['score'];
$playerping = $sValue['ping'];
$ret .= '<li>'.$playername.' (ID: '.$playerid.'), Punkty ('.$playerscore.'), Ping ('.$playerping.')</li>';
}
return $ret;
}
}
}
In a function you can only return ONE value.
Try creating a list of players and return the list when all records have been added to it.
In your case, list of players will result in an array of players