Pfgecnbnm php bp php

Pfgecnbnm php bp php

    Tell PHP to execute a certain file.

$ php my_script.php $ php -f my_script.php
$ php -r 'print_r(get_defined_constants());'

Note: Read the example carefully: there are no beginning or ending tags! The -r switch simply does not need them, and using them will lead to a parse error.

$ some_application | some_filter | php | sort -u > final_output.txt

As with every shell application, the PHP binary accepts a number of arguments; however, the PHP script can also receive further arguments. The number of arguments that can be passed to your script is not limited by PHP (and although the shell has a limit to the number of characters which can be passed, this is not in general likely to be hit). The arguments passed to the script are available in the global array $argv . The first index (zero) always contains the name of the script as called from the command line. Note that, if the code is executed in-line using the command line switch -r, the value of $argv[0] will be «Standard input code» ; prior to PHP 7.2.0, it was a dash ( «-» ) instead. The same is true if the code is executed via a pipe from STDIN .

Читайте также:  Переназначить класс в css

A second global variable, $argc , contains the number of elements in the $argv array (not the number of arguments passed to the script).

As long as the arguments to be passed to the script do not start with the — character, there’s nothing special to watch out for. Passing an argument to the script which starts with a — will cause trouble because the PHP interpreter thinks it has to handle it itself, even before executing the script. To prevent this, use the argument list separator — . After this separator has been parsed by PHP, every following argument is passed untouched to the script.

# This will not execute the given code but will show the PHP usage $ php -r 'var_dump($argv);' -h Usage: php [options] [-f] [args. ] [. ] # This will pass the '-h' argument to the script and prevent PHP from showing its usage $ php -r 'var_dump($argv);' -- -h array(2) < [0]=>string(1) "-" [1]=> string(2) "-h" >

However, on Unix systems there’s another way of using PHP for shell scripting: make the first line of the script start with #!/usr/bin/php (or whatever the path to your PHP CLI binary is if different). The rest of the file should contain normal PHP code within the usual PHP starting and end tags. Once the execution attributes of the file are set appropriately (e.g. chmod +x test), the script can be executed like any other shell or perl script:

Example #1 Execute PHP script as shell script

Assuming this file is named test in the current directory, it is now possible to do the following:

$ chmod +x test $ ./test -h -- foo array(4) < [0]=>string(6) "./test" [1]=> string(2) "-h" [2]=> string(2) "--" [3]=> string(3) "foo" >

As can be seen, in this case no special care needs to be taken when passing parameters starting with — .

The PHP executable can be used to run PHP scripts absolutely independent of the web server. On Unix systems, the special #! (or «shebang») first line should be added to PHP scripts so that the system can automatically tell which program should run the script. On Windows platforms, it’s possible to associate php.exe with the double click option of the .php extension, or a batch file can be created to run scripts through PHP. The special shebang first line for Unix does no harm on Windows (as it’s formatted as a PHP comment), so cross platform programs can be written by including it. A simple example of writing a command line PHP program is shown below.

Example #2 Script intended to be run from command line (script.php)

if ( $argc != 2 || in_array ( $argv [ 1 ], array( ‘—help’ , ‘-help’ , ‘-h’ , ‘-?’ ))) ?>

This is a command line PHP script with one option.

can be some word you would like
to print out. With the —help, -help, -h,
or -? options, you can get this help.

The script above includes the Unix shebang first line to indicate that this file should be run by PHP. We are working with a CLI version here, so no HTTP headers will be output.

The program first checks that there is the required one argument (in addition to the script name, which is also counted). If not, or if the argument was —help, -help, -h or -?, the help message is printed out, using $argv[0] to dynamically print the script name as typed on the command line. Otherwise, the argument is echoed out exactly as received.

To run the above script on Unix, it must be made executable, and called simply as script.php echothis or script.php -h. On Windows, a batch file similar to the following can be created for this task:

Example #3 Batch file to run a command line PHP script (script.bat)

@echo OFF "C:\php\php.exe" script.php %*

Assuming the above program is named script.php , and the CLI php.exe is in C:\php\php.exe , this batch file will run it, passing on all appended options: script.bat echothis or script.bat -h.

See also the Readline extension documentation for more functions which can be used to enhance command line applications in PHP.

On Windows, PHP can be configured to run without the need to supply the C:\php\php.exe or the .php extension, as described in Command Line PHP on Microsoft Windows.

Note:

On Windows it is recommended to run PHP under an actual user account. When running under a network service certain operations will fail, because «No mapping between account names and security IDs was done».

User Contributed Notes 7 notes

On Linux, the shebang (#!) line is parsed by the kernel into at most two parts.
For example:

1: #!/usr/bin/php
2: #!/usr/bin/env php
3: #!/usr/bin/php -n
4: #!/usr/bin/php -ddisplay_errors=E_ALL
5: #!/usr/bin/php -n -ddisplay_errors=E_ALL

1. is the standard way to start a script. (compare «#!/bin/bash».)

2. uses «env» to find where PHP is installed: it might be elsewhere in the $PATH, such as /usr/local/bin.

3. if you don’t need to use env, you can pass ONE parameter here. For example, to ignore the system’s PHP.ini, and go with the defaults, use «-n». (See «man php».)

4. or, you can set exactly one configuration variable. I recommend this one, because display_errors actually takes effect if it is set here. Otherwise, the only place you can enable it is system-wide in php.ini. If you try to use ini_set() in your script itself, it’s too late: if your script has a parse error, it will silently die.

5. This will not (as of 2013) work on Linux. It acts as if the whole string, «-n -ddisplay_errors=E_ALL» were a single argument. But in BSD, the shebang line can take more than 2 arguments, and so it may work as intended.

Summary: use (2) for maximum portability, and (4) for maximum debugging.

Источник

Выполнить скрипт PHP из другого скрипта PHP

Как я могу заставить свой сервер запускать php script путем запуска его вручную с помощью php? В основном у меня есть довольно большой файл cronjob, который запускается каждые 2 часа, но я хочу, чтобы иметь возможность запускать файл вручную самостоятельно, не дожидаясь его загрузки (я хочу, чтобы это было сделано на стороне сервера). EDIT: Я хочу выполнить файл из файла php. Не в командной строке.

Ответы были неверны только потому, что вы не включили важные вопросы в свой вопрос. Учитывая предоставленные вами данные, ответы на 100% правильные. Теперь, когда вы описали, что вы на самом деле пытаетесь сделать, ответы улучшатся. Очень просто, у вас нет причин для недовольства. Люди пытаются помочь.

10 ответов

Вы можете вызвать PHP script вручную из командной строки

hello.php Command line: php hello.php Output: hello world! 

EDIT OP отредактировал вопрос, чтобы добавить критическую деталь: script должен быть выполнен другим script.

Существует несколько подходов. Сначала и проще всего, вы можете просто включить файл. Когда вы включаете файл, код внутри «выполняется» (фактически, интерпретируется). Любой код, который не находится внутри функции или тела класса, будет обработан немедленно. Взгляните на документацию для include (docs) и/или require (docs) (примечание: include_once и require_once связаны друг с другом, но различны по-важному. Посмотрите документы, чтобы понять разницу). Ваш код будет выглядеть следующим образом:

 include('hello.php'); /* output hello world! */ 

Вторым и немного более сложным является использование shell_exec (docs). С помощью shell_exec вы вызовете двоичный код php и передадите искомый script в качестве аргумента. Ваш код будет выглядеть так:

$output = shell_exec('php hello.php'); echo "
$output

"; /* output hello world! */

Наконец, и самое сложное, вы можете использовать библиотеку CURL для вызова файла, как если бы он запрашивался через браузер. Ознакомьтесь с документацией библиотеки CURL здесь: http://us2.php.net/manual/en/ref.curl.php

$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.myDomain.com/hello.php"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) $output = curl_exec($ch); curl_close($ch); echo "
$output

"; /* output hello world! */

Документация для используемых функций

  • Командная строка: http://php.net/manual/en/features.commandline.php
  • include : http://us2.php.net/manual/en/function.include.php
  • require : http://us2.php.net/manual/en/function.require.php
  • shell_exec : http://us2.php.net/manual/en/function.shell-exec.php
  • curl_init : http://us2.php.net/manual/en/function.curl-init.php
  • curl_setopt : http://us2.php.net/manual/en/function.curl-setopt.php
  • curl_exec : http://us2.php.net/manual/en/function.curl-exec.php
  • curl_close : http://us2.php.net/manual/en/function.curl-close.php

Источник

How to Execute php file from another php

  • All categories
  • ChatGPT (11)
  • Apache Kafka (84)
  • Apache Spark (596)
  • Azure (145)
  • Big Data Hadoop (1,907)
  • Blockchain (1,673)
  • C# (141)
  • C++ (271)
  • Career Counselling (1,060)
  • Cloud Computing (3,469)
  • Cyber Security & Ethical Hacking (162)
  • Data Analytics (1,266)
  • Database (855)
  • Data Science (76)
  • DevOps & Agile (3,608)
  • Digital Marketing (111)
  • Events & Trending Topics (28)
  • IoT (Internet of Things) (387)
  • Java (1,247)
  • Kotlin (8)
  • Linux Administration (389)
  • Machine Learning (337)
  • MicroStrategy (6)
  • PMP (423)
  • Power BI (516)
  • Python (3,193)
  • RPA (650)
  • SalesForce (92)
  • Selenium (1,569)
  • Software Testing (56)
  • Tableau (608)
  • Talend (73)
  • TypeSript (124)
  • Web Development (3,002)
  • Ask us Anything! (66)
  • Others (2,231)
  • Mobile Development (395)
  • UI UX Design (24)

Join the world’s most active Tech Community!

Welcome back to the World’s most active Tech Community!

Subscribe to our Newsletter, and get personalized recommendations.

GoogleSign up with Google facebookSignup with Facebook

Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

  • DevOps Certification Training
  • AWS Architect Certification Training
  • Big Data Hadoop Certification Training
  • Tableau Training & Certification
  • Python Certification Training for Data Science
  • Selenium Certification Training
  • PMP® Certification Exam Training
  • Robotic Process Automation Training using UiPath
  • Apache Spark and Scala Certification Training
  • Microsoft Power BI Training
  • Online Java Course and Training
  • Python Certification Course
  • Data Scientist Masters Program
  • DevOps Engineer Masters Program
  • Cloud Architect Masters Program
  • Big Data Architect Masters Program
  • Machine Learning Engineer Masters Program
  • Full Stack Web Developer Masters Program
  • Business Intelligence Masters Program
  • Data Analyst Masters Program
  • Test Automation Engineer Masters Program
  • Post-Graduate Program in Artificial Intelligence & Machine Learning
  • Post-Graduate Program in Big Data Engineering

COMPANY

WORK WITH US

DOWNLOAD APP

appleplaystore googleplaystore

CATEGORIES

CATEGORIES

  • Cloud Computing
  • DevOps
  • Big Data
  • Data Science
  • BI and Visualization
  • Programming & Frameworks
  • Software Testing © 2023 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved. Terms & ConditionsLegal & Privacy

Источник

Оцените статью