简体   繁体   English

从Bash运行PHP文件

[英]Run PHP file from Bash

I need to run a script that will execute a php file but I can't run the PHP file from Bash Script 我需要运行将执行php文件的脚本,但无法从Bash脚本运行PHP文件

Test.sh: Test.sh:

#!/bin/sh
php /home/username/public_html/Test3/Test.php

Where is the error? 错误在哪里?

/var/log/cron : / var / log / cron:

Sep  7 22:56:01 srv CROND[4344]: (root) CMD (sh /home/Username/public_html/Test3/test.sh)

Test.php Test.php

<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $date = date('h:i:s');
    $sql = "UPDATE deneme SET CRONTEST='".$date."' WHERE id=1";

    $stmt = $conn->prepare($sql);

    $stmt->execute();

    echo $stmt->rowCount() . " records UPDATED successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?> 

Multiple ways to get this working. 有多种方法可以使其正常工作。 My first choice, call the PHP script directly from cron. 我的首选,直接从cron调用PHP脚本。 To do that, make sure your php script is executable (chmod 755) Make sure the CLI php script starts with.. 为此,请确保您的php脚本是可执行文件(chmod 755),请确保CLI php脚本以。开头。

#!/usr/bin/php
<?php

From a shell, type 'which php' and change the '/usr/bin...' line accordingly. 在外壳中,键入“哪个php”,并相应地更改“ / usr / bin ...”行。 Once those steps are done, your cron entry might look like . 完成这些步骤后,您的cron条目可能看起来像。 . .

*/5 * * * * /usr/bin/php -f /var/www/script.php

and again, make sure you point to php's actual location. 再次,确保您指向php的实际位置。
Tried explaining in comments, ran out of room :/ 试图在评论中解释,跑出房间了:/

I solved my question this method: 我用这种方法解决了我的问题:

#!/bin/bash

data=$(/usr/bin/php -q /home/username/public_html/Test3/Test.php);

But I can't variables, for example: 但是我不能变量,例如:

#!/bin/bash

data=$(/usr/bin/php -q /home/username/public_html/Test3/Test.php name=Saracoglu);

Its not working. 它不起作用。 I'm searching.. 我在搜寻..

I know it's old, but I just ran into this today. 我知道它很旧,但是今天我才碰到它。 Whenever a Bash script does not execute a PHP script (despite having correct permissions and the "php" command working on its own) , I found using the full path to PHP resolves it. 每当Bash脚本不执行PHP脚本时(尽管具有正确的权限并且“ php”命令自己运行) ,我发现使用PHP的完整路径可以解决该问题。 ie

#!/bin/bash

other code
...
/usr/bin/php /home/username/public_html/Test3/Test.php

You can use which php and whereis php to determine the correct path. 您可以使用which phpwhereis php来确定正确的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM