Portrety Uliczne Nieznajomych - zobacz wyjątkową galerię portretów z warszawskich ulic
ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Google Plus
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 29
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
Przyznam, że jestem pod sporym wrażeniem. Od wielu lat zajmuje się grafiką przeznaczoną do druku ze szczególnym uwzględnieniem opakowań. Z radością stwierdzam, iż twórca serwisu jest moim ulubionym typem potencjalnego współpracownika (choć branża troszeczkę inna) tzn. pada pytanie i błyskawicznie pada konkretna odpowiedź bez względu na stopień skomplikowania pytania. Gorąco polecam współpracę, gdyż macie pewność że nie zostaniecie potraktowani sloganami typu "oczywiście", "nie ma sprawy" tylko otrzymacie konkretną pomoc. Tak trzymać! Na pewno jeszcze nie raz skorzystam

Paweł
Studio Gama

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

popen

(PHP 3, PHP 4, PHP 5)

popen -- Otwiera wskaźnik pliku do procesu

Opis

resource popen ( string polecenie, string tryb )

Otwiera potok do procesu uruchomionego przez rozwidlenie polecenia (ang. forking) podanego w parametrze polecenie.

Zwraca wskaźnik pliku identyczny do tego zwracanego przez fopen() z wyjątkiem tego, że jest on jednokierunkowy (może być tylko użyty do odczytu lub zapisu) i musi być zamknięty za pomocą pclose(). Wskaźnik ten może być użyty z fgets(), fgetss() i fwrite().

W przypadku błędu, zwraca FALSE.

Notatka: Jeśli szukasz dwukierunkowej obsługi (w obie strony), użyj proc_open().

Przykład 1. popen() przykład

<?php
$uchwyt
= popen("/bin/ls", "r");
?>

Jeśli polecenie uruchamiane nie może zostać znalezione, poprawny zasób jest zwracany. To może wydawać się dziwne, ale ma sens; pozwala tobie na dostęp do wszystkich informacji o błędach zwracanych przez powłokę.

<?php
error_reporting
(E_ALL);

/* Dodanie przekierowania, aby móc dostać stderr. */
$uchwyt = popen('/sciezka/do/czegos 2>&1', 'r');
echo
"'$uchwyt'; " . gettype($uchwyt) . "\n";
$czytaj = fread($uchwyt, 2096);
echo
$czytaj;
pclose($uchwyt);
?>

Notatka: Jeśli tryb bezpieczny został włączony, możliwe jest wykonywanie programów tylko z katalogu określonego przez safe_mode_exec_dir. Ze względów praktycznych, nie można podawać elementów .. w ścieżce do pliku wykonywalnego.

Ostrzeżenie

Jeśli włączony jest tryb bezpieczny, wszystkie słowa następujące po nazwie polecenia są traktowane jako pojedyńczy argument. A więc, polecenie echo y | echo x staje się echo "y | echo x".

Patrz także pclose(), fopen() i proc_open().




User Contributed Notes

don at digithink dot com
20-Dec-2005 01:28

// The above import function can be easily extended using
// /usr/local/bin/xls2csv (part of catdoc ) and popen
// to read excell files directly.
// In our particular application the first line was the file heading.
function importxls($file,$head=true,$throwfirst=true,$delim=",",$len=1000) {
   $return = false;
   $handle = popen("/usr/local/bin/xls2csv $file", "r");
// or die if not there.
   if ($throwfirst) {
       $throw = fgetcsv($handle, $len, $delim);
   }
   if ($head) {
       $header = fgetcsv($handle, $len, $delim);
   }
   while (($data = fgetcsv($handle, $len, $delim)) !== FALSE) {
       if ($head AND isset($header)) {
           foreach ($header as $key=>$heading) {
               $row[$heading]=(isset($data[$key])) ? $data[$key] : '';
               print "<li>". $heading ."=>" . $row[$heading]."</li>";
           }
           $return[]=$row;
       } else {
           $return[]=$data;
       }
   }
   fclose($handle);
   return $return;
}


rjl at xs4all dot nl
23-Nov-2005 10:16

Truncated output from ps command?

The solution lies in the way ps displays it's info
specifically the -w option which:
'uses 132 columns to display information,
instead of the default which is your window size.'....
somehow with fgets in php that results in 74 characters
regardless off the init length parameter

a bit of code:

echo '<table width="99%"><tr><td>cron</td></tr>' . "\n";
$fp=popen("/bin/ps -waux","r");
while (!feof($fp)) {
   $buffer = fgets($fp, 4096);
   $croninf .= '<tr><td>' . $buffer . '</td></tr>' . "\n";
}
pclose($fp);
echo $croninf;
echo '</table><br><br>' . "\n";

Ciao,

Rene =<>=


erb at agricola-gymnasium dot de
06-Oct-2005 02:48

Writing and executing a bash script is as simple as that:

$f = popen ("/bin/bash","w");
fwrite($f, "export KRB5CCNAME=`tempfile`\n");
fwrite($f, "export KRBTKFILE=`tempfile`\n");
fwrite($f, "$KINIT --keytab=$GLOBALS["KADMIN_KEYFILE"] --use-keytab --afslog $GLOBALS["KADMIN_PRINC"]\n");
fwrite($f, "pts delete $uid\n");
fwrite($f, "fs rmmount $rwhome\n");
fwrite($f, "vos remove sanjo b user.$uid\n");
fwrite($f, "$KDESTROY\n");
pclose($f);


Cride5
09-Sep-2005 02:39

Here is a nice little script for monitoring your http access log.

<?php

$handle
= popen("tail -f /etc/httpd/logs/access.log 2>&1", 'r');
while(!
feof($handle)) {
  
$buffer = fgets($handle);
   echo
"$buffer<br/>\n";
  
ob_flush();
  
flush();
}
pclose($handle);

?>

----
www.eviltree.co.uk
www.solidsites.co.uk
www.mongbong.com


atampone at NOSPAMFORME dot trdsupra dot com
20-Jun-2005 03:26

If you want to fork a process under windows, this is the function to use.  I created a batch file called runcmd.bat with the following line

start %1 %2 %3 %4

then I have the folowing function

<?
define
('RUNCMDPATH', 'c:\\htdocs\\nonwebspace\\runcmd.bat');

function
runCmd($cmd) {
  
$externalProcess=popen(RUNCMDPATH.' '.$cmd, 'r');
  
pclose($externalProcess);
}   
?>

with this, doing something like

<? runCmd('php.exe printWorkOrder.php 3498'); ?>
will launch php.exe outside of apache and allow the script calling the runCmd() function to continue without waiting for the command line process to return.  The process will run under the same user account that Apache (or whatever webserver you're running) is running under, so make sure it has permissions to do whatever you need to do.  Also, make sure that the batch file has enough %n s in order to pass all the command line variables that you might need to pass.

Special thanks to kicken from the devshed forums for coming up with the idea.


electronerd at monolith3d dot com
26-May-2005 08:46

In response to shaun at nospam dot phplabs dot com:

fread() does not guarantee that all the expected data is read. The length argument is only an upper limit. If there isn't more data immediately available, fread() may return early.


PGP Dude
07-May-2005 07:52

I should say, my host uses a modified form of safe mode, so I don't know if that might have caused a problem with "popen" as opposed to "proc_open".  The warning below does NOT appear on the proc_open page:

quote:
With safe mode enabled, all words following the initial command string are treated as a single argument. Thus, echo y | echo x becomes echo "y | echo x".


PGP Dude
06-May-2005 09:30

LinixDude010's srcipt did not work for me.  Seems wrong to read and write with popen, according to the manual.

The script produced pgp text, but there was something wrong with the text and I could not decode it.

This replacement script, using proc_open, which can read and write, DOES work:

<?php
function pgp_encrypt($keyring_location, $public_key_id, $plain_text) {
 
$encrypted_text='';
 
$key_id = EscapeShellArg($public_key_id);
 
putenv("PGPPATH=$keyring_location");

 
// encrypt the message
 
$descriptorspec = array(
  
0 => array("pipe", "r"),  // stdin
  
1 => array("pipe", "w"),  // stdout
  
2 => array("pipe", "w"// stderr ?? instead of a file
 
);
 
$process = proc_open("pgpe -r $key_id -af", $descriptorspec, $pipes);
  if (
is_resource($process)) {
  
fwrite($pipes[0], $plain_text);
  
fclose($pipes[0]);
   while(
$s= fgets($pipes[1], 1024)) {
        
// read from the pipe
        
$encrypted_text .= $s;
   }
  
fclose($pipes[1]);
  
// optional:
  
while($s= fgets($pipes[2], 1024)) {
    
$encrypted_text.= "\n<p>Error: $s</p>\n";
   }
  
fclose($pipes[2]);
  }
  return
$encrypted_text;
}

$message = pgp_encrypt("/home/username/.pgp", "to@domain.com", "dummy text to be encrypted");
print
nl2br($message);

?>


shaun at nospam dot phplabs dot com
27-Feb-2005 02:52

Note that there appears to be a limit to the amount of data that fread() will return from a handle opened with popen(). A call to fread() may not return as much as you ask for.

For example, suppose I have a file "myfile.txt" which is more than 10KB in size. The following code works as expected:

<?php
$fp
= fopen('myfile.txt', 'r');
$data = fread($fp, 10240);
echo
strlen($data);
?>

The output is '10240.' However, popen() behaves differently:

<?php
$fp
= popen('/bin/cat myfile.txt', 'r');
$data = fread($fp, 10240);
echo
strlen($data);
?>

On my system, this code prints out '8192' instead of the expected '10240.'


webmaster at elcurriculum dot com
09-Dec-2004 09:05

This function send an email in html format.

function SendEmail($to,$asunto,$html,$from) {
   $fd = popen("/usr/sbin/sendmail -t", "w");
   fputs($fd, "Content-type: text/html\r\n");
   fputs($fd, "To: $to\r\n");
   fputs($fd, "From: TRYKE <" . $from . ">\r\n");
   fputs($fd, "Subject: $asunto\r\n");
   fputs($fd, "X-Mailer: PHP3\r\n\r\n");
   fputs($fd, $html);
   pclose($fd);
}

Examples:
SendEmail("tryke@hot.com","My Subject","<h1>Hi,<br>How are you?</h1>","miemail@midomain.com");

More:
http://tryke.blogcindario.com


kalvinb602 at hotmail dot com
07-Jul-2004 12:42

If you're having trouble with the server (Apache) hanging when issuing system commands consider the following bug report:

http://bugs.php.net/bug.php?id=22526

basically, if you're using sessions issue a

session_write_close();

command before you execute your system command to keep the server from hanging.

This may also correct the problem when using other system command executing functions like exec.

Ben


Michel Machado
07-Mar-2004 02:53

Yet another workaround for not having bidirectional pipes in php.

$Cmd =
"bc 2>&1 << END\n" .
"100+221\n" .
"1+3*3\n" .
"quit\n" .
"END\n";

$fp = popen($Cmd, 'r');
$read = fread($fp, 1024);
echo $read;
pclose($fp);


http://vmlinuz.nl/about/contact/
11-Nov-2002 05:58

From the popen linux programmers manual:
<quote>The  command  argument  is  a pointer to a null-terminated string containing a shell command line.  This  command  is passed  to  /bin/sh  using the -c flag.</quote>

Since php uses this popen function, you need to be sure /bin/sh exists. This file may not exist in chroot()ed environments.


ajv-php at erkle dot org
08-Aug-2002 08:02

I noticed that some of the examples above seem to advocate passing unencrypted data to gpg via the pipe shell escape, in the absence of a bi-directional popen (on some OSes).

The approach I've taken is similar to:

  $prefix = 'example';
  $command = '/usr/local/bin/gpg --encrypt --armor --no-tty --batch --no-secmem-warning --recipient "joe.soap@example.com"';
  $tmpfile = tempnam('/tmp', $prefix);
  $pipe = popen("$command 2>&1 >$tmpfile", 'w');
  if (!$pipe) {
   unlink($tmpfile);
  } else {
   fwrite($pipe, $plaintxt, strlen($plaintxt));
   pclose($pipe);
   $fd = fopen($tmpfile, "rb");
   $output = fread($fd, filesize($tmpfile));
   fclose($fd);
   unlink($tmpfile);
  }
  return $output;

This means that unencrypted information is not passed via a (potentially readable) shell command, and only encrypted information gets stored on disc.


12-Jul-2002 11:33

Here is a workaround for not having bidirectional pipes in php.

If you have bidirectional pipe support, don't bother with this.

The trick here is to send the input on the command line to the target application.  In particular I wanted to use openssl without using temp files or named pipes.  This solution should also be thread/process safe.

This does work on Linux (RedHat 7).

function filterThroughCmd($input, $commandLine) {
  $pipe = popen("echo \"$input\"|$commandLine" , 'r');
  if (!$pipe) {
   print "pipe failed.";
   return "";
  }
  $output = '';
  while(!feof($pipe)) {
   $output .= fread($pipe, 1024);
  }
  pclose($pipe);
  return $output;
}

# example:
print filterThroughCmd("hello", "cat");
# Piping to cat has the effect of echoing your input.


cyberlot at cyberlot dot net
30-Jun-2002 10:29

The below code works for both way processing ;) Have fun folks

<?
   system
("mkfifo pipeout");
  
$pipe = popen("./nwserver -module Chapter1E > pipeout","w");
  
$pipeout = fopen("pipeout", "r");
   while (
$s = fgets($pipeout,1024)) {
   echo
$s;
   }

?>


linuxdude010 at yahoo dot com
24-May-2002 08:49

I had all kinds of trouble encrypting a message with PGP, but I finanlly got it to work.  The trick was to 'chmod o+r pubring.pkr' so that the apache server could read the public keys!!!  Then, this function worked fine:

<?PHP
function pgp_encrypt($keyring_location, $public_key_id, $plain_text) {

      
$key_id = EscapeShellArg($public_key_id);
      
putenv("PGPPATH=$keyring_location");

      
// encrypt the message
      
$pipe = popen("pgpe -r $key_id -af", "r");             
      
fwrite($pipe, $plain_text);
      
$encrypted_text = '';
       while(
$s = fgets($pipe, 1024)) {
              
// read from the pipe
              
$encrypted_text .= $s;
       }
      
pclose($pipe);

       return
$encrypted_text;
}

$message = pgp_encrypt("/home/username/.pgp", "to@domain.com", "dummy text to be encrypted");
print
nl2br($message);

?>


nricciardi at mindspring dot com
09-Mar-2002 01:38

ive tried using popen using bidirectional pipes without working for obvious reasons, but i managed to create a simple script that managed to take care of the problem.  This example is for gpg encryption.

<?
   $message
= "this is the text to encrypt with gpg";
  
$sendto = 'Dummy Key <another@fake.email>';

  
system("mkfifo pipein");
  
system("mkfifo pipeout");
  
system("gpg --encrypt -a -r '$sendto' > pipeout < pipein &");
  
$fo = fopen("pipeout", "r");
  
$fi = fopen("pipein", "w");
  
fwrite($fi, $message, strlen($message));
  
fclose($fi);
   while (!
feof($fo)) {
    
$buf .= fread($fo, 1024);
   }
   echo
$buf;
  
unlink("pipein");
  
unlink("pipeout");
?>

If anyone has a better way of doing this I would love to see it.


kevin at pricetrak dot com
29-Jun-2001 08:26

Just a quick note about your environment. None of the apache specific environment variables are available to the called program.


trevor at verite dot com
16-Feb-2001 09:42

Just make sure that you check the user information being passed into the command (if any) before it executes.


bevmo at gmx dot de
01-Dec-2000 07:27

Try this if you want to use sendmail...
$mailer = popen ("/usr/sbin/sendmail -t -i","w");
fwrite ($mailer,"Subject:
From:
To:

*insert text*
");
pclose ($mailer);


stevet at linuxfan dot com
14-Nov-2000 04:17

In PHP3, I could do:

$query = "echo hello world | mycmd"
$fp = ($query, "r");

Under PHP4, this just produces "hello world | mycmd" as the output - the pipe is not executed.

Instead, use:

$query = "hello world";
$cmd = "mycmd";
$fp = popen($cmd, "w+");
fwrite($fp, $query);


lexzeus at mifinca dot com
08-Nov-2000 06:53

Try this (if you're familiar with vi editor) :

<?php
$f
=popen("vi newfile.txt","w");
sleep(1);
fputs($f,"i");  // insert

sleep(1);
fputs($f,"Hello world\r"); // write the text to vi Editor

sleep(1);
fputs($f,chr(27));  // cancel action

sleep(1);
fputs($f,":wq\r");  // write and quit

pclose($f); // back to php

exit;
?>

heh heh heh,

LexZEUS


matthew at leftcoast dot com
04-Oct-2000 03:16

Note that your OS must support bi-direction pipes for popen to be bi-directional. 

FreeBSD and BSDI are known to support bi-pipes. 

Not sure about Linux.


 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt