I am learning PHP. I see a code including "eval" below:
<?php
$name = 'cup';
$string = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$cup = \"$str\";");
echo $cup. "\n";
?>
My question is about "\$cup = \"$str\";" . Why do I have to use \, " and ; to run the above code? Simply eval($cup = $str) gives me error.
Simply eval($cup = $str) is wrog, eval need a string, eg;
eval('$cup = $str;'); // this work
now, if use double quote, eg
eval("\$cup = \"$str\";");
in double quote strings variables in the strings will be evaluated. eg:
$cup = 'hello';
$str = 'world';
eval("$cup = \"$str\";"); // eval("hello = \"world\";");
\is a escape characters
$cup = 'hello';
$str = 'world';
eval("\$cup = \"$str\";"); // eval("$cup = \"world\";");
recommended reading: PHP Strings
Side note: PHP eval is evil (use very, very careful)
Related
I am writing a file that is plan.php. It is a php file that I am writing. I am using \n to put the new line in that file but it is giving me save output.
Here is code:
$datetime = 'Monthly';
$expiry = '2017-08-07';
$expiryin = str_replace('ly', '',$datetime);
if($expiryin == 'Month' || $expiryin == 'Year') {
$time = '+ 1'.$expiryin.'s';
} else {
$time = '+'.$expiryin.'s';
}
$expiry_date = date('Y-m-d', strtotime($time, strtotime($expiry)));
$string = createConfigString($expiry_date);
$file = 'plan.php';
$handle = fopen($file, 'w') or die('Cannot open file: '.$file);
fwrite($handle, $string);
And the function is:
function createConfigString($dates){
global $globalval;
$str = '<?php \n\n';
$configarray = array('cust_code','Auto_Renew','admin_name');
foreach($configarray as $val){
$str .= '$data["'.$val.'"] = "'.$globalval[$val].'"; \n';
}
$str .= '\n';
return $str;
}
But it is giving the output like:
<?php .......something....\n.....\n
So my question is how to put the new line in this file.
Note: There is no error in code. I have minimized the code to put here.
As everyone already mentioned '\n' is just a two symbols string \n.
You either need a "\n" or php core constant PHP_EOL:
function createConfigString($dates){
global $globalval;
// change here
$str = '<?php ' . PHP_EOL . PHP_EOL;
$configarray = array('cust_code','Auto_Renew','admin_name');
foreach($configarray as $val){
// change here
$str .= '$data["'.$val.'"] = "'.$globalval[$val].'";' . PHP_EOL;
}
// change here
$str .= PHP_EOL;
return $str;
}
More info about interpreting special characters in strings http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
Replace ' with " ;-)
You can learn more about strings in PHP's manual: http://docs.php.net/manual/en/language.types.string.php
If you use \n inside a single-quoted string ($var = '\n';), it will be just that - the litteral string \n, and not a newline. For PHP to interpret that it should in fact be a newline, you need to use doublequotes ($var = "\n";).
$var = '\n'; // The litteral string \n
$var = "\n"; // Newline
PHP.net on double quoted strings
Live demo
\n does not work inside single quotes such as '\n'. You need to use double quotes "\n". So for your purpose, the change you need to make is:
function createConfigString($dates){
global $globalval;
$str = '<?php \n\n';
$configarray = array('cust_code','Auto_Renew','admin_name');
foreach($configarray as $val){
$str .= "$data['".$val."'] = '".$globalval[$val]."'; \n"; // change places of double and single quotes
}
$str .= "\n"; // change places of double and single quotes
return $str;
}
I have a webpage which includes a hyperlink as follows:
$name = "Hello World";
echo "<a href='page.php?name='". preg_replace(" ", "_", $name) "'> bla bla </a>"
This generates the following link successfully:
...page.php?name=Hello_World
in my page.php I try to reverse the operation:
if($_SERVER[REQUEST_METHOD] == "GET"){
$name = $_GET['name'];
//testing if the problem is with GET
echo $name;
//now here's the problem:
$string = preg_replace("_", " ", $name);
echo $string;
}
the $name echoes correctly but the $string is always null
I've tried all possible combinations like ~~ and // and [_] and \s and using $_GET directly like:
preg_replace("_", " ", $_GET['name']);
none of them worked.
This problem has burned most of my day.
Any help is appreciated.
preg_replace accepts a regular expression as it's first arguments. Neither " " nor "_" are valid regular expressions.
In this case you can use str_replace.
The preg_replace syntax is incorrect as pointed by #Halcyon, the following is correct:
$string = preg_replace('/_/', ' ', $name);
But for such a simple find/replace you can use str_replace instead:
$string = str_replace("_", " ", $name);
echo $string;
you can create a function like sefurl
function makesefurl($url=''){
$s=trim($url);
$tr = array('ş','Ş','ı','I','İ','ğ','Ğ','ü','Ü','ö','Ö','Ç','ç','(',')','/',':',',');
$eng = array('s','s','i','i','i','g','g','u','u','o','o','c','c','','','-','-','');
$s = str_replace($tr,$eng,$s);
$s = preg_replace('/&amp;amp;amp;amp;amp;amp;amp;.+?;/', '', $s);
$s = preg_replace('/\s+/', '-', $s);
$s = preg_replace('|-+|', '-', $s);
$s = preg_replace('/#/', '', $s);
$s = str_replace('.', '.', $s);
$s = trim($s, '-');
$s = htmlspecialchars(strip_tags(urldecode(addslashes(stripslashes(stripslashes(trim(htmlspecialchars_decode($s))))))));
}
echo "<a href='page.php?name='". makesefurl($name) "'> bla bla </a>";
and than you can convert it to before makesefurl function all you need to create another functin like decoder or encoder html command
I have a file that i'm parsing And I'm trying to replace $mail["email_from"] = "test#example.com"; with $mail["email_from"] = request("email");,(meaning that I want to replace all the lines that has $mail["email_from"] at the begining an ; at the end) and here's my preg_replace:
$email = "$mail[\"email_from\"] = request(\"email\")";
$newcontent = preg_replace("/\$mail[\"email_from\"](.+);/",$email,$content);
What's the error in my code? and how to fix it? Much appreciated
DEMO
After using good quotes and escaping all chars you need, this works:
$email = '$mail["email_from"] = "test#example.com";';
$replacement = '$mail["email_from"] = request("email");';
$newContent = preg_replace('/\\$mail\\[\\"email_from\\"\\](.+);/i', $replacement, $email);
echo $newContent; //$mail["email_from"] = request("email");
$email = "$mail[\"email_from\"] = request(\"email\")";
^---double-quoted string
^^^^^---array reference
You probably need
$email = "\$mail[\"email_from\"] = request(\"email\")";
^--escape the $
Use ^ and $ to specify beginning and end of line. Special characters like $, [, and ] need to be escaped.
<?php
$content = '$mail["email_from"] = "test#example.com";';
$email = '$mail["email_from"] = request("email");';
$newcontent = preg_replace('/^\$mail\["email_from"\] =.+;$/',$email,$content);
echo $newcontent . "\n";
outputs:
$mail["email_from"] = request("email");
It would be nice if I could call my_escape($text, '<p><b><i>') that escapes everything except all <p>, <b> and <i> tags. I'm looking for a generic solution where I can specify an arbitrary set of tags. Does this exist? If not what's the best approach to implement it?
in htmlspecialchars function it converts html tags to
& to &
" to "
' to '
< to <
> to >
after convert you can do reverse to decode
<?php
$test="<p><b><a>Test</b></a></p>";
$test = htmlspecialchars($test);
$test = str_replace("<p>", "<p>", $test);
$test = str_replace("<i>", "<i>", $test);
$test = str_replace("<b>", "<b>", $test);
$test = str_replace("</b>", "</b>", $test);
$test = str_replace("</i>", "</i>", $test);
$test = str_replace("</p>", "</p>", $test);
echo $test;
?>
Your best bet is to do something like this
// Add placeholders
$search = array('<p>', '<b>');
$replace = array("\ap\a", "\ab\a");
$text = str_replace($search, $replace, $text);
$text = htmlspecialchars($text);
// Put it all back together
$text = str_replace($replace, $search, $text);
It would be best to use a regular expression, but that is a lot more explaining.
I wish to have one string that contains for instance (mystring):
file config.php
$mystring = "hello my name is $name and i got to $school";
file index.php
include('config.php');
$name = $_GET['name'];
$school = $_GET['school'];
echo $mystring;
Would this work ? or are there any better ways
$string = 'Hello, my name is %s and I go to %s';
printf($string, $_GET['name'], $_GET['school']);
or
$string = 'Hello, my name is :name and I go to :school';
echo str_replace(array(':name', ':school'), array($_GET['name'], $_GET['school']), $string);
You can automate that last one with something like:
function value_replace($values, $string) {
return str_replace(array_map(function ($v) { return ":$v"; }, array_keys($values)), $values, $string);
}
$string = 'Hello, my name is :name and I go to :school';
echo values_replace($_GET, $string);
No it won't work.
You have to define $name first before using it in another variable
config.php should look like
<?php
$name = htmlspecialchars($_GET['name']);
$school = htmlspecialchars($_GET['school']);
$mystring = "hello my name is $name and i got to $school";
and index.php like
<?php
include('config.php');
echo $mystring;
Why didn't you try it?
demo:
http://sandbox.phpcode.eu/g/2d9e0.php?name=martin&school=fr.kupky
Alternatively, you can use sprintf like this:
$mystring = "hello my name is %s and i got to %s";
// ...
printf($mystring, $name, $school);
This works because your $mystring literal is using double quotes, if you'd used single quotes then it would not work.
http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing