HattrickNZ
HattrickNZ

Reputation: 4663

running a php script in the command line + very basic

Now maybe this is a completely novice/silly question, apologies, but...

I have the following file:

$ cat helloWorldScript.php
/*here I want to be able to run this in the command line
witht the command pho scriptname.php.
*/
<?php  Print "Hello, World!\n"; ?>

Now I can run the script as follows:

$ php helloWorldScript.php
/*here I want to be able to run this in the command line
witht the command pho scriptname.php.
*/
Hello, World!

or like this with the -f parameter -f <file> Parse and execute <file>.

$ php -f helloWorldScript.php
/*here I want to be able to run this in the command line
witht the command pho scriptname.php.
*/
Hello, World!

But why does it show the comments when I execute the file?
What is the difference in using the -f?

The reason I ask is because I am want to use a php script to import a csv file into a database, see here.
I have some basic knowledge of php in a browser but here I just have this question.

Upvotes: 1

Views: 103

Answers (2)

amphetamachine
amphetamachine

Reputation: 30621

<?php ... ?> is the special tag that delineates where your code begins. Anything outside of that is taken to mean "print this out verbatim."

In order to get your /* ... */ comments to not print out, you will need to include them inside the code portion of your script:

<?php
/*here I want to be able to run this in the command line
witht the command pho scriptname.php.
*/
print "Hello, World!\n";
?>

Other suggestions

If you put a shebang line at the top of your file that reads #!/usr/bin/php or even #!/usr/bin/env php, you can execute your script as if it were a program, provided you have the executable bit set on the file.

Also, the ?> is not necessary.

So all together:

#!/usr/bin/php
<?php
/*here I want to be able to run this in the command line
witht the command pho scriptname.php.
*/
print "Hello, World!\n";

Then chmod +x myscript.php. Then you can call it from the command line using ./myscript.php

Upvotes: 3

Jon Surrell
Jon Surrell

Reputation: 9647

Those are not comments because they are outside of the <?php ?> tags.

Move the opening tag to the top of the file and it should behave as expected:

<?php
/*here I want to be able to run this in the command line
witht the command pho scriptname.php.
*/
Print "Hello, World!\n"; ?>

Anything not contained in the php tags will not be parsed as code.

If your file will only contain code (this sounds like your case), it is common practice and even encouraged to open <?php on the first line and omit any closing ?> tag.

See the documentation.

Upvotes: 6

Related Questions