PHP Simple Tinker Like Script

PHP Simple Tinker Like Script

Last Updated on Feb 15, 2023

Introduction

If you have worked with Laravel you know what tinker is but if you haven’t Laravel Tinker is a tool that allows users to interact with the application through the command line.

Today we are going to build a simple Tinker like tool that lets the user write php code in the command line.

So let’s get started

Simple Tinker

First we need a way to get whatever that user writes. There is a function for that in PHP and it’s called readline. It takes a string and with that prompts the user. For example

readline("what is your name? ");

Then the user is allowed to type whatever they want. And what they write will be returned by this function. So let’s prompt the user and store what they type in a variable

$code = readline(">>> ");

Great! Now that we have what the user wants to run, let's run it. How can we run a php code inside php?!

Easy. there is a function for it called eval. That runs the code that is given to it. For example:

eval("echo 2+2; ");

This will print 4. So let’s use it and run the code we got from user

eval($code);

Great. We are almost done. Right now when the application runs once it will be finished and comes out of our tool we want to keep asking the user and keep running the code. So let’s put our code inside a loop. Let’s also add a new line so the new prompt will be in the new line.

while(true){
    $code = readline(">>> ");
    eval($code);
    echo "\n";
}

Great. Now we keep asking the user and run their code. But what if the user writes a code that is not valid or there is a typo? Well php is going to throw an error and the user will be thrown out of the application.

So let’s handle the errors as well. Do you remember error handling?

Here is our final code

while(true){
    try{
        $code = readline(">>> ");
        eval($code);
        echo "\n";
    }catch(Throwable $th){
        echo $th->getMessage();
echo "\n";
    }
}

You can easily run this with your command line. You can write php <name of the file>

In my case it would be 

php learner.php

And to make it even cooler you can remove the .php from the end of your file. So my file would be learner and when I want to run the code I would run 

php learner

Here is a video of that

With a few lines of code we could create such a powerful application. Isn’t it amazing?

Conclusion

Now you know about creating a simple Tinker like application in PHP.

I recommend you to open a PHP files and try build your own. try to add more features.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • readline
  • eval
  • tinker like application
  • command line application

Category: programming

Tags: #php #open source

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses