Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

system

(PHP 3, PHP 4, PHP 5)

system -- Execute an external program and display the output

Описание

string system ( string command [, int &return_var] )

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.

Список параметров

command

The command that will be executed.

return_var

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

Возвращаемые значения

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

Примеры

Пример 1. system() example

<?php
echo '<pre>';

// Outputs all the result of shellcommand "ls", and returns
// the last output line into $last_line. Stores the return value
// of the shell command in $retval.
$last_line = system('ls', $retval);

// Printing additional info
echo '
</pre>
<hr />Last line of the output: '
. $last_line . '
<hr />Return value: '
. $retval;
?>

Примечания

Внимание

Если вы собираетесь передавать функции данные, отправленные пользователем, вы должны использовать функции escapeshellarg() или escapeshellcmd() для того, чтобы обезопасить исполнение команд.

Замечание: Если вы собираетесь использовать эту функцию в программе, работающей в качестве демона, убедитесь, что стандартный вывод функции направлен в файл или другой поток, в противном случае PHP зависнет вплоть до конца выполнения программы.

Замечание: В случае работы в безопасном режиме, вы можете запускать что-либо только в пределах safe_mode_exec_dir. В настоящее время, использование .. в пути запрещено

Внимание

В случае работы в безопасном режиме, все слова, следующие за начальной командой, рассматриваются как единый аргумент. То есть echo y | echo x будет работать как echo "y | echo x".



PS> <shell_exec
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
system
toby at globaloptima dot co dot uk
20-Sep-2007 02:16
Regarding Billybob's comment about multi-line system commands like this:

$commandeDB1 = system ("cd \
                       cd mysql
                       cd bin
                       mysql -uroot -pedfdiver -P3307
                       use diver_1
                          insert into cdn_flv_8(flv_file,cdn_dn_or_ip,video_path,flv_groups
    values('$fichier','130.98.61.32','/diver_edf/video_1/','0');");

First things first, this kind of mysql interaction should be taken care of with the in-built mysql or mysqli PHP libraries, it make much more sense when you see it, loads and loads of tutorials online about this exact subject:

http://php.net/mysql

See how you can do exactly the same thing without using the system command:

$link = mysql_connect('localhost', 'root', 'edfdiver');
mysql_select_db('diver_1')
mysql_query("your insert sql here");
mysql_close($link);

Also you no longer rely on MySQL being located in a certain folder, your script is cross-platform, easier to understand and generally far more robust.

Regarding multi-line statements using the system function, the only way I've done this in the past is to separate each command with a semi-colon which in some cases is useful but most of the time seems to be a really bad way of doing things (this is using Linux, BASH Shell, I expect Windows has similar mechanism).

Note that you don't seem to be able to set shell variables either, again using BASH:

x=10;echo $x

This works on the command line, running via system prints an empty line, may be possible but I've not managed it yet.

Also in your example, commands 1,2,3 and 4 are for the Operating System whilst commands 5 and 6 are for MySQL, try putting a semi-colon between each of your commands to see what happens.

My advice, if you are new-ish to PHP, is to try and avoid the system/exec/passthru functions and stick with in-built PHP libraries where-ever possible, most things you want to do can be handled by these libraries.

And additions to this are welcome, I'm no expert, just a few things I've noticed.

Toby
Billybob
13-Sep-2007 07:39
Hi

I'm a newbie in php, and I was wondering if it's possible to use multiple line with "system". Here is an example:

$commandeDB1 = system ("cd \
                       cd mysql
                       cd bin
                       mysql -uroot -pedfdiver -P3307
                       use diver_1
                          insert into cdn_flv_8(flv_file,cdn_dn_or_ip,video_path,flv_groups
    values('$fichier','130.98.61.32','/diver_edf/video_1/','0');");

Thanks
willytk at gmail dot com
10-Sep-2007 05:39
If you're having problems with getting imagemagick/convert to work with ghostscript because the gs executable isn't in the apache PATH, do the following:

To create a thumb of the first pdf page:

<?php
$command
= 'export PATH=$PATH:/sw/bin; convert "files/example.pdf[0]" -thumbnail 150x150 "files/thumbs/example.png"';

$lastline = system($command,$return);
?>

Thanks entropy.ch and phpaladin!

Regards,

Willy T. Koch
Oslo, Norway
timgolding_10 at hotmail dot com
20-Jul-2007 07:19
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

<?PHP

$accepted_types
=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 <br />';
        if(!
file_exists($uploaddir)){
           
//Copy the file to some permanent location
           
if(move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $uploaddir))
             {
              echo
$uploaddir." was uploaded! <br />";
             }
            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'].'<br />';
?>
aaron at visual-code dot com
01-Jul-2007 04:41
Regarding the running of processes in the background.  i found that after a few different attempts that this worked fine and allowed the main script to continue unhindered.

Hope that this might help someone.

$arg1 = "arg1";
$arg2 = "arg2";
$page = "/path/tothe/script/scriptToRun.php";
$args = "--arg1='".urlencode($arg2)."' --arg2 ='".urlencode($arg2)."'";
$command = "(php -c /usr/local/lib/php.ini ".$page." ".$args." &) > /dev/null";
system($command);
eis
20-Jun-2007 02:11
It should be noted, too, that "unable to fork" error in Windows also occurs if you try to send a command that's too long for cmd.exe to process.
peter at randomnity dot com
28-Mar-2007 10:09
Just a note to dan at thecsl dot org

0 and FALSE are _NOT_ the same.
You can check for false like so:

<?php
if($return_val === FALSE) {
  
// ....
} else if ($return_val == 0) {
  
// ...
}
// Continue...
?>
jordan314 at mailinator dot com
20-Mar-2007 01:44
z1a7n8g, your system logging to file function was really useful, but had two errors:
$line=fgets($fPtr,filesize("yourfile.php");
that line needs a second closing ')'
and:
while ($line)
returns true until your script runs out of memory. Those two lines can be combined:
while($line=fgets($fPtr,filesize("yourfile.php")));
norman_ss at hotmail dot com
08-Mar-2007 03:43
thanks to tr4nc3,

I'm trying to, from the explorer, run an access's macro and this example give me the solution:

You can execute a .bat file with the especifications that give us tr4nc3.
After, in this .bat file, you can execute msacces.exe and pass /x parameter with the name of the macro. like this:

"c:\windows\system32\cmd.exe /c <path or the msaccess.exe>" <path of the .mdb file> /x <name of the macro>"

At the end of the .bat file you have to put "exit" and the thread will end.

Thanks to tr4nc3!
dotmg at wikk
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571