2

how can i call function declared in my php file from address bar? I already tried appending function name with site address but it didn't called the function..

http://myWebSite.com/myFile.php?writeMessage

myfile.php:

<?php
  /* Defining a PHP Function */
  function writeMessage()
  {
  echo "You are really a nice person, Have a nice time!";
  }
  /* Calling a PHP Function */
  writeMessage();
  ?>

6 Answers 6

9

You can check presence of GET parameter in URL and call function accordingly:

if(isset($_GET['writeMessage'])){
   writeMessage();
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Fred-ii- Another example of the case. Also agreed with hanky here, good answer :)
3

A simple way that i would use given that you dont have too many functions is to use a if statement at the top of the php file and check the parameter of the url.

Lets say url:

http://myWebSite.com/myFile.php?writeMessage

Turn it into:

http://myWebSite.com/myFile.php?function=writeMessage

code:

<?php
  $function = $_GET['function'];
  if($function == "writeMessage") {
    // writeMessage();
  }
?>

Comments

1

Of course it doesnt, especially not in that way. For me, it seems to be a horrible idea to call PHP Functions from the address bar, but if you insist:

append the function name to your url like this:

http://myWebSite.com/myFile.php?func=writeMessage

And in the PHP File:

<?php
    $func = filter_var($_GET["func"]);
    call_user_func($func);
?>

Comments

1

Try:

http://myWebSite.com/myFile.php?writeMessage=1

And:

<?php
 /* Defining a PHP Function */
 function writeMessage()
 {
    echo "You are really a nice person, Have a nice time!";
 }
 /* Calling a PHP Function */
 if(isset($_GET['writeMessage']) && $_GET['writeMessage'] == 1){
   writeMessage();
 }
?>

Comments

1

You can do something like this:

<?php

function writeMessage() {
    echo "You're a nice person";
}

$writeMessageArg = $_GET['writeMessage']; /* grabs the argument from the URL */

if (isset($writeMessageArg)) {
    writeMessage();
}

?>

2 Comments

how differ answer you have from OP's
Is it not obvious? I have a new variable defined as $_GET['writeMessage'] and then I check to see if it is set.
1

For a generic approach

<?php

$q = $_SERVER['QUERY_STRING'];

function TestFunc() {
    echo "TestFunc() called.";
}

$q();

?>

You can call the TestFunc() by entering the following url in the address bar:

http://myWebSite.com/myFile.php?TestFunc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.