Running a function by typing in URL

2019-03-06 05:19发布

问题:

I have searched all over the internet to run a function from URL and found out it is not possible.

I am asking if there is another way to do this. I will explain below what I am trying to achieve.

On my website I have several functions that when a hyperlink is clicked on that cracks.php page, the main content changes accordingly. Now I want to direct people from a single URL to that cracks.php page with the function already called. Example - www.example.com/cracks.php?AC ( which will call a function named AC and the content changes before the page loads)

Ive found this method below, but couldnt get it to work.

if(document.location.search == '?AC')  
{  
    AC();  
}  

Sorry for the messy code on the website. Thanks for reading, any help would be appreciated.

回答1:

You can call www.example.com/cracks.php?do=AC and then get do with $doMethod = $_GET['do'];. What you then do is, use a switch function or a few ifs to check and execute when e.g. $doMethod equals AC.

Like this:

$doMethod = $_GET['do'];
switch($doMethod)
{
    case "AC":
        //some random stuff to do
        break;
    case "BD":
        //some random stuff to do
        break;
    case "XY":
        //some random stuff to do
        break;
    default:
        break;
}


回答2:

That depends if you need to do that dynamically or you can do it hard coded. Because that hard coded is too simple (with if's and switches), what you have to do is:

$functionsList = Array('func1', 'func2');


function func1(){
    echo '1';
}

function func2(){
    echo '2';
}

if (function_exists($_GET['f']) and in_array($_GET['f'], $functionsList)){
    call_user_func($_GET['f']);
}

Then call your_file_name.php?f=func1 and your_file_name.php?f=func2 and you'll see different outputs.



回答3:

With the help of Mark Koopman I managed to use his Javascript method and it worked like I wanted.

So heres the method in Javascript:

<html>
    <body>
        <script>
            function handleOnload()
            {
                if(location.search == "?AC")
                   alert("the query string is " + location.search);
            }

            window.onload=handleOnload;
        </script>
    </body>
</html>


标签: php url