Ordinarily, one would expect that the unexpected T_STRING implies a missing semicolon. However, in this case, where's the semicolon missing from??
global $lay;
$yal = eval("return '$lay';");
echo $yal . "\n";
The error is thrown in the eval, viz
Parse error: syntax error, unexpected T_STRING in ... BOGARIP.php(140) : eval()'d code on line 1
with $lay containing
$reportDate\t$heads['Account']\t$id\t$heads['Time zone']\t$heads['Campaign']\t$heads['Ad group']\t$heads['Network']\t$heads['Network (with search partners)']\t\t$heads['Ad group state']\t$heads['Campaign state']\t$heads['Impressions']\t$heads['Clicks']\t$heads['CTR']\t$heads['Avg. CPC']\t$heads['Avg. CPM']\t$heads['Cost']\t$heads['Avg. position']
Does this imply that the bug is actually in $lay or am I missing something else? Is this level of string substitution even possible?
You really shouldn't be doing anything with eval, generally speaking. But, for the sake of the technical issue here, consider the following:
eval("return '$lay';");
You're surrounding the $lay variable with single quotes. Now let's look at the contents of this variable:
$reportDate\t$heads['Account...
See the problem? You're using single quotes within the value too. Swap out the quotes in your eval statement so there is no longer a conflict:
eval('return "$lay";');
Again again, please don't use this code. By and large, professionals will steer you away from every using eval, as it opens up your application to a great deal of potential woes. Please find another way to do whatever it is you're attempting.
Took #Evert's advice and refactored. Now the format contains
%DATE%\t%Account%\t%ID%\t%Time zone%\t%Campaign%\t%Ad group%\t%Network%\t%Network (with search partners)%\t\t%Ad group state%\t%Campaign state%\t%Impressions%\t%Clicks%\t%CTR%\t%Avg. CPC%\t%Avg. CPM%\t%Cost%\t%Avg. position%
and the code
$heads["ID"] = $id;
$heads["DATE"] = $reportDate;
...
global $lay;
$layout = $lay;
foreach ($heads as $key => $value) {
$layout = str_replace("%" . $key . "%", $value, $layout);
}
$layout = str_replace("\\n", "\n", $layout);
$layout = str_replace("\\t", "\t", $layout);
Related
I have website where users can search posts by entering keywords,
I am using Sphinx search for full text search, everyhting is working as expected.
But when i enter/input some special charaters in search query the search dosnt complete and throws error.
e.g.
keyword i search for :
hello)
my query for sphinxql :
SELECT id FROM index1 WHERE MATCH('hello)')
error i get :
index index1: syntax error, unexpected ')' near ')'
my php code looks like this
<?php
$sphinxql = mysqli_connect($sphinxql_host.':'.$sphinxql_port,'','') or die('ERROR');
$q = urldecode($_GET['q']);
$sphinxql_query = "SELECT id FROM $sphinx_index WHERE MATCH('".$q."') ";
?>
How can i escape user input and make sure the query wont brake and return the result set ?
You should use SQL escaping, to avoid SQL injection.
http://php.net/manual/en/mysqli.real-escape-string.php
$sphinxql_query = ".... MATCH('".mysqli_real_escape_string($sphinxql,$q)."') ";
... BUT you may want to ALSO, escape extended syntax.
See the FIRST THREE POSTS (after that it delves into misunderstanding) in this thread in the sphinx forum
http://sphinxsearch.com/forum/view.html?id=13619
For a simple solution.
The function in that thread, can be used to make your query work. It will escape the ) and stop it being taken as a operator.
BUT, it also means you WONT be able to use any search operators - because it blindly escapes them ALL. (which is the confusion later in the thread)
If you want to be able to use some or all operators, need to use more advanced escaping. (which I dont have a good solution for)
Edit: actully lets go the whole hog...
<?php
//Escapes all the Extended syntax, so can accept anything the user throws at us.
function EscapeString ( $string ) {
$from = array ( '\\', '(',')','|','-','!','#','~','"','&', '/', '^', '$', '=' );
$to = array ( '\\\\', '\(','\)','\|','\-','\!','\#','\~','\"', '\&', '\/', '\^', '\$', '\=' );
return str_replace ( $from, $to, $string );
}
if ($allow_full_extended_syntax) {
$q = $_GET['q'];
// the user is responsible for providing valid query.
} elseif ($allow_partical_extended_syntax) {
$q = InteligentEscape($_GET['q']);
//I don't have this function, it would need to be created.
} else {
$q = EscapeString($_GET['q']);
// escapes ALL extended syntax. NO operators allowed
}
$sphinxql_query = ".... MATCH('".mysqli_real_escape_string($sphinxql,$q)."') ";
Then it sounds like you want both $allow_full_extended_syntax and $allow_partical_extended_syntax set to false. Which means no operators will work, because they will be fully escaped.
The EscapeString function needs to escape the < character as well. Also see escapeString function in PECL shpinx for reference.
What is the best way to go about defining a php function and the call to that function, in a string, and then executing that code i.e., eval? I'm trying to get the length of an encoded uri out of a function defined and called in a string.
$json_arr['my_function'] = "function hashfun1($enc_uri) { return strlen($enc_uri); } hashfun1($enc_uri);";
$hash_func = $json_arr['my_function'];
$hash_val = eval($hash_func);
print_r($hash_val); // should be length of encoded uri but displays "Parse error: syntax error, unexpected '%', expecting '&' or T_VARIABLE"
exit;
Thanks.
I guess you want:
$json_arr['my_function'] = "function hashfun1($enc_uri) { return strlen($enc_uri); } hashfun1('" . $enc_uri . '");";
You missed to populate $enc_uri.
Don't do this in production code, although it works. eval() is evil. You have been warned.
you need to escape "$" in double-quoted string. And check number of returns (second for eval):
$json_arr['my_function'] = "function hashfun1(\$enc_uri) { return strlen(\$enc_uri); } return hashfun1(\$enc_uri);";
I guess I need to use call_user_func(); This worked for me: $json_arr['my_function'] = function($enc_uri) { return strlen($enc_uri); };
$hash_val = call_user_func($json_arr['my_function'], $enc_uri);
print_r($hash_val);
exit;
Thanks for the help guys.
PHP
<?php
$truck['Toyota']=Tundra;
$truck['Nissan']=Titan;
$truck['Dodge']=Ram;
print "<br />Toyota makes the".$truck['Toyota']."<br />";
print "Nissan makes the".$truck['Nissan']."<br />";
print "Dodge makes the".$truck['Dodge']."<br />";
?>
I am learning PHP by tutorial:
An Associative Array is an array in which the keys are associated with values.
And, when viewed in a browser...
Toyota makes the Tundra
Nissan makes the Titan
Dodge makes the Ram
NOT SO!
I get:
Toyota makes theR
Nissan makes theR
Dodge makes theR
Can anyone explain?
OK so everyone has pointed out that you need to quote your strings, but that's not the real problem.
(The reason that your code is not throwing an error right now is because the strings you forgot to quote are treated as PHP "bare strings" -- basically an undefined constant whose name is used as the value, you should not use/rely on this.)
Now for the real problem: it looks like you have already defined $truck to be a string further up in your code, so when you try to read/write to it as if it were an associative array, you are really read/writing the first character in that originally defined string (the string key your are using is converted to an int). Since the last assignment is $truck['Dodge'] = "Ram", the first character in $truck is changed to an "R", and that's what you are then seeing in your output.
You should (and this case need to) define $truck as an array before you start using it like one:
$truck = array();
$truck['Toyota'] = "Tundra";
$truck['Nissan'] = "Titan";
$truck['Dodge'] = "Ram";
Even better, for best practices, you should use a different variable name for the first $truck (string) and the second $truck (array) so it's not confusing:
// some code that I imagine comes before your example
$truck = "Ford F150";
// ...
$trucks = array();
$trucks['Toyota'] = "Tundra";
$trucks['Nissan'] = "Titan";
$trucks['Dodge'] = "Ram";
print "<br />Toyota makes the".$trucks['Toyota']."<br />";
print "Nissan makes the".$trucks['Nissan']."<br />";
print "Dodge makes the".$trucks['Dodge']."<br />";
You need quotes around string literals. E.g.:
<?php
$truck['Toyota'] = "Tundra";
$truck['Nissan'] = "Titan";
$truck['Dodge'] = "Ram";
A good idea is to enable error reporting, so you will be told about these issues by the php interpreter. Stick this line at the top of your script (next after <?php):
error_reporting(E_ALL);
It looks like you're using constants Tundra Titan and Ram instead of strings. Have you defined those constants elsewhere in your code?
$truck['Toyota']="Tundra";
$truck['Nissan']="Titan";
$truck['Dodge']="Ram";
I think its a syntax error.
you have to put your strings inside quotation marks:
$truck['Toyota']='Tundra';
$truck['Nissan']='Titan';
$truck['Dodge']='Ram';
I don't know if the post has been edited by Stack Overflow or it lost them but your values are not wrapped in single quotations..
Also, just a piece of advice; concatenation is only required on single quote strings you can wrap your variables in braces to save that 0.00001 msec :)
Enable error reporting and reduce the code to more quickly fix if you've found the error:
<?php
# display errors and show all warnings and errors, that's helpful:
ini_set('display_errors', 1); error_reporting(~0);
$truck['Toyota']=Tundra;
$truck['Nissan']=Titan;
$truck['Dodge']=Ram;
echo "<br />\n";
# when doing the same thing multiple times, take foreach:
foreach ($truck as $manufacturer => $model)
{
echo $manufacturer, ' makes the ', $model, ".<br />\n";
}
This is a follow-up question to the one I posted here (thanks to mario)
Ok, so I have a preg_replace statement to replace a url string with sometext, insert a value from a query string (using $_GET["size"]) and insert a value from a associative array (using $fruitArray["$1"] back reference.)
Input url string would be:
http://mysite.com/script.php?fruit=apple
Output string should be:
http://mysite.com/small/sometext/green/
The PHP I have is as follows:
$result = preg_replace('|http://www.mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
This codes outputs the following string:
http://mysite.com/small/sometext//
The code seems to skip the value in $fruitArray["$1"].
What am I missing?
Thanks!
Well, weird thing.
Your code work's perfectly fine for me (see below code that I used for testing locally).
I did however fix 2 things with your regex:
Don't use | as a delimiter, it has meaning in regex.
Your regular expression is only giving the illusion that it works as you're not escaping the .s. It would actually match http://www#mysite%com/script*php?fruit=apple too.
Test script:
$fruitArray = array('apple' => 'green');
$_GET = array('size' => 'small');
$result = 'http://www.mysite.com/script.php?fruit=apple';
$result = preg_replace('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
echo $result;
Output:
Rudis-Mac-Pro:~ rudi$ php tmp.php
http://www.mysite.com/small/sometext/green/
The only thing this leads me to think is that $fruitArray is not setup correctly for you.
By the way, I think this may be more appropriate, as it will give you more flexibility in the future, better syntax highlighting and make more sense than using the e modifier for the evil() function to be internally called by PHP ;-) It's also a lot cleaner to read, IMO.
$result = preg_replace_callback('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#', function($matches) {
global $fruitArray;
return 'http://www.mysite.com/' . $_GET['size'] . '/sometext/' . $fruitArray[$matches[1]] . '/';
}, $result);
i write it again, i don't understand good where is the error, the evaluation of preg results is very weird in php
preg_replace(
'|http\://([\w\.-]+?)/script\.php\?fruit=([\w_-]+)|e'
, '"http://www.$1/".$_GET["size"]."/sometext/".$fruitArray["$2"]."/";'
, $result
);
It looks like you have forgotten to escape the ?. It should be /script.php\?, with a \? to escape properly, as in the linked answer you provided.
$fruitArray["\$1"] instead of $fruitArray["$1"]
Beginner question.
How do I substitute:
$_SESSION['personID'] for {personID} in the following:
public static $people_address = "/v1/People/{personID}/Addresses"
look this:
$template = "/v1/People/{personID}/Addresses";
$people_address = str_replace('{personID}', $_SESSION['personID'], $template);
echo $people_address;
output:
/v1/People/someID/Addresses
EDIT: This answer no longer applies to the question after edit but I'm leaving it around for a little while to explain some questions that occured in comments another answer to this question
There are a few ways - the . operator is probably the easiest to understand, its entire purpose is to concatenate strings.
public static $people_address = "/v1/People/".$_SESSION['personID']."/Addresses";
//PHP Parse error: syntax error, unexpected '.', expecting ',' or ';'
public static $people_address = "/v1/People/$_SESSION[personID]/Addresses";
//PHP Parse error: syntax error, unexpected '"' in
However you can't use concatenation in property declarations sadly - just simple assignment. You cant use the "string replacement" format either:
To work around it you could assign the static outside of the class - i.e.:
class test {
public static $people_address;
// ....
}
// to illustrate how to work around the parse errors - and show the curly braces format
test::$people_address = "/v1/People/${_SESSION[personID]}/Addresses";
// another (much better) option:
class test2 {
public static $people_address;
public static function setup() {
self::$people_address = "/v1/People/".$_SESSION['personID']."/Addresses";
}
}
// somewhere later:
test2::setup();