Shelton Tee
Shelton Tee

Reputation: 13

How to open link in php code being executed via command line

header("location:http;//")

Above line does not seem to work when executing PHP scripts from command line. How best can I open links via command line?

Upvotes: 1

Views: 2804

Answers (3)

Anifowose Tobi
Anifowose Tobi

Reputation: 23

The solution provided above would only work for windows. IT would not work on mac OS . Here is a more general solution

public function  open(string $url): void
{
    switch (PHP_OS) {
        case 'Darwin':
            $opener = 'open';
            break;
        case 'WINNT':
            $opener = 'start';
            break;
        default:
            $opener = 'xdg-open';
    }

    exec(sprintf('%s %s', $opener, $url));
}

Upvotes: 1

Professor Abronsius
Professor Abronsius

Reputation: 33813

A very hastily and quickly tested method might be to use exec passing in the path to a known browser with the url as it's argument - seemed to work ok.

<?php
    $url='https://www.google.co.uk';
    $cmd=sprintf( '%%userprofile%%\AppData\Local\Google\Chrome\Application\chrome.exe %s', $url );
    exec( $cmd );
?>

Thanks to @Álvaro's comment the above can be simplified further( on Windows at least )

<?php
    $url='https://www.google.co.uk';
    $cmd=sprintf( 'start %s',$url );
    exec( $cmd );
?>

Upvotes: 1

Obsidian
Obsidian

Reputation: 3897

header() is HTTP-related only and is used to tell what headers should by returned by the server to the client's browser which performed the request. Location, in particular, simply means Hey ! Check out this place instead: xxxxx.

The client's browser, in turn, will decide by itself if it chooses to follow this advice or not (it usually does) but at no time, the served fetches these informations to re-serve them again to its client.

So the best way to do is to use your script throughout a web browser instead (as it supposed to be). If you want to « open links » from a command line, simply type your browser's executable name followed by an URL (e.g.: firefox http://www.stackoverflow.com).

If what you want to do instead is fetching files or specific pages from a remote web server, use a command line client such as wget or curl instead.

Upvotes: 0

Related Questions