How to call php function with URL? - php

Hello Id like to know how to call the function I just written from URL?
Bellow are my php code.
<?php
require 'db.php';
function l1(){
echo "Hello there!";
}
function l2(){
echo "I have no Idea what Im doing!";
}
function l3(){
echo "I'm just a year 1 college student dont torture me sir!";
}
?>
I tried http://127.0.0.1/study/sf.php?function=l1 but it wont echo the written code.
Please point me to the right direction.

Yes you could supply that parameter into calling your user defined function:
$func = $_GET['function'];
$func();
Might as well filter the ones you have defined thru get_defined_functions
function l1(){
echo "Hello there!";
}
function l2(){
echo "I have no Idea what Im doing!";
}
function l3(){
echo "I'm just a year 1 college student dont torture me sir!";
}
$functions = $arr = get_defined_functions()['user']; // defined functions
if(!empty($_GET['function']) && in_array($_GET['function'], $functions)) {
$func = $_GET['function'];
$func();
}
Sample Output
Sidenote: function_exists can be also applied as well:
if(!empty($_GET['function']) && function_exists($_GET['function'])) {
// invoke function
}

One option you can do if use if/elseifs like so:
if($_GET['function'] == 'l1')
{
l1();
}
else if($_GET['function'] == 'l2')
{
l2();
}
Or you could use a riskier approach and call the function name directly from the input.
$functionName = $_GET['function'];
$functionName();
Edit:
Or you could use a switch statement:
switch($_GET['function'])
{
case 'l1':
l1();
break;
case 'l2':
l2();
break;
case 'l3':
l3();
break;
}

Related

How to check if constant is defined, inside function - php

I am trying to make a small PHP function which can check if a constant is defined, and if so, echo it, and if not, echo space or nothing.
Right now, the if(defined() part is not working, because the constant is being transferred to a variable inside the function.
function getConstant($constant) {
if(defined($constant)) {
echo constant($constant);
} else {
echo '';
}
}
The echo constant($constant) part is working fine, but I cannot check if the constant is actually defined because it is a variable now.
I cannot seem to find a solution for it
public static function isConstants($constant) {
$oClass = new ReflectionClass(__CLASS__);
$allConstants = $oClass->getConstants();
if (isset($allConstants[$constant])) {
echo $allConstants[$constant];
} else {
echo '';
}
}

Cookie check in OOP

Until yesterday I was burning my brain trying to switch from a procedural thinking to a OOP thinking; this morning I gave up. I said to my self I wasn't probably ready yet to understand it.
I started then coding in the usual way, writing a function to check if there's the cookie "logged" or not
function chkCookieLogin() {
if(isset($_COOKIE["logged"])) {
$logged = 'true';
$cookieValue = $_COOKIE["logged"];
return $logged;
return $cookieValue;
}
else {
$logged = 'false';
return $logged;
}
}
$result = chkCookieLogin();
if($result == 'true'){
echo $cookieValue;
}
else {
echo 'NO COOKIE';
}
since I run across a problem: I wanted to return two variables ($logged and $cookieValue) instead of just one. I google it and I found this answer where Jasper explains a method using an OOP point of view (or this is what I can see).
That answer opened me a new vision on the OOP so I tried to rewrite what I was trying to achieve this way:
class chkCookie {
public $logged;
public $cookieValue;
public function __construct($logged, $cookieValue) {
$this->logged = $logged;
$this->cookieValue = $cookieValue;
}
function chkCookieLogin() {
$out = new chkCookie();
if(isset($_COOKIE["logged"])) {
$out->logged = 'true';
$out->cookieValue = $_COOKIE["logged"];
return $out;
}
else {
$out->logged = 'false';
return $out;
}
}
}
$vars = chkCookieLogin();
$logged = $vars->logged;
$cookieValue = $vars->cookieValue;
echo $logged; echo $cookieValue;
Obviously it didn't work at the first attempt...and neither at the second and the third. But for the first time I feel I'm at one step to "really touch" the OOP (or this is what I think!).
My questions are:
is this attempt correctly written from the OOP point of view?
If yes, what are the problems? ('cause I guess there's more than one)
Thank you so much!
Credit to #NiettheDarkAbsol for the idea of returning an Array data-type.
Using dependency injection, you can set-up an object like this:
class Factory {
private $Data = [];
public function set($index, $data) {
$this->Data[$index] = $data;
}
public function get($index) {
return $this->Data[$index];
}
}
Then to use the DI module, you can set methods like so (using anonymous functions):
$f = new Factory();
$f->set('Cookies', $_SESSION);
$f->set('Check-Cookie', function() use ($f) {
return $f->get('Cookies')['logged'] ? [true, $f->get('Cookies')['logged']] : [false, null];
});
Using error checks, we can then call the method when and as we need it:
$cookieArr = is_callable($f->get('Check-Cookie')) ? call_user_func($f->get('Check-Cookie')) : [];
echo $cookieArr[0] ? $cookieArr[1] : 'Logged is not set';
I'd also consider adding constants to your DI class, allowing more dynamic approaches rather than doing error checks each time. IE, on set() include a constant like Factory::FUNC_ARRAY so your get() method can return the closure already executed.
You can look into using ternary operators if you're confused.
See it working over at 3v4l.org.
If it means anything, here is an OOP styled approach.

Calling function in another function

I have a function printContent() which prints the arguments and logged() which checks if the user is logged in.
My point is to do something like this:
logged("printContent('TITLE', 'CONTENT', 1)", 1);
It doesn't work. It should printContent() if user is not logged in, but nothing is happening. If I'll try changing return() into print() it prints the text "printContent(text...)".
Here are these two functions:
function logged($echo = 0, $logout = 0)
{
if($_SESSION['user'])
{
if($echo)
{
if(!($logout)) return $echo;
else return false;
}
else return true;
}
else
{
if($logout == 1) return $echo;
else return false;
}
}
function printContent($title, $content, $type = 0){
if($type == 1){
echo '<div class="right-box">';
if($title) echo '<h3>'.$title.'</h3>';
echo $content.'</div>';
}
else {
echo '<div class="left-box">';
if($title) echo '<h2>'.$title.'</h2>';
echo '<div class="left-box-content">'.$content.'</div></div>';
}
}
It should printContent() if user is not logged in
You can try
if(!logged())
{
printContent('TITLE', 'CONTENT', 1);
}
Your logged() function is too complicated; the $echo and $logout parameters make the logic extremely hard to follow. You should simplify it to just this, doing one thing very well:
function isLoggedIn()
{
return !empty($_SESSION['user']);
}
Then, the logic becomes quite simple afterwards:
if (!isLoggedIn()) {
printContent('title', 'content', 1);
}
Play time
Being fancy, you could do this since 5.3, though it's a very contrived example of what you could accomplish with anonymous functions:
function ifLoggedIn($loggedIn, $loggedOut)
{
return empty($_SESSION['user']) ? $loggedIn() : $loggedOut();
}
The $loggedIn and $loggedOut parameters are the callback parameters and get executed from inside the function, based on whether the user is logged in or not. To use it:
ifLoggedIn(function() {
}, function() {
printContent('TITLE', 'CONTENT', 1);
});
What you seem to be looking for is a callback.
If I understand you correctly, you wish printContent only to execute, if the user is logged in, correct?
You may want to check this question for further info: How do I implement a callback in PHP?
you are trying to execute a plain string. Use
function1( function2() );
that is the same as
$tmp = function2();
function1($tmp);

Creating multilanguage homepage

so im making homepage with three languages.
I am using switch method, here is code -
public function languages()
{
if (isset($_GET['lang']) && $_GET['lang'] != '')
{
$_SESSION['lang'] = $_GET['lang'];
}
else
{
$_SESSION['lang'] = 'en_EN';
}
switch($_SESSION['lang'])
{
case 'en_EN': require_once('language/lang.eng.php');break;
case 'lv_LV': require_once('language/lang.lv.php');break;
case 'ru_RU': require_once('language/lang.ru.php');break;
default: require_once('language/lang.eng.php');
}
}
public function translate($txt)
{
global $text;
return $text[$txt];
}
and it should display in index.php file like this -
<?php $index->translate('search'); ?>
but the problem is that it shows no errors, no notices, no warnings and no translated or default text.
I included function languages() , maybe you can help me with this problem?
EDIT:
im calling $language at start of index.php file - <?php require_once('class.index.php'); $index = new index; $index->languages(); ?> and $text is defined in lang.eng.php; lang.lv.php and lang.ru.php file.
Since you're using a class, I think it's better to use properties instead of globals, it will be easier in future mantainance. Create a class variable holding $text and use that
class Index {
var $text;
public function languages()
{
require(".....");
$this->text = $text;
}
public function translate($txt)
{
if(isset($this->text[$txt]))
{
return $this->text[$txt];
}
else
{
return "no translation";
}
}
}
$index = new Index;
$index->languages();
echo $index->translate('search');
type
<?php echo $index->translate('search'); ?>
Check first whether the session is initialized or not and also place the languages() function call before the translate so that it loads the language prior to translation and also put error_reporting(E_ALL) at top so that any error suppresion will be be removed and also put echo the returned result of translate statement

how to use PHP magic constants from other classes?

i have created below function in a file info.php to debug variable & data during page load
class Info {
static function watch($what,$msg='',$more=FALSE)
{
echo "<hr/>";
echo "<br/>".$msg.":";
if( is_array($what) || is_object($what) )
{
echo "<pre>";
print_r($what);
echo "</pre>";
}
else{
echo $what;
}
if($more)
{
echo "<br/>METHOD:".__METHOD__;
echo "<br/>LINE:".__LINE__;
}
}
}
now i call this method from another page index.php, where i inculded info.php
in this file i want to debug POST array, so i write below code
class Testpost {
__construct() { // some basic intializtion }
function getPostdata($postarray) {
$postarray=$_POST;
Info::watch($postarray,'POST ARRAY', TRUE);
}
everything is working fine but method and LINE appears below
METHOD:Info::watch();
LINE:17 // ( where this code is written in Info class)
but i wantbelow to display
METHOD: Testpost::gtPostdata()
LINE:5( where this function is called in Testpost class)
so how do i do that if i put$more=TRUE in watch() then method and line number should be diaply from the class where it is called.
can i use self:: or parent::in watch method?? or something else
please suggest me how to call magic constants from other classes or is there any other method to debug varaibale?? ( please dont suggest to use Xdebug or any other tools)
You have to use the debug_backtrace() php function.
You also have below the solution to your problem. Enjoy! :)
<?php
class Info {
static function watch($what,$msg='',$more=FALSE)
{
echo "<hr/>";
echo "<br/>".$msg.":";
if( is_array($what) || is_object($what) )
{
echo "<pre>";
print_r($what);
echo "</pre>";
}
else{
echo $what;
}
if($more)
{
$backtrace = debug_backtrace();
if (isset($backtrace[1]))
{
echo "<br/>METHOD:".$backtrace[1]['function'];
echo "<br/>LINE:".$backtrace[1]['line'];
}
}
}
}
You can not use those constants from that scope. Check out the function debug_backtrace() instead. If it gives you too much info, try to parse it.
debug_bactrace is the only way you could totally automate this, but it's a "heavy-duty" function.... very slow to execute, and needs parsing to extract the required information. It might seem cumbersome, but a far better solution is to pass the necessary information to your Info::watch method:
class Info {
static function watch($whereClass,$whereLine,$what,$msg='',$more=FALSE)
{
echo "<hr/>";
echo "<br/>".$msg.":";
if( is_array($what) || is_object($what) )
{
echo "<pre>";
print_r($what);
echo "</pre>";
}
else{
echo $what;
}
if($more)
{
echo "<br/>METHOD:".$whereClass;
echo "<br/>LINE:".$whereLine;
}
}
}
now i call this method from another page index.php, where i inculded info.php
class Testpost {
__construct() { // some basic intializtion }
function getPostdata($postarray) {
$postarray=$_POST;
Info::watch(__METHOD__,__LINE__,$postarray,'POST ARRAY', TRUE);
}

Categories