Basically I'm sending a formatted string to a PHP script via POST
So say I have the string... "abcdef$ghikl" it will recognize $ghikl as a variable...
Is there any ways to tell PHP that no variables exist within this string?
I know how to hard code it, you just use "'", but since the string is being sent to the script, I don't know what to do...
Thanks guys
For the scope of the question, all the code that's really needed is this:
$string = $_POST['string'];
// a couple strcmp's here, just to see if the string == ""
$array = explode("+", $string);
Try escaping the $
"abcdef\$ghikl"
PHP won't see that as a variable unless you eval() it. Can you show us your code?
Related
I have some variables defined in a PHP file. I then call a python script from the PHP with these variables as arguments. HOWEVER the values of the variables do not carry over to my python script, it seems as though they as passed as strings and not as variables:
$first = "doggy";
$second = "kitty";
$command = escapeshellcmd('python ./script.py $first $second');
$output = shell_exec($command);
The above code produces not "doggy" and "kitty" respectively in my Python script, but literally "$first" and "$second". I want doggy and kitty.
For example when I print in Python:
print sys.argv[1];
>>$first
is the output I am receiving.
My Python script is NOT outputting anything, the script interacts with an API that I wish to use these variables with.
I have tried these previous posts which seem to be near what I am asking. I am either not understanding them, or they are not working. Some answers are too technical or too vague.
Passing value from PHP script to Python script
PHP <-> Python variable exchange
If shell_exec is not the best way for this, I am open to new ideas. Any and all help is appreciated. Thanks for taking the time to look at my post.
A single quoted string will be displayed literally, while a double quoted string will interpret things like variables and new line sequences (\n).
Therefore, change from single to double quotes:
$command = escapeshellcmd("python ./script.py $first $second");
Read more about strings in the PHP manual: http://se1.php.net/manual/en/language.types.string.php
Hey PHP developers I am newbie.
Today I want to run my process.php file in the background because it takes too much time to load... Here is the code that I want to use.
$proc=new BackgroundProcess();
$proc->setCmd('exec php <BASE_PATH>/process.php hello world');
$proc->start();
And I want to add this ids=$postid&reaction=$reaction variable instead of hello world.
And want to receive it with post in process.php file like this
$id =$_POST['ids'];
$type = $_POST['reaction'];
I am using this GitHub file
https://github.com/pandasanjay/php-script-background-processer/blob/master/README.md
Before doing downvote answer me I am a newbie in PHP.
You can try exec() for this. If you want to pass parameters then try like this.
//it will store logs to log_data.log
exec("php process.php $id $type >log_data.log &");
Hope this will work for you :)
Try like this
function execInBackground() {
//this will run in background
exec("php process.php $id $type > /dev/null &");
}
As soon as it is not HTTP request at all, you cannot access $_GET and $_POST superglobals. The right way to receive arguments in this case, is to access the array $argv. See official documentation:
http://php.net/manual/en/reserved.variables.argv.php
UPD: And, well, if you really want to pass $_GET/$_POST params to this script executed via shell, here is a dirty trick:
$get_params_as_string = base64_encode(json_encode($_GET));
$proc=new BackgroundProcess();
$proc->setCmd("exec php <BASE_PATH>/process.php {$get_params_as_string}");
$proc->start();
And in your process.php access it like this:
$get_params = json_decode(base64_decode($argv[1]), true);
So, we are just created JSON from $_GET array. Then, as we know that JSON string contains special characters(like ", {, }, etc), and to avoid dealing with problems of escaping and unescaping, we simply encode this string as base64. It guarantees us absence of special characters in result string. Now we can use this string as a single argument, which we will pass to shell command (your BackgroundProcess). And finally, in process.php we can access this string from $args[1], then decode from base64, then decode from JSON to a regular PHP array. Here we go.
This solution is provided only for educational purpose, please don't ever do it in real life.
OK, so I shave my head, but if I had hair I wouldn't need a razor because I'd have torn it all out tonight. It's gone 3am and what looked like a simple solution at 00:30 has become far from it.
Please see the code extract below..
$psusername = substr($list[$count],16);
if ($psusername == $psu_value){
$answer = "YES";
}
else {
$answer = "NO";
}
$psusername holds the value "normann" which is taken from a URL in a text based file (url.db)
$psu_value also holds the value "normann" which is retrieved from a cookie set on the user's computer (or a parameter in the browser address bar - URL).
However, and I'm sure you can guess my problem, the variable $answer contains "NO" from the test above.
All the PHP I know I've picked up from Google searches and you guys here, so I'm no expert, which is perhaps evident.
Maybe this is a schoolboy error, but I cannot figure out what I'm doing wrong. My assumption is that the data types differ. Ultimately, I want to compare the two variables and have a TRUE result when they contain the same information (i.e normann = normann).
So if you very clever fellows can point out why two variables echo what appears to be the same information but are in fact different, it'd be a very useful lesson for me and make my users very happy.
Do they echo the same thing when you do:
echo gettype($psusername) . '\n' . gettype($psu_value);
Since i can't see what data is stored in the array $list (and the index $count), I cannot suggest a full solution to yuor problem.
But i can suggest you to insert this code right before the if statement:
var_dump($psusername);
var_dump($psu_value);
and see why the two variables are not identical.
The var_dump function will output the content stored in the variable and the type (string, integer, array ec..), so you will figure out why the if statement is returning false
Since it looks like you have non-printable characters in your string, you can strip them out before the comparison. This will remove whatever is not printable in your character set:
$psusername = preg_replace("/[[:^print:]]/", "", $psusername);
0D 0A is a new line. The first is the carriage return (CR) character and the second is the new line (NL) character. They are also known as \r and \n.
You can just trim it off using trim().
$psusername = trim($psusername);
Or if it only occurs at the end of the string then rtrim() would do the job:
$psusername = rtrim($psusername);
If you are getting the values from the file using file() then you can pass FILE_IGNORE_NEW_LINES as the second argument, and that will remove the new line:
$contents = file('url.db', FILE_IGNORE_NEW_LINES);
I just want to thank all who responded. I realised after viewing my logfile the outputs in HEX format that it was the carriage return values causing the variables to mismatch and a I mentioned was able to resolve (trim) with the following code..
$psusername = preg_replace("/[^[:alnum:]]/u", '', $psusername);
I also know that the system within which the profiles and usernames are created allow both upper and lower case values to match, so I took the precaution of building that functionality into my code as an added measure of completeness.
And I'm happy to say, the code functions perfectly now.
Once again, thanks for your responses and suggestions.
I get a string, from an external clientside script, which must later be attached as part of an url. Now I am wondering what is the best way to santitize such data?
The string I get will have a structure like this:
dynamicVal#staticVal:dynamicVal
This value will then be added to an url:
http://the-page.com/dynamicVal#staticVal:dynamicVal
The url is then used as followed:
$link = htmlspecialchars("http://external-page.com/dynamicVal#staticVal:dynamicVal", ENT_QUOTES);
$var = "'Open URL'";
Problem is, htmlspecialchars wont help to prevent execution of random javascript code, e.g. by adding this alert to the value:
dynamicVal#staticVal:dynamicVal'+alert(\"breakout\")+'
Using rawurlencode wont help either, because it is not a value of a parameter but a real part of the url.
So what is the best way to sanitize the passed string when concatenating to the url?
Thanks in advance.
Edit:
Using rawurlencode only on the dynamic parts actually also didn't solve the issue, the javascript still got executed.
Test snippet:
$splitVal = "#staticVal:";
$tmpArr = explode($splitVal, "dynamicVal#staticVal:dynamicVal'+alert(\"breakout\")+'");
$link = htmlspecialchars(sprintf("http://external-page.com/"."%s$splitVal%s", rawurlencode($tmpArr[0]), rawurlencode($tmpArr[1])), ENT_QUOTES);
echo "'Open URL'";
Edit2:
Using json_encode when passing the string as javascript argument didn't help either.
Adapted test snippet:
$splitVal = "#staticVal:";
$tmpArr = explode($splitVal, "dynamicVal#staticVal:dynamicVal\"+alert('breakout')+\"");
$link = htmlspecialchars(sprintf("http://external-page.com/"."%s$splitVal%s", rawurlencode($tmpArr[0]), rawurlencode($tmpArr[1])), ENT_QUOTES);
echo "'Open URL'";
Adaptions done:
Switched the quotes in the malicous JS.
Moved htmlspecialchars around json_encode, because a double quoted string gets returned which would break the html otherwise.
You should use urlencode() for this. Not on the whole string but on the dynamic parts only.
$link = sprintf('http://external-page.com/%s#staticVal:%s', urlencode('dynamicVal'), urlencode('dynamicVal'));
$var = "'Open URL'";
EDIT:
OK - I see your problem. I didn't realize that you insert the code into a JavaScript function call. You'll have to ensure that the JavaScript interpreter treats your link as a string argument to window.open():
$link = sprintf('http://external-page.com/%s#staticVal:%s', urlencode('dynamicVal'), urlencode('dynamicVal'));
$var = "'Open URL'";
For completenes, I was able to solve that issue by simply putting addslashes on the dynamic part before using rawurlencode.
Both function calls are needed to prevent breaking out. Using addslashes prevents normal quotes (',") and rawurlencode prevents already encoded quotes (%29,%22) to cause harm.
So final solution looks like this:
$splitVal = "#staticVal:";
$tmpArr = explode($splitVal, "dynamicVal#staticVal:dynamicVal'+alert(\"breakout\")+'");
$link = htmlspecialchars(sprintf("http://external-page.com/"."%s$splitVal%s", rawurlencode(addslashes($tmpArr[0])), rawurlencode(addslashes($tmpArr[1]))), ENT_QUOTES);
echo "'Open URL'";
I have a string that has HTML & PHP in it, when I pull the string from the database, it is echo'd to screen, but the PHP code doesn't display. The string looks like this:
$string = 'Hello <?php echo 'World';?>';
echo $string;
Output
Hello
Source Code
Hello <?php echo 'World';?>
When I look in the source code, I can see the php line there. So what I need to do is eval() just the php segment that is in the string.
One thing to consider is that the PHP could be located anywhere in the string at any given time.
* Just to clarify, my PHP config is correct, this is a case of some PHP being dumped from the database and not rendering, because I am echo'ing a variable with the PHP code in it, it fails to run. *
Thanks again for any help I may receive.
$str = "Hello
<?php echo 'World';?>";
$matches = array();
preg_match('/<\?php (.+) \?>/x', $str, $matches);
eval($matches[1]);
This will work, but like others have and will suggest, this is a terrible idea. Your application architecture should never revolve around storing code in the database.
Most simply, if you have pages that always need to display strings, store those strings in the database, not code to produce them. Real world data is more complicated than this, but must always be properly modelled in the database.
Edit: Would need adapting with preg_replace_callback to remove the source/interpolate correctly.
You shouldn't eval the php code, just run it. It's need to be php interpreter installed, and apache+php properly configured. Then this .php file should output Hello World.
Answer to the edit:
Use preg_replace_callback to get the php part, eval it, replace the input to the output, then echo it.
But. If you should eval things come from database, i'm almost sure, it's a design error.
eval() should work fine, as long as the code is proper PHP and ends with a semicolon. How about you strip off the php tag first, then eval it.
The following example was tested and works:
<?php
$db_result = "<?php echo 'World';?>";
$stripped_code = str_replace('?>', '', str_replace('<?php', '', $db_result));
eval($stripped_code);
?>
Just make sure that whatever you retrieve from the db has been properly sanitized first, since you're essentially allowing anyone who can get content into the db, to execute code.