4D v14.3

PHP Execute

Home

 
4D v14.3
PHP
PHP Execute

PHP Execute 


 

PHP Execute ( scriptPath {; functionName {; phpResult {; param} {; param2 ; ... ; paramN}}} ) -> Function result 
Parameter Type   Description
scriptPath  Text in Pathname to PHP script or "" to execute a PHP function
functionName  Text in PHP function to be executed
phpResult  Operator, Variable, Field in Result of PHP function execution or * to not receive any result
param  Text, Boolean, Real, Longint, Date, Time in Parameter(s) of PHP function
Function result  Boolean in True = execution correct False = execution error

The PHP Execute command can be used to execute a PHP script or function.

Pass the pathname of the PHP script to be executed in the scriptPath parameter. This can be a relative pathname if the file is located next to the database structure or an absolute path. The pathname can be expressed in either the system syntax or POSIX syntax.
If you want to execute a standard PHP function directly, pass an empty string ("") in scriptPath. The function name must be passed in the second parameter

Pass a PHP function name in the functionName parameter if you want to execute a specific function in the scriptPath script. If you pass an empty string or omit the functionName parameter, the script is entirely executed.

Note: PHP is case sensitive for function names. Do not use parentheses, just enter the function name only.

The phpResult parameter receives the result of the execution of the PHP function. You can pass either:

  • a variable, an array or a field in order to receive the result,  
  • the * character if the function does not return any result or if you do not want to retrieve it.

The phpResult parameter can be of the Text, Longint, Real, Boolean, or Date type as well as (except for arrays) a field of the BLOB or Time type. 4D will carry out the conversion of the data and any adjustments needed according to the principles described in the Conversion of data returned section below. 

  • If you passed a function name in the functionName parameter, phpResult will receive what the PHP developer returned with the return command from the body of the function. 
  • If you use the command without passing a function name in the functionName parameter, phpResult will receive what the PHP developer returned with the echo command (or a similar command).

If you call a PHP function that expects arguments, use the param1...N parameters to pass one or more values. The values must be separated by semi-colons. You can pass values of the Alpha, Text, Boolean, Real, Integer, Longint, Date or Time type. Pictures and BLOBs are not accepted. You can send an array; in this case, you must pass a pointer to the array to the PHP Execute command, otherwise the current index of the array will be sent as an integer (see the example). The command accepts all types of arrays except for pointer, picture and 2D arrays.
The param1...N parameters are sent in PHP in the JSON format in UTF-8. They are automatically decoded with the PHP json_decode command before being sent to the PHP  functionName function.

Note: For technical reasons, the size of parameters passed via the FastCGI protocol must not exceed 64 KB. You need to take this limitation into account if you use parameters of the Text type.

The command returns True if the execution has been carried out correctly on the 4D side, in other words, if the launching of the execution environment, the opening of the script and the establishing of the communication with the PHP interpreter were successful. Otherwise, an error is generated, which you can intercept with the ON ERR CALL command and analyze with GET LAST ERROR STACK.
In addition, the script itself may generate PHP errors. In this case, you must use the PHP GET FULL RESPONSE command in order to analyze the source of the error (see example 4).

Note: PHP can be used to configure error management. For more information, please refer, for example, to the following page: http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting.

The following table specifies how 4D interprets and converts data that is returned according to the type of the phpResult parameter.

Type of phpResult parameterProcessing by 4DExample
BLOB4D recovers the data received without any modifications(*).
Text4D expects data encoded in UTF-8 (*). The PHP developer may need to use the PHP utf8_encode command.Example of PHP script:
echo utf8_encode(myText)
Date4D expects a date sent as a string in the RFC 3339 format (sometimes called DATE_ATOM in PHP). This format is of the type "YYYY-MM-DDTHH:MM:SS", for example: 2005-08-15T15:52:01+00:00. 4D ignores the time part and returns the date in UTC.
Time4D expects a time sent as a string in the RFC 3339 format  (see the Date type). 4D ignores the date part and returns the number of seconds elapsed since midnight while considering the date in the local time zone. Example of PHP script for sending 2h30'45":
echo date( DATE_ATOM, mktime( 2,30,45))
Integer or Real4D interprets the numerical value expressed with numbers, the + or - sign and/or the exponent prefixed by 'e'. Any '.' or ',' character is interpreted as a decimal separator.Example of PHP script:
echo -1.4e-16;
Boolean4D returns True if it receives the string "true" from PHP or if the numerical evaluation gives a value that is not Null.Example of PHP script:
echo (a==b);
Array4D considers that the PHP array was returned in the JSON format.Example of PHP script for returning an array of two texts:
echo json_encode( array( "hello", "world"));

(*) By default, HTTP headers are not returned:
- If you use PHP Execute by passing a function in the functionName parameter, HTTP headers are never returned in phpResult. They are only available through the PHP GET FULL RESPONSE command.
- If you use PHP Execute without a function name (the functionName parameter is omitted or contains an empty string), you can return HTTP headers by setting the PHP Raw result option to True using the PHP SET OPTION command.

Note: If you need to recover large volumes of data using PHP, it is usually more efficient to pass by the stdOut buffer (echo command or similar) rather than by the function return. For more information, refer to the description of the PHP GET FULL RESPONSE command.

You can use the SET ENVIRONMENT VARIABLE command to specify the environment variables used by the script. Warning: after calling LAUNCH EXTERNAL PROCESS or PHP Execute, the set of environment variables is erased.

4D provides the following special functions:

  • quit_4d_php: used to quit the PHP interpreter and all its child processes. If at least one child process is executing a script, the interpreter does not quit and the PHP Execute command returns False.
  • relaunch_4d_php: used to relaunch the PHP interpreter.

Note that the interpreter is relaunched automatically when the first request is sent by PHP Execute.

Calling the "myPhpFile.php" script without any function. Here are the contents of the script:

<?php
echo 'Current PHP version: ' . phpversion();
?>

The following 4D code:

 C_TEXT($result)
 C_BOOLEAN($isOK)
 $isOK:=PHP Execute("C:\\php\\myPhpFile.php";"";$result)
 ALERT($Result)

... will display "Current PHP version: 5.3"

Calling the myPhpFunction function in the "myNewScript.php" script with parameters. Here are the contents of the script:

<?php
// . . . PHP code. . .
function myPhpFunction($p1, $p2) {
    return $p1 . ' '. $p2;
}
// . . . PHP code.. . .
?>

Calling with function:

 C_TEXT($result)
 C_TEXT($param1)
 C_TEXT($param2)
 C_BOOLEAN($isOk)
 $param1 :="Hello"
 $param2 :="4D world!"
 $isOk:=PHP Execute("C:\\MyFolder\\myNewScript.php";"myPhpFunction";$result;$param1;$param2)
 ALERT($result// Displays "Hello 4D world!"

Quitting the PHP interpreter:

 $ifOk:=PHP Execute("";"quit_4d_php")

Error management:

  // Installation of the error-management method
 phpCommError:="" // Modified by PHPErrorHandler
 $T_saveErrorHandler :=Method called on error
 ON ERR CALL("PHPErrorHandler")</p><p> // Execution of script
 C_TEXT($T_result)
 If(PHP Execute("C:\\MyScripts\\MiscInfos.php";"";$T_result))
  // No error, $T_Result contains the result
 Else
  // An error is detected, managed by PHPErrorHandler
    If(phpCommError="")
       ... // PHP error, use PHP GET FULL RESPONSE
    Else
       ALERT(phpCommError)
    End if
 End if
 
  // Uninstalling method
 ON ERR CALL($T_saveErrorHandler)

The PHP_errHandler method is as follows:

 phpCommError:=""
 GET LAST ERROR STACK(arrCodes;arrComps;arrLabels)
 For($i;1;Size of array(arrCodes))
    phpCommError:=phpCommError+String(arrCodes{$i})+" "+arrComps{$i}+" "+
    arrLabels{$i}+Char(Carriage return)
 End for

Dynamic creation by 4D of a script before its execution:

 DOCUMENT TO BLOB("C:\\Scripts\\MyScript.php";$blobDoc)
 If(OK=1)
    $strDoc:=BLOB to text($blobDoc;UTF8 text without length)
 
    $strPosition:=Position("function2Rename";$strDoc)
 
    $strDoc:=Insert string($strDoc;"_v2";Length("function2Rename")+$strPosition)
 
    TEXT TO BLOB($strDoc;$blobDoc;UTF8 text without length)
    BLOB TO DOCUMENT("C:\\Scripts\\MyScript.php";$blobDoc)
    If(OK#1)
       ALERT("Error on script creation")
    End if
 End if

The script is then executed:

 $err:=PHP Execute("C:\\Scripts\\MyScript.php";"function2Rename_v2";*)

Direct retrieval of a Date and Time type value. Here are the contents of the script:

<?php
// . . . code php. . .
echo date(DATE_ATOM, mktime(1, 2, 3, 4, 5, 2009));
// . . . code php. . .
?>

Receiving the date on the 4D side:

 C_DATE($phpResult_date)
 $result :=PHP Execute("C:\php_scripts\ReturnDate.php";"";$phpResult_date)
  //$phpResult_date is !05/04/2009 !
 
 C_TIME($phpResult_time)
 $result :=PHP Execute("C:\php_scripts\ReturnDate.php";"";$phpResult_time)
  //$phpResult_time is ?01 :02 :03 ?

Distribution of data in arrays:

 ARRAY TEXT($arText ;0)
 ARRAY LONGINT($arLong ;0)
 $p1 :=","
 $p2 :="11,22,33,44,55"
 $phpok :=PHP Execute("";"explode";$arText;$p1;$p2)
 $phpok :=PHP Execute("";"explode";$arLong;$p1;$p2)
 
  // $arText contains the Alpha values "11", "22", "33", etc.
  // $arLong contains the numbers, 11, 22, 33, etc.

Initialization of an array:

 ARRAY TEXT($arText ;0)
 $phpok :=PHP Execute("";"array_pad";$arText;->$arText;50;"undefined")
  // Execute in PHP: $arrTest = array_pad($arrTest, 50, ’undefined’);
  // Fills the $arText array with 50 "undefined" elements

Passing of parameters via an array:

 ARRAY INTEGER($arInt;0)
 $phpok :=PHP Execute("";"json_decode";$arInt;"[13,51,69,42,7]")
  // Execute in PHP: $arInt = json_decode(’[13,51,69,42,7]’);
  // Fills the array with the initial values

Here is an example of the basic use of the trim function, to remove extra spaces and/or invisible characters from the beginning and end of a string:

 C_TEXT($T_String)
 $T_String:="   Hello  "
 C_BOOLEAN($B)
 $B:=PHP Execute("";"trim";$T_String;$T_String)

For more information concerning the trim function, please refer to the PHP documentation.

 
PROPERTIES 

Product: 4D
Theme: PHP
Number: 1058

 
HISTORY 

Created: 4D v12
Modified: 4D v12.1

 
SEE ALSO 

Executing PHP scripts in 4D
PHP GET FULL RESPONSE
PHP SET OPTION

 
ARTICLE USAGE

4D Language Reference ( 4D v12.4)
4D Language Reference ( 4D v14 R2)
4D Language Reference ( 4D v14 R3)
4D Language Reference ( 4D v13.5)
4D Language Reference ( 4D v14.3)
4D Language Reference ( 4D v14 R4)