Unit4 PHP
Unit4 PHP
Unit4 PHP
PHP and Python are two of the most popular and influential programming languages. They both
have their strengths and weaknesses and share many standard software development
capabilities. Although Rasmus Lerdorf developed PHP as a web language, and Guido van
Rossum created Python as a general-purpose programming language. Assessing each language
and comparing their strengths across several core elements can help you make the correct
choice.
Development Environment (PHP < Python)
Language Complexity (PHP > Python)
Extendibility (PHP > Python)
Security (PHP > Python)
Scalability and Adaptability (=)
Documentation and Community Support(=)
EXECUTING PYTHON SCRIPT USING PHP:
To run a Python script from PHP, we can use the shell_exec function.
Step :1 create python file “x.py” in “www\wamp”
Print(“hello”)
Step:2 create php file for calling(execute) python script.
<?PHP
$command_exec = escapeshellcmd('python x.py');
$str_output = shell_exec($command_exec);
echo $str_output;
?>
To call escapeshellcmd to escape the command string.Then we call shell_exec to run
the $command.
And we get the output from $output
ESCAPESHELLCMD() METHOD:
escapeshellcmd() escapes any characters in a string that might be used to trick a shell
command into executing arbitrary commands. This function should be used to make sure that
any data coming from user input is escaped before this data is passed to
the exec() or system() functions, or to the backtick operator.
The command line is a dangerous place for unescaped characters. Never pass unmodified user
input to one of PHP's shell-execution functions. Always escape the appropriate characters in the
command and the arguments. Following characters are preceded by a
backslash: &#;`|*?~<>^()[]{}$\, \x0A and \xFF. ' and " are escaped only if they are not paired.
On Windows, all these characters plus % and ! are preceded by a caret (^).
Syntax:
escapeshellcmd ( string $command )
Example:
<?php
$command = "\\%!** Hello World";
$escaped_command = escapeshellcmd($command);
echo ($escaped_command);
?>
Output
!Hello World
SHELL_EXEC() METHOD :
used to execute the commands via shell and return the complete output as a string. The
shell_exec is an alias for the backtick operator
syntax:
shell_exec( $cmd )
example: display list of file and directory
$output = shell_exec(‘dir');
echo "$output";
EXEC() METHOD:
The exec()is used to execute an external program and returns the last line of the output. It
also returns NULL if no command run properly.
Syntax:
exec( $command, $output)
example: display last line of output
exec("dir",$output1);
echo $output1;
SYSTEM() :
it is for executing a system command and immediately displaying the output - presumably text.
Example:
system("dir",$output1);
echo $output1;
THE OS MODULE
The OS module in Python provides functions for interacting with the operating
system. OS comes under Python's standard utility modules. we will be covering the following:
• os.chdir() os.getcwd()
• os.mkdir() os.makedirs()
• os.remove() os.rename()
• os.rmdir() os.walk()
• os.path write()
• read() close()
OS.PATH.JOIN
The join method give you the ability to join one or more path components together using the
appropriate separator. For example, on Windows, the separator is the backslash, but on Linux,
the separator is the forward slash. Here’s how it works:
>>> os.path.join(' C:\wamp\www\test\pytest ', 'p1.py')
' C:\wamp\www\test\pytest \p1.py'
In this example, we joined a directory path and a file path together to get a fully qualified path.
OS.PATH.SPLIT
The split method will split a path into a tuple that contains the directory and the file.
>>> os.path.split(' C:\wamp\www\test\pytest \p1.py')
(' C:\wamp\www\test\pytest ', 'p1.py')
This example shows what happens when we path in a path with a file. Let’s see what happens if
the path doesn’t have a filename on the end:
>>> os.path.split(' C:\wamp\www\test\pytest ')
(' C:\wamp\www\test\pytest ', 'p1')
As you can see, it took the path and split it in such a way that the last sub-folder became the
second element of the tuple with the rest of the path in the first element.
For our final example, I thought you might like to see a commmon use case of the split:
>>> dirname, fname = os.path.split(' C:\wamp\www\test\pytest\p1.py')
>>> dirname
' C:\wamp\www\test\pytest '
>>> fname
'p1.py'
This shows how to do multiple assignment. When you split the path, it returns a two-element
tuple. Since we have two variables on the left, the first element of the tuple is assigned to the
first variable and the second element to the second variable.
OS.OPEN()
Python method open() opens the file file and set various flags according to flags and possibly
its mode according to mode.The default mode is 0777 (octal), and the current umask value is
first masked out.
SYNTAX:
os.open(file, flags[, mode]);
PARAMETERS
file − File name to be opened.
flags − The following constants are options for the flags. They can be combined using the
bitwise OR operator |. Some of them are not available on all platforms.
• os.O_RDONLY − open for reading only
• os.O_WRONLY − open for writing only
• os.O_RDWR − open for reading and writing
• os.O_NONBLOCK − do not block on open
• os.O_APPEND − append on each write
• os.O_CREAT − create file if it does not exist
• os.O_TRUNC − truncate size to 0
• os.O_EXCL − error if create and file exists
• os.O_SHLOCK − atomically obtain a shared lock
• os.O_EXLOCK − atomically obtain an exclusive lock
• os.O_DIRECT − eliminate or reduce cache effects
• os.O_FSYNC − synchronous writes
• os.O_NOFOLLOW − do not follow symlinks
mode − This work in similar way as it works for chmod()
OS. READ():
os.read() method in Python is used to read at most n bytes from the file associated with the
given file descriptor.
SYNTAX:
os.read(fd, n)
PARAMETER:
import os
# Open the file and get # the file descriptor associated # with it using os.open() method
fd = os.open(“data.csv”, os.O_RDONLY)
OS.WRITE()
os.write() method in Python is used to write a bytestring to the given file descriptor.
SYNTAX:
os.write(fd, str)
PARAMETER:
Example:
import os
# Open the file and get# the file descriptor associated# with it using os.open() method
fd = os.open("x.txt", os.O_RDWR|os.O_CREAT )
# String to be written
s = "I like apple"
# Convert the string to bytes
line = str.encode(s)
# Write the bytestring to the file # associated with the file # descriptor fd and get the number of
# Bytes actually written
numBytes = os.write(fd, line)
print("Number of bytes written:", numBytes)
# close the file descriptor
os.close(fd)
SUBPROCESS MODULE IN PYTHON:
Subprocess in Python is a module used to run new codes and applications by creating new
processes. It lets you start new applications right from the Python program you are currently
writing. So, if you want to run external programs from a git repository or codes from C or C++
programs, you can use subprocess in Python.
SYNTAX:
os.popen(command[, mode])
EXAMPLE
>>> program = "notepad.exe"
>>> subprocess.Popen(program)
EXAMPLE:
import subprocess
cm='dir'
p1= subprocess.Popen(cm,shell=True)
p1.wait()
if p1.returncode==0:
print("sucessful run")
else:
print(p1.stderr)
EXPLANATION:
• Import subprocess module.
• Run ‘dir’ command and wait for process completion.
• If process completed successful it’s return 0. Otherwise 1(none).
• If no error found display “successfully run” otherwise display error using stderr.
Note : that using the wait method can cause the child process to deadlock when using the
stdout/stderr=PIPE commands when the process generates enough output to block the pipe.
You can use the communicate method to alleviate this situation.
COMMUNICATE
There are several ways to communicate with the process you have invoked. to use the
subprocess module’s communicate method.
SYNTAX:
Variableofincommingprocess.communicate()
EXAMPLE:
Import subprocess
args = 'dir'
p1=
subprocess.Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,universal_n
ewlines=True)
o,e=p1.communicate()
print('out',format(o))
print('error',format(e))
if p1.returncode==0:
print("sucessful run")
else:
print(p1.stderr)
EXPLANATION:
it takes output of first process(p1) for further process using p1.communicate().
We can store value of stdout and stderr in variable ‘o’ and ‘e’, because it will pass using
stdout=subprocess.PIPE and stderr=subprocess.PIPE respectively.
Output will display using print()
In this code example, we create an args variable to hold our list of arguments. Then we redirect
standard out (stdout) to our subprocess so we can communicate with it.
The communicate method itself allows us to communicate with the process we just spawned.
We can actually pass input to the process using this method. But in this example, we just use
communicate to read from standard out. You will notice when you run this code that
communicate will wait for the process to finish and then returns a two-element tuple that
contains what was in stdout and stderr. That last line that says “None” is the result of stderr,
which means that there were no errors.
CHECK-CALL():
to run new applications or programs through Python code by creating new processes. It also
helps to obtain the input/output/error pipes as well as the exit codes of various commands.
check_call() returns as soon as /bin/sh process exits without waiting for descendant
processes (assuming shell=True as in your case). check_output() waits until all output is read.
Parameters:
args=The command to be executed.Several commands can be passed as a string by separated by
“;”.
stdin=Value of standard input stream to be passed as (os.pipe()).
stdout=Value of output obtained from standard output stream.
stderr=Value of error obtained(if any) from standard error stream.
shell=Boolean parameter.If True the commands get executed through a new shell environment.
EXAMPLE:
cm=['echo','hello']
p1=subprocess.check_call(cm,shell=True,universal_newlines=True)
print(p1)
CHECK-OUTPUT():
check_output() is used to get the output of the calling program in python. It has 5
arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the
commands that are to be passed as a string.
EXAMPLE:
Import subprocess
cm='dir'
p1=subprocess.check_output(cm,shell=True,universal_newlines=True)
print(p1)
DECODE():
This method is used to convert from one encoding scheme, in which argument string is
encoded to the desired encoding scheme. This works opposite to the encode. It accepts the
encoding of the encoding string to decode it and returns the original string.
Syntax :
decode(encoding, error)
Parameters:
encoding : Specifies the encoding on the basis of which decoding has to be performed.
error : Decides how to handle the errors if they occur, e.g ‘strict’ raises Unicode error in case
of exception and ‘ignore’ ignores the errors occurred. decode with error replace implements
the 'replace' error handling.
EXAMPLE:
a = 'This is a bit möre cömplex sentence.'
print('Original string:', a)
# Encoding in UTF-8
encoded_bytes = a.encode('utf-8', 'replace')
# Trying to decode via ASCII, which is incorrect
decoded_correct = encoded_bytes.decode('utf-8', 'replace')
print('Correctly Decoded string:', decoded_correct)
EXECUTE PHP FILE IN PYTHON
<?php
Echo “hello”;
?>
import subprocess
proc = subprocess.Popen("php c:/wamp/www/test/p1.php", shell=True,
stdout=subprocess.PIPE)
script_response = proc.stdout.read()
print(script_response)
Note if not error like ->> set environmental variable for php