Php system error stream



system

(PHP 4, PHP 5, PHP 7, PHP 8)

system — Execute an external program and display the output

Description

system() is just like the C version of the function in that it executes the given command and outputs the result.

The system() call also tries to automatically flush the web server’s output buffer after each line of output if PHP is running as a server module.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

Parameters

The command that will be executed.

If the result_code argument is present, then the return status of the executed command will be written to this variable.

Return Values

Returns the last line of the command output on success, and false on failure.

Examples

Example #1 system() example

Notes

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

See Also

  • exec() — Execute an external program
  • passthru() — Execute an external program and display raw output
  • popen() — Opens process file pointer
  • escapeshellcmd() — Escape shell metacharacters
  • pcntl_exec() — Executes specified program in current process space
  • backtick operator

User Contributed Notes 19 notes

This is for WINDOWS users. I am running apache and I have been trying for hours now to capture the output of a command.

I’d tried everything that is written here and then continued searching online with no luck at all. The output of the command was never captured. All I got was an empty array.

Finally, I found a comment in a blog by a certain amazing guy that solved my problems.

Adding the string ‘ 2>&1’ to the command name finally returned the output!! This works in exec() as well as system() in PHP since it uses stream redirection to redirect the output to the correct place!

You probably want to check your system calls for errors. The convention is to return 0 for «no error» which is the same as FALSE which can be confusing. You need to do something like:

= «/usr/bin/pngtopnm $png_file > $pnm_file » ;
system ( $cmd , $return_value );
( $return_value == 0 ) or die( «returned an error: $cmd » );
?>

another reason to use shell_exec instead of system is when the result is multiple lines such as grep or ls

// this correctly sets answer string to all lines found
//$answer = shell_exec («grep ‘set of color names’ *.php «);
//echo «answer = $answer»;

// this passes all lines to output (they show on page)
// and sets answer string to the final line
$sys = system ( «grep ‘set of color names’ *.php » );
echo «sys =(( $sys ))» ;

?>

here is view/source resulting from system call

setprefs.php:// The standard set of color names is:
setprefs.php:// Most browsers accept a wider set of color names
silly.php: //$answer = shell_exec («grep ‘set of color names’ *.php «);
silly.php: $sys = system («grep ‘set of color names’ *.php «);
sys =((silly.php: $sys = system («grep ‘set of color names’ *.php «);))

and here is view source from using shell_exec instead

answer = setprefs.php:// The standard set of color names is:
setprefs.php:// Most browsers accept a wider set of color names
silly.php: $answer = shell_exec («grep ‘set of color names’ *.php «);
silly.php:// $sys = system («grep ‘set of color names’ *.php «);

It’s important to note that if you are running a series of system() commands in a loop, you need to include the second argument in order for them to run synchonously.

// this will execute process.php asynchronously; not waiting for completion before executing the next one.
$array = array(‘apple’, ‘banana’, ‘pear’);
foreach($array as $i)
<
system(«php process.php \»fruit=$i\»»);
>

// this will execute process.php 3 times, waiting for the prior command to complete before starting a new one
$array = array(‘apple’, ‘banana’, ‘pear’);
foreach($array as $i)
<
system(«php process.php \»fruit=$i\»», $status);
>

Читайте также:  Golang http error response

Do not use «system» if you use the «php.ini» option:
zlib.output_compression = On

Doing so will result in the browser receiving garbage (I’m guessing the headers/buffers get confused).

Use passthru in this case, it appears to work as intended.

If you can’t see any output or error from system(), shell_exec() etc, you could try this:

function my_exec ( $cmd , $input = » )
< $proc = proc_open ( $cmd , array( 0 =>array( ‘pipe’ , ‘r’ ), 1 =>array( ‘pipe’ , ‘w’ ), 2 =>array( ‘pipe’ , ‘w’ )), $pipes );
fwrite ( $pipes [ 0 ], $input ); fclose ( $pipes [ 0 ]);
$stdout = stream_get_contents ( $pipes [ 1 ]); fclose ( $pipes [ 1 ]);
$stderr = stream_get_contents ( $pipes [ 2 ]); fclose ( $pipes [ 2 ]);
$rtn = proc_close ( $proc );
return array( ‘stdout’ => $stdout ,
‘stderr’ => $stderr ,
‘return’ => $rtn
);
>
var_export ( my_exec ( ‘echo -e $( , ‘h\\nel\\nlo’ ));
?>

For example, «echo shell_exec(‘ls’);» will get nothing output,
«my_exec(‘ls’);» will get «sh: ls: command not found»,
«my_exec(‘/bin/ls’);» will maybe get «sh: /bin/ls: Permission denied»,
and the permission may be caused by selinux.

An example of using the system to call the file command on a linux server. This script detects whether a user posted file is a jpeg, gif or png

=array( «JPEG» , «GIF» , «PNG» );

// The temporary filename of the file in which the uploaded file was stored on the server.
if(!empty( $_FILES [ «uploadedfile» ]))
<
$uploaddir = $_SERVER [ ‘DOCUMENT_ROOT’ ]. «/images/» ;
$uploaddir .= basename ( $_FILES [ ‘uploadedfile’ ][ ‘name’ ]);

//verfiy file using linux FILE command
$last_line = system ( ‘file ‘ . escapeshellarg ( $_FILES [ ‘uploadedfile’ ][ ‘tmp_name’ ]), $retval );

//get the file extension returned through magic database
$splitvals = explode ( ‘ image data’ , $last_line );
$vals = explode ( ‘:’ , $splitvals [ 0 ]);
$vals [ 1 ]= str_replace ( ‘ ‘ , » , $vals [ 1 ]);

if ( in_array ( $vals [ 1 ], $accepted_types ))
<
echo $vals [ 1 ]. ‘ was accepted
‘ ;
if(! file_exists ( $uploaddir )) <
//Copy the file to some permanent location
if( move_uploaded_file ( $_FILES [ «uploadedfile» ][ «tmp_name» ], $uploaddir ))
<
echo $uploaddir . » was uploaded!
» ;
>
else
<
echo «There was a problem when uploding the new file, please contact admin about this.» ;
>
>
else echo ‘This file already exists in DB please rename file before uploading’ ;
>
>else echo $_FILES [ ‘uploadedfile’ ][ ‘error’ ]. ‘
‘ ;
?>

To run a full screen program from a PHP CLI script, redirect input from and output to /dev/tty. For example:

Windows commands requiring a GUI.

Alot of the info on this topic is from the 2010-2012 time frame and referring to XP, and basically don’t work. I am using apache/php/mysql in windows 7.

When requiring a system command in windows with a GUI — such as a labview executable, notepad, etc. others have mentioned the psexec command from sysinternals, since cmd /c wont work, but the specific use was not real clearly defined. Here is what worked for me on windows 7:

system(‘C:/nttools/2019/psexec \\\\10.100.100.101 -i -u administrator -p password -accepteula -nobanner C:\\htdocs\\test\\test.bat’);

The path to the psexec executable is with forward slashes, the remote PC network location (which was actually the local PC, not remote) was \\ip_address with an extra backslash for each backslash so that required the 4 \’s.

The path for the command to be executed by psexec required backslashes, which also requires double backslashes.

The -i option is for an interactive program, and is required for it to properly run, otherwise it show up in the taskmanager but not be visable or execute properly if given command line arguments.

The -accepteula -nobanner is to suppress the sysinternals message box about their license.

My command to execute is really long with multiple command line inputs with many surrounded in double quotes, so I thought it would be easiest to put that in a batch file and just call the bat file. Works great, remote users loading the webpage causes the executable to pop up on the web server, do its analysis and disappear. Labview can read native excel files with active-x functions and write to a mysql data base to store results etc, so thats a pretty powerful combination of functions.

Читайте также:  Format exception only one

Источник

error_log

(PHP 4, PHP 5, PHP 7, PHP 8)

error_log — Send an error message to the defined error handling routines

Description

Sends an error message to the web server’s error log or to a file.

Parameters

The error message that should be logged.

Says where the error should go. The possible message types are as follows:

error_log() log types

message is sent to PHP’s system logger, using the Operating System’s system logging mechanism or a file, depending on what the error_log configuration directive is set to. This is the default option.
1 message is sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, additional_headers is used.
2 No longer an option.
3 message is appended to the file destination . A newline is not automatically added to the end of the message string.
4 message is sent directly to the SAPI logging handler.

The destination. Its meaning depends on the message_type parameter as described above.

The extra headers. It’s used when the message_type parameter is set to 1 . This message type uses the same internal function as mail() does.

Return Values

Returns true on success or false on failure. If message_type is zero, this function always returns true , regardless of whether the error could be logged or not.

Changelog

Version Description
8.0.0 destination and additional_headers are now nullable.

Examples

Example #1 error_log() examples

// Send notification through the server log if we can not
// connect to the database.
if (! Ora_Logon ( $username , $password )) <
error_log ( «Oracle database not available!» , 0 );
>

// Notify administrator by email if we run out of FOO
if (!( $foo = allocate_new_foo ())) <
error_log ( «Big trouble, we’re all out of FOOs!» , 1 ,
«operator@example.com» );
>

// another way to call error_log():
error_log ( «You messed up!» , 3 , «/var/tmp/my-errors.log» );
?>

Notes

error_log() is not binary safe. message will be truncated by null character.

message should not contain null character. Note that message may be sent to file, mail, syslog, etc. Use appropriate conversion/escape function, base64_encode() , rawurlencode() or addslashes() before calling error_log() .

User Contributed Notes 20 notes

Advice to novices: This function works great along with «tail» which is a unix command to watch a log file live. There are versions of Tail for Windows too, like Tail for Win32 or Kiwi Log Viewer.

Using both error_log() and tail to view the php_error.log you can debug code without having to worry so much about printing debug messages to the screen and who they might be seen by.

Further Note: This works even better when you have two monitors setup. One for your browser and IDE and the other for viewing the log files update live as you go.

DO NOT try to output TOO LARGE texts in the error_log();

if you try to output massive amounts of texts it will either cut of the text at about 8ooo characters (for reasonable massive strings,

There is a limit on the maximum length that you can pass as the $message.

The default seem to be 1024 but can be changed by adjusting the value of the runtime configuration value of ‘log_errors_max_len’.

Beware! If multiple scripts share the same log file, but run as different users, whichever script logs an error first owns the file, and calls to error_log() run as a different user will fail *silently*!

Nothing more frustrating than trying to figure out why all your error_log calls aren’t actually writing, than to find it was due to a *silent* permission denied error!

when using error_log to send email, not all elements of an extra_headers string are handled the same way. «From: » and «Reply-To: » header values will replace the default header values. «Subject: » header values won’t: they are *added* to the mail header but don’t replace the default, leading to mail messages with two Subject fields.

( «sometext» , 1 , «zigzag@my.domain» ,
«Subject: Foo\nFrom: Rizzlas@my.domain\n» );

You can easily filter messages sent to error_log() using «tail» and «grep» on *nix systems. This makes monitoring debug messages easy to see during development.

Be sure to «tag» your error message with a unique string so you can filter it using «grep»:

error_log(«DevSys1 — FirstName: $FirstName — LastName: $Lastname»);

On your command line:

tail -f /var/log/httpd/error_log | grep DevSys1

In this example, we pipe apache log output to grep (STDIN) which filters it for you only showing messages that contain «DevSys1».

The «-f» option means «follow» which streams all new log entries to your terminal or to any piped command that follows, in this case «grep».

Relative paths are accepted as the destination of message_type 3, but beware that the root directory is determined by the context of the call to error_log(), which can change, so that one instance of error_log () in your code can lead to the creation of multiple log files in different locations.

In a WordPress context, the root directory will be the site’s root in many cases, but it will be /wp-admin/ for AJAX calls, and a plugin’s directory in other cases. If you want all your output to go to one file, use an absolute path.

When logging to apache on windows, both error_log and also trigger_error result in an apache status of error on the front of the message. This is bad if all you want to do is log information. However you can simply log to stderr however you will have to do all message assembly:

LogToApache($Message) <
$stderr = fopen(‘php://stderr’, ‘w’);
fwrite($stderr,$Message);
fclose($stderr);
>

«It appears that the system log = stderr if you are running PHP from the command line»

Actually, it seems that PHP logs to stderr if it can’t write to the log file. Command line PHP falls back to stderr because the log file is (usually) only writable by the webserver.

Note that since typical email is unencrypted, sending data about your errors over email using this function could be considered a security risk. How much of a risk it is depends on how much and what type of information you are sending, but the mere act of sending an email when something happens (even if it cannot be read) could itself imply to a sophisticated hacker observing your site over time that they have managed to cause an error.

Of course, security through obscurity is the weakest kind of security, as most open source supporters will agree. This is just something that you should keep in mind.

And of course, whatever you do, make sure that such emails don’t contain sensitive user data.

Another trick to post «HTML» mail body. Just add «Content-Type: text/html; charset=ISO-8859-1» into extra_header string. Of course you can set charset according to your country or Env or content.

stuff

«,1,»eat@joe.com»,»subject :lunch\nContent-Type: text/html; charset=ISO-8859-1″);

//Multiline error log class
// ersin güvenç 2008 eguvenc@gmail.com
//For break use «\n» instead ‘\n’

Class log <
//
const USER_ERROR_DIR = ‘/home/site/error_log/Site_User_errors.log’ ;
const GENERAL_ERROR_DIR = ‘/home/site/error_log/Site_General_errors.log’ ;

/*
User Errors.
*/
public function user ( $msg , $username )
<
$date = date ( ‘d.m.Y h:i:s’ );
$log = $msg . » | Date: » . $date . » | User: » . $username . «\n» ;
error_log ( $log , 3 , self :: USER_ERROR_DIR );
>
/*
General Errors.
*/
public function general ( $msg )
<
$date = date ( ‘d.m.Y h:i:s’ );
$log = $msg . » | Date: » . $date . «\n» ;
error_log ( $msg . » | Tarih: » . $date , 3 , self :: GENERAL_ERROR_DIR );
>

$log = new log ();
$log -> user ( $msg , $username ); //use for user errors
//$log->general($msg); //use for general errors
?>

Depending on the error, you may also want to add an error 500 header, and a message for the user:

$message = ‘Description of the error.’;
error_log($message);
header($_SERVER[‘SERVER_PROTOCOL’] . ‘ 500 Internal Server Error’, true, 500);
exit($message);

When error_log() unexpectedly uses stdout, you should check if the php.ini value for error_log is empty in your CLI environment. Something as simple as this might restore expected behavior:

After scouring the internet for getting event logging to
work in syslog on Windows 2003, I found the following
from this post and was able to successfully get Windows
Event Viewer to log PHP errors/notices:

Источник

Оцените статью
toolgir.ru
Adblock
detector