Tải bản đầy đủ - 0 (trang)
Chapter 12. Working with the Server Environment

Chapter 12. Working with the Server Environment

Tải bản đầy đủ - 0trang

OpeningPipestoandfromProcessesUsing

popen()

InChapter11,"WorkingwithFilesandDirectories,"youlearned

howtoopenafileforreadingandwriting,usingthefopen()

function.Now,you'llseethatyoucanopenapipetoaprocess

usingthepopen()function.

Thepopen()functionisusedlikethis:



$file_pointer=popen("somecommand",mode)

Themodeiseitherr(read)orw(write).

Listing12.1isdesignedtoproduceanerroritwillattemptto

openafileforreading,whichdoesnotexist.



Listing12.1Usingpopen()toReadaFile



1:
2:$file_handle=popen("/path/to/fakefile2>&1","r");

3:$read=fread($file_handle,2096);

4:echo$read;

5:pclose($file_handle);



6:?>

Line2utilizesthepopen()function,attemptingtoopenafile

forreading.Inline3,anyerrormessagestoredinthe

$file_handlepointerisread,andprintedtothescreeninline

4.Finally,line5closesthefilepointeropenedinline2.

Ifyousavethiscodeaslisting12.1.php,placeitinyour

documentrootandaccessitwithyourWebbrowser,youwill

seethefollowingerrormessagedisplayedonyourscreen:



sh:/path/to/fakefile:Nosuchfileordirectory



Listing12.2Usingpopen()toReadtheOutputof

theUnixwhoCommand



1:
2:$handle=popen("who","r");

3:while(!feof($handle)){

4:$line=fgets($handle,1024);

5:if(strlen($line)>=1){

6:echo"$line
";



7:}

8:}

9:pclose($handle);

10:?>

Inline2,afilepointerisreturnedwhenweusepopen()for

reading.Line3beginsawhileloopwhichwillreadeachlineof

outputfromtheprocessandeventuallyprintthelineifit

containsinformationinline6.Theconnectionisclosedinline9.

Ifyousavethiscodeaslisting12.1.php,placeitinyour

documentroot,andaccessitwithyourWebbrowser,youmay

seesomethinglikethefollowing(withyouractualinformation,

notmine,ofcourse):



juliepts/0Sep3021:06(adsl-67-125-85-212.dsl.snfc21.pacbell

Listing12.3showshowtousepopen()inwritemode,topass

datatoanexternalapplication,inthiscasecolumn.Thegoalof

thescriptistotaketheelementsofamultidimensionalarray

andoutputthemintableformat,inanASCIIfile.



Listing12.3Usingpopen()toPassDatatotheUnix

columnCommand



1:
2:$products=array(

3:array("HAL2000",2,"red"),

4:array("Tricorder",3,"blue"),

5:array("ORACAI",1,"pink"),

6:array("SonicScrewdriver",1,"orange")

7:);

8:



9:$handle=popen("column-tc3-s/>/somepath/purchases.tx

10:foreach($productsas$p){

11:fputs($handle,join('/',$p)."\n");

12:}

13:pclose($handle);

14:echo"done";

15:?>

Inlines27,amultidimensionalarraycalled$productsis

defined.Inline9,popen()isusedinwriteformattosenda

commandtothecolumnapplication.Thecommandsends

parameterstothecolumnapplication,tellingittoformatthe

inputasathree-columntable,using/asafielddelimiter.The



outputwillbesenttoafilecalledpurchases.txt.Lines1012

useforeachtoloopthroughthe$productsarrayandsend

eachelementtotheopenfilepointer.Thejoin()functionis

usedtoconvertthearraystoastring,withthedelimiter

appendedtoit.Line13closestheopenfilepointer,andline14

printsastatustothescreen.

Ifyousavethiscodeaslisting12.3.php,placeitinyour

documentroot,andaccessitwithyourWebbrowser,itshould

createafileinthespecifiedlocation.Lookingatthefilecreated

onmymachine,Iseethefollowing:



HAL20002red

Tricorder3blue

ORACAI1pink

SonicScrewdriver1orange



RunningCommandswithexec()

Theexec()functionisoneofseveralfunctionsyoucanuseto

passcommandstotheshell.Theexec()functionrequiresa

stringrepresentingthepathtothecommandyouwanttorun,

andoptionallyacceptsanarrayvariablewhichwillcontainthe

outputofthecommand,andascalarvariablewhichwillcontain

thereturnvalue(1or0).Forexample:



exec("/path/to/somecommand",$output_array,$return_val);

Listing12.4usestheexec()functiontoproduceadirectory

listingwiththeshell-basedlscommand.



Listing12.4Usingexec()andlstoProducea

DirectoryListing



1:
2:exec("ls-al.",$output_array,$return_val);

3:echo"Returned$return_val
";

4:foreach($output_arrayas$o){

5:echo"$o
";



6:}

7:?>

Inline2,theexec()functionissuesthelscommand,withthe

outputofthecommandplacedinthe$output_arrayarrayand

thereturnvalueplacedinthe$return_valvariable.Line3

simplyprintsthereturnvalue,whiletheforeachloopinlines

46printsouteachelementin$output_array.

Ifyousavethiscodeaslisting12.4.php,placeitinyour

documentroot,andaccessitwithyourWebbrowser,youmay

seesomethinglikeFigure12.1(withyouractualinformation,

notmine,ofcourse).



Figure12.1.Outputofascriptthatusesexec()to

listdirectorycontents.



Inthepreviouschapter,youlearnedtouseopendir()and



readdir()todisplayadirectorylisting,butthiswasasimple

exampleofusingexec()toperformataskusingsystemtools.

Therewillbetimeswhenrunningacommandonyoursystem

willachieveaneffectthatmaytakeagreatdealofcodeto

reproduceinPHP.Forexample,youmayhavealreadycreateda

shellscriptorPerlscriptthatperformsacomplextaskinashort

periodoftime;ratherthanreinventthewheelusingPHP,you

cansimplyuseexec()toaccesstheexistingscript.However,

rememberthatcallinganexternalprocesswillalwaysaddsome

amountofadditionaloverheadtoyourscript,intermsofboth

timeandmemoryusage.



RunningCommandswithsystem()orpassthru()

Thesystem()functionissimilartotheexec()functioninthat

itlaunchesanexternalapplication,anditutilizesascalar

variableforstoringareturnvalue:



system("/path/to/somecommand",$return_val);

Thesystem()functiondiffersfromexec()inthatitoutputs

informationdirectlytothebrowser,withoutprogrammatic

intervention.Thefollowingsnippetofcodeusessystem()to

printamanpageforthemancommand,formattedwiththe

tagpair:




echo"
";

system("manman|colb",$return_val);

echo"
";

?>



Similarly,thepassthru()functionfollowsthesyntaxofthe

system()function,butitbehavesdifferently.Whenusing

passthru(),anyoutputfromtheshellcommandisnotbuffered

onitswaybacktoyou;thisissuitableforrunningcommands

theproducebinarydatainsteadofsimpletextdata.An

exampleofthiswouldbetouseshelltoolstolocateanimage

andsenditbacktothebrowser,asseeninListing12.5.



Listing12.5Usingpassthru()toOutputBinary

Data



1:


2:if((isset($_GET[imagename]))&&(file_exists($_GET[imagenam

3:header("Content-type:image/gif");



4:passthru("giftopnm$_GET[imagename]|pnmscale-xscale.5

ppmtogif");

5:}else{

6:echo"Theimage$_GET[imagename]couldnotbefound";

7:}

8:?>



Theshellutilitiesusedinthisscript,giftopnm,pnmscaleand

ppmtogifmayormaynotbeinstalledonyoursystem.Iftheyare

not,don'tworryaboutit;justusethislistingtounderstandthe

conceptofusingthepassthru()function.



ThisscriptwouldbecalledfromHTMLlikethefollowing:




Inline2ofListing12.5,theuserinputistestedtoensurethat

thefileinquestion(test.gif,accordingtotheHTMLsnippet)

exists.BecausethescriptwillbeoutputtingGIFdatatothe

browser,theappropriateheaderissetonline3.Online4,the

passthru()functionconsecutivelyexecutesthreedifferent

commandsgiftopnm,pnmscale,andppmtogif,whichscalesthe

imageto50%ofitsoriginalheightandwidth.Theoutputofthe

passthru()commandthatis,thenewimagedataissenttothe

browser.

Inthisandothersystem-relatedexamples,youcouldhaveused

theescapeshellcmd()orescapeshellarg()functiontoescape

elementsintheuserinput.Doingsoensuresthattheusercannot

trickthesystemintoexecutingarbitrarycommandssuchas

deletingimportantsystemfilesorresettingpasswords.These

functionsgoaroundthefirstinstanceoftheuserinput,suchas



$new_input=escapeshellcmd($_GET[someinput]);

Youwouldthenreference$new_inputthroughouttheremainder

ofyourscript,insteadof$_GET[someinput].Usingthesetwo

commands,plusensuringthatyourscriptiswrittensoastoonly

performtasksyouwantittodo,andnotyourusers,isawayto

keepyoursystemsecure.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 12. Working with the Server Environment

Tải bản đầy đủ ngay(0 tr)

×