How can I write php codes as string? - php

I have this code:
<?php $myarray->appends(['action' => $_GET['desc']])->render() ?>
When there is action argument in the url, then my code works as well. Otherwise it throws this error message:
Undefined index: action (View:
/var/www/html/myweb/resources/views/mypage.blade.php)
So I need to do this ->appends(['action' => $_GET['desc']]) dynamically. Something like this:
<?php
if ( isset($_GET['desc']) ) {
$append_param = "->appends(['action' => $_GET['desc']])";
} else {
$append_param = "";
}
$myarray.$append_param->render();
?>
But I'm pretty much sure my code won't work .. I wore code about just for showing you what was my point.
Anyway, can anybody tell me how can I do that in a right way?
All I'm trying to do is: appending action argument to the pagination-links if it already exists. Otherwise I don't want to append it.

You should never take input from a user-controllable source and execute it. Doing this is a major security risk, and it will probably open more security holes in your server than you'd be able to patch in a lifetime.
If you really, really must do this, you can use eval(). But please, make sure you understand the security implications of this.

i think you are just horribly overthinking the whole situation. you don't have to put your code in a string to execute it conditionally, you can just write it as code itself.
having no further information about how your class works internally, the most straightforward and basic way would be:
if ( isset($_GET['desc']) ) {
$myarray->appends(['action' => $_GET['desc']])->render()
} else {
$myarray->render();
}

You cannot do that.
First, if you want to check for a valid key in an array, use "array_key_exists(key, array)" which is hugely recommanded.
if ( array_key_exists('dec',$_GET) ) {
Then, if I understand, you want to "append" data to an Array ? That means adding a value to a key in this array.
This can be done easily with PHP :
$array [ $key ] = $value;
Be very careful on your variable names :
$myarray.$append_param->render();
This makes no sense, if it's an array, you only should use [] on it (or array functions), but if it's an object, you only can use -> on it.

Related

First timer PHP edit to update html, some errors

this is my first time using PHP in a real project environment. The project is pretty simple, take an existing, working PHP site and update the HTML to be consistent with HTML5. After designing the HTML, I am inserting the PHP from the previous site. This works most of the time, but I get a few errors. For instance:
<?
$sec = $_GET['sec'];
if ($sec == "1") {
echo ('Success!');
}
?>
Is causing the error:
Notice: Undefined index: sec in /file_that_holds_site_build.
Of course that is only if the url doesn't include the append tag (=1) that alerts the message.
So the question is this, what am I missing that causes the $GET when there is no $sec? How do I eliminate this error on first page load?
You're getting that notice because you're trying to access an array index that doesn't exist in some scenarios. Here's how you should be getting the data out of the request.
$sec = array_key_exists('sec', $_GET) ? $_GET['sec'] : null;
Thanks to everyone who provided possible answers to this question. It was Daniel that came up with the easiest fix. Again, I am just adjusting someone else's code to work, so a universal solve would involve too much of my own writing. To the point, the final code looks like this:
<?
if (isset($_GET["sec"])){
$sec = $_GET['sec'];
if ($sec == "1") {
echo ('Success! Your username and password have been sent via email.');
}}
?>
Notice the added if statement. As I said in a comment to Daniel, SO SIMPLE!
Thanks again for everyone's help. I hope to be likewise of service to you all soon.
Simple just use isset($_GET['sec']) to check for the parameter 'sec' before using it in the php code. That should eliminate the error. This is quite trivial I suppose.
I often simply extract() the wohle $_GET super global and then either get the desired variable or not. As a kind of "declaration" I initialize each expected variable first with false. This way I find it much easier to handle than individually doing a check like if(isset($_GET['element'])) ...
$var1=$var2=$var3=false; // my desired variables
extract($_GET); // everything I get from the form
// or: extract($_REQUEST);
if ($var1) { /* do something with it */ }
Possible security risk:
Of course you should be aware that everybody could simply include their own variable as an argument to he page ...

CodeIgniter Session syntax

Can someone quickly help me out with CodeIgniter's syntax. I need to access an array I stored in the session's userdata and I cant figure out the proper syntax.
<?php echo $this->session->userdata['user_session']['first_name']; ?>
gives me this error:
Fatal error: Cannot use object of type stdClass as array
All of the answers given in this Question dont work:
Access array variable in session (CodeIgniter)
This is how you get session data:
echo $this->session->userdata('first_name');
Been a while since I've worked in Codeigniter, but if I can remember correctly, when you store an array like you've stated, you'd call it like this:
$this->session->userdata("user_session")['first_name'];
Let me know if that works?
Or you can store that data to a variable, and call the array that way. Like such:
$data = array("bar" => "the_value");
$this->session->set_userdata("foo", $data);
$foo = $this->session->userdata("foo");
echo $foo["bar"]; //Outputs the_value
Let me know if that helped.
However, just to let you know.. Normally, storing the session data goes as follows:
$this->session->set_userdata("first_name", "value");
Really no need to go and set your own array inside of userdata, because that's generally what the userdata array is for.
I found the proper syntax. Well, at least one way to go about it. #Matt GrubB was the closest and put me on the right track.
$temp_session = $this->session->userdata('user_session');
echo $temp_session->first_name;
Since userdata is an object full of info created when I query my database, the easiest way to access the data is to take it and put it in another temporary array. You then have to stab it. I kept stumbling by trying to do $this->temp_session->first_name or something of the like.

Monitor a PHP variable for change in value

I am actually trying to monitor a PHP variable (may be as a separate thread but not possible in PHP) and fire a PHP function whenever the value of the variable changes.
eg: lets take a variable $_GLOBALS['foo']=1;
if at any point in the code, the value of $_GLOBALS['foo'] changes to something else, i want to fire a PHP function immediately.
The variable can be anywhere inside a loop or in a function,etc.
Why i want this: I have a variable which stores the last error occured as a text. If the value of the variable changes from "" to something else, i want to trigger an error. My LOGIC may seem a bit strange but this is what i would like to do.
Thanx in advance.
Edit: I tried: How to use monitors in PHP? and How can one use multi threading in PHP applications but does not seem to solve the problem.
The Code (Thought this could solve some of your doubts on my question):
public function addtag($tagarray,$uid,$tagtype="1")
{
$dbobj=new dboperations();
$uiobj=new uifriend();
$tagid=$uiobj->randomstring(30,DB_SOCIAL,SOCIAL_TAG,tag_tagid);
$c=0;
foreach($tagarray as $tags)
{
$c++;
$tagname=$tags["tagname"];
$taguid=$tags["tagid"];
$dbobj->dbinsert("INSERT INTO ".SOCIAL_TAG." (".tag_tagid.",".tag_fuid.",".tag_tuid.",".tag_tagname.",".tag_tagtype.") VALUES
('$tagid','$uid','$taguid','$tagname','$tagtype')",DB_SOCIAL);
}
if($c==0)
{
$lasterror="No tags were added";return "";
}
else
{
return $tagid;
}
}
Here, if i call a error handling function instead of monitoring the variable, it wont be advisable in my case since the error handling function may do any operation like give alert and redirect to a page or any similar operation.
I asked this question cause, i thought what if the script does not reach the line
return "";
It would affect the project's workflow. Thats what i am worried about.
And the variable i was talking about is $lasterror and i have many functions like this where $lasterror is used.
I saw this, so I built this:
https://github.com/leedavis81/vent
Should solve your problem.
There is no built-in way to do this in PHP, and there's no easy way to add it. It doesn't really feel right for the way the language works anyway.
Instead of setting a variable, you could build a custom function that handles the error - or use PHP's built-in error handling functionality using a custom error handler.
Another error handling method which comes close to what you want to do (I think) is exceptions.

php $POST dynamic variable names security concerns

I am thinking of making a loop to gather all my $_POST variables and assign them to dynamically named variables.Something like this (not tested)
for($i; $i <= $_POST[].length; $i++){
${$_POST[i]} = $_POST[i]
}
But I am wondering about the security of something like this. This would then create a variable in the system for every bit of post data sent to the page. Can that variable be damaging even if the script I write doesn't reference it? Is this the type of thing I should avoid entirely? I have some pages that send quite a few variables and a script like this would prevent a whole lot of writing, but is it safe enough?
Yes there are possible security risks.
Say you have a variable $is_admin defined earlier in the code that gives someone admin abilities. If someone POSTS to that page with
$_POST['is_admin'] = true;
Then $is_admin is now true. Not good.
What's wrong with using $_POST?
Yes there can be security concerns/problems, for example one could overwrite any local variables which are already set, like database, config values ect.
So something like this should be avoided:
$yourImportantVar = 'Something relies on this';
//User POSTS yourImportantVar=overwritten
foreach ($_POST as $key => $value) {
$$key = $value;
}
echo $yourImportantVar; //overwritten
But if you want to implement a loop to save a chunk of code, you could create an allowed array which you loop over and extract out the value from the $_POST.
foreach (array(
'name',
'address',
'somethingelse',
'ect'
) as $key) {
$$key = isset($_POST[$key]) ? $_POST[$key] : null;
}
This is a very bad idea for security and maintainability. Simplified example why...
<?php
if (someRandomSessionCheck()) {
$isAdminUser = true;
}
if ($isAdminUser) {
// give access to everything
}
?>
Someone could post to the page with a variable "isAdminUser=1" and would have access to everything.
Another reason it is a bad idea is you can't clearly see from the script where your variables are created. This reduces maintainability of the script. What if you now want to run the script but instead need to get the data from somewhere else and not a POST?
Only issue I can think of at the moment is when that overwrites the existing variable in the scope. This can be very unsafe depending on what you do with it. Think about the variable being the URL you are doing a HTTP request to. Or worse, some flag variable which accesses some critical part of your code.
I will post an example that speaks about HTTP request:
<?php
$url = "http://safe/url/to/POSTto";
$var = array("url" => "http://www.mysite.com/url"); //assume this is $_POST
foreach($var as $key => $value){
${$key} = $value;
}
//now upon the HttpRequest, your site can receive the (critical) data which was actually meant for the safe site.
?>
EDIT: #Galen has posted about the flag variable I was talking about, so may be I need not post any example to highlight the problem.
PHP had a feature (using the term loosely) called register_globals. It has since been deprecated (PHP 5.3) and removed (PHP 5.4), but it mirrored the functionality for which you are looking. It performed the same thing as the PHP function extract() does, which sets variables in the current scope with names of the keys and values of the matching array values.
This is most definitely a security risk. Consider the example of a poor check for authentication:
if($is_logged_in) {
// Allow execution of destructive actions
}
If this feature was enabled (or you mimicked it), a malicious user would be able to set the variable $is_logged_in and bypass the login screen. Don't worry about saving typing. If you need to copy and paste a code block like this at the beginning of your files:
$something = $_POST['something'];
$another = $_POST['another'];
$stuff = $_POST['stuff'];
//etc.
Not only is it much more secure, but it doesn't leave developers (who aren't expecting register_globals) puzzled when undeclared variables start being used. Also, the fact that PHP has removed it and there are plenty of arguments against its use should be evidence enough.
<?php
/* Suppose that $var_array is an array returned from
wddx_deserialize */
$size = "large";
$var_array = array("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");
echo "$color, $size, $shape, $wddx_size\n";
?>
Please check this. Same thing what you are going do by using loop. may help you
You are basically implementing extract($_POST, EXTR_OVERWRITE) which will overwrite any already existing variables. The manual already warns to use extract in a way you do:
Do not use extract() on untrusted data, like user input (i.e. $_GET, $_FILES, etc.). If you do, for example if you want to run old code that relies on register_globals temporarily, make sure you use one of the non-overwriting extract_type values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini.
This can result in overwriting essential and sensitive variables, including those that cannot really be modified directly like $_SESSION, $_SERVER, and $GLOBALS:
POST /foo.php HTTP/1.1
Content-Type: application/x-www-urlencoded
_SESSION[user]=admin
This would have the same effect as $_SESSION = array('user'=>'admin').

Formatting the POST array to an SQL insert\update string in codeigniter 2

I'm trying to automate form creation and submission in codeigniter.
Basically what I want is to find a way to go over all the data in the POST array and format it correctly to an insert or update sql query.
The problem is I don't know how to access to whole POST array in CI, all I know of is the $this->input->post(field_name) way which only gives you a specific field.
Ideally I would want to send the POST array to the $this->db->insert_string() or $this->db->update_string() to do the job for me.
I know I can still use the php native $_POST array, but this is not recommended and not as secure as CI's input class.
Anyone know a way to do this?
Thanks,
Amos
Eventually I found out that the input class cleans the $_POST array automatically (not talking about XSS cleaning) and so the only advantage to use $this->input->post(something) is that it checks if that key exists.
Since I need the whole array I don't need that check and can safely use $this->db->insert_string($_POST).
If I you do want XSS cleaning you can either turn it on globally in the config or use geocine's answer (I would go for a mix of the 2 examples he gave).
Another way to go if you want the whole array with XSS cleaning and without it turned on globally is to go with WanWizard's Input library extension found here: http://codeigniter.com/forums/viewthread/172705/#821150
foreach($_POST as $key => $value) {
$value = $this->input->post($key);
//do something
}
or
$keys = array_keys($_POST);
for($i=0,$max=count($keys);$i<=$max;$i++)
{
$value = $this->input->xss_clean($_POST[$keys[$i]]);
//do something
}

Categories