Reputation: 1814
I'm a new one using PHP. I want to use awk in PHP.
I have a file which is named a
. The content is:
www.b.com * record=600,IN,A,1.2.3.4record=600,IN,A,5.6.7.8
www.1.com u record=600,IN,A,1.2.3.4
www.1.com w record=600,IN,A,1.2.3.4
Now I use PHP to handle it.
<?php
$dn = "www.1.com";
$hello = shell_exec("awk '{ if ( $1==".$dn.")print $1}' a") ;
echo $hello;
?>
It doesn't work — can you tell me why? If I use this other way, it does work.
$hello = shell_exec("awk '{ if ( $1==\"www.b.com\")print $1}' a") ;
Upvotes: 2
Views: 2243
Reputation: 270677
awk
sees $dn
as a string literal, so you need to quote the string inside awk
, which is what you did in your test example:
$dn = "www.1.com";
$hello = shell_exec("awk '{ if ( $1==\"".$dn."\")print $1}' a") ;
// ---------------------------------^^^-------^^^
// Surround in escaped double quotes...
echo $hello;
If the string $dn
is to be sourced from any kind of user or browser input, be sure to properly escape it with escapeshellarg()
or escapeshellcmd()
first. Since escapeshellarg()
adds single quotes, that probably isn't useful here, but escapeshellcmd()
which is normally used to escape the entire command, could at least escape any internal quotes or other bad characters that might come in $dn
.
Upvotes: 6