PHP Modify Variable - php

There is a PHP file called test2.php,the code is in follow:
<?php
$data=array(
'name' => 'jack',
'age' => 8,
);
?>
I want to modify the $data in anoher php file called test1.php,
but i find that if only use:
require_once "./test2.php";
$data['age']=10;
echo $data['age'];
Although the output is 10,but $data in test2.php dosen't change.
I want to know how to edit a PHP file in anoher PHP file.

To change the contents of test2.php, you need to use a code editor (or... thru file_put_contents (make sure your file is writable), or use a database approach to store the data values, etc.)
However, if you just want to change the value of the age element of the $data array thru programming, then you can use session variables to do what you want
So change test2.php to
<?php
session_start();
if (!isset($_SESSION["data"])) {
$_SESSION["data"]=array(
'name' => 'jack',
'age' => 8,
);
}
echo $_SESSION["data"]["age"];
?>
and use the following as test1.php
<?php
session_start();
//require_once "./test2.php";
//$data['age']=10;
//echo $data['age'];
$_SESSION["data"]["age"]=10;
echo "Data changed, please visit test2.php to see the effect";
?>
Please try these steps:
visit the test2.php and see the value of $_SESSION["data"]["age"] echoed
visit the test1.php (to change the data)
visit test2.php and see what happens

Related

How to store the list of data into session with single line in codeigniter

I want to store the list of data into session with single line and then how to extract that data on view.userData variable contains list of data.I can store the data like below that i know.but instead of writing multiple line can i store with single line.and how can i extract that data to use on view.Thanks in Advance.
$userData=$google_oauthV2->userinfo->get();
$this->session->set_userdata('userdata',$userData['id']);
$this->session->set_userdata('username',$userData['given_name'];
Can I store the data like below?
$this->session->set_userdata('userdata',$userData);
How can use the variable on view like this it is giving nothing
<?php if(!empty($userdata['given_name'])){?>
<li>HI <?php echo $userdata['given_name'];?></li>
<?php }
After reading the Codeigniter User Guide on sessions, where this is explained ( as we all have ), you could do the following...
This is demonstration code which is really good for testing stuff out like this.
The View auth_view.php for want of a better name
<h1> View </h1>
<?php if(!empty($this->session->given_name)){?>
<li>Hi <?= $this->session->given_name;?></li>
<?php }
The Controller
// $userData=$google_oauthV2->userinfo->get();
// Recreate the Array from google_oauthV2
$userData['id'] = 1;
$userData['given_name'] = 'Fred Flintstone';
$this->session->set_userdata($userData); // Save ALL the data from the array
var_dump($this->session->userdata()); // DEBUG- Lets look at what we get!
$data = $this->load->view('auth_view', NULL, true);
echo $data;
Does that help explain the possibilities?
I highly recommend reading the user guide, because I did to get this answer.
This is hard for me to answer as I don't know how the set_userdata() function works, ie will it accept an array.
But you could try:
$userData=$google_oauthV2->userinfo->get();
$this->session->set_userdata('data',$userData);
And on the view page:
<?php if(!empty($data['userData']['given_name'])){?>
<li>HI <?php echo $data['userData']['given_name'];?></li>
If that does not work this is what I would do.
$userData=$google_oauthV2->userinfo->get();
$this->session->set_userdata('userdata',$userData['id']);
$this->session->set_userdata('username',$userData['given_name']);
$_SESSION['data'] = $userData;
And on the view page:
<?php if(!empty($_SESSION['data']['userData']['given_name'])){?>
<li>HI <?php echo $_SESSION['data']['userData']['given_name'];?> </li>
<?php }
Also you are missing a right paren on:
$this->session->set_userdata('username',$userData['given_name'];
in your orginal code.
Yes, you can store data like this:
$this->session->set_userdata('userdata',$userData);
To access it from view, just store the session data into a local variable.
$userData = $_SESSION['userdata'];
then you can use it.
<?php if(!empty($userData['given_name'])){ ?>
<li>HI <?php echo $userData['given_name'];?> </li>
<?php } ?>
NOTE:
To use session in codeigniter you have to load the session library in your controllers.You can load it in constroctor or top of the method where you are going set session.(you don't have to load it to view.)
$this->load->library('session');

Array to string convertion Error Cakephp

I am trying to display an icon image and give that image a link with the intern details but not working. I am trying to do like within a cakephp code i am trying to show an image and when a user will click on that image it will show another page with these array('action' => 'detail'), $intern['Intern']['id']) details.Here is my code below. What's wrong with these code
<?php
echo $this->Html->link(($this->Html>image('.img/resource/hover_down_icon.png')),array('action' => 'detail'), $intern['Intern']['id']),array('css' =>'image_down_icon');
?>
Trying to display an image and give it a link,Use this type of method
echo '<img src="hover_down_icon.png" />';
OR
echo "<img src=\"hover_down_icon.png\" /> ";
if you want to send details to another page set the details in a variable and send ,then retrive value at next page by
//Using GET, POST or COOKIE.
$var_value = $_REQUEST['details'];
Try to alter your code with adequate changes
you are using wrong perameter in the action array .you need to use array('action' => 'detail', $intern['Intern']['id']) as one parameter. Try this one
<?php
echo $this->Html->link(($this->Html>image('.img/resource/hover_down_icon.png')),array('action' => 'detail', $intern['Intern']['id']),array('css' =>'image_down_icon'));
?>

passing variables from php file to anther

How to pass variables from a php file to another while it is not html inputs ,just i have a link refer to the other file and i want to pass variables or values to it
Example:
File1.php
<?php
$name='OdO';
echo "<a href='File2.php'>Go To File2</a>";
?>
File2.php
<?php
echo $name;
?>
Use sessions to store any small value that needs to persist over several requests.
File1.php:
session_start();
$_SESSION['var'] = 'foo';
File2.php:
session_start();
$var = $_SESSION['var']; // $var becomes 'foo'
Try to use sessions. Or you can send a GET parameters.
You can use URLs to pass the value too.
like
index.php?id=1&value=certain
and access it later like
$id = $_GET['id'];
$value = $_GET['value'];
However, POST might be much reliable. Sessions/Cookies and database might be used to make the values globally available.
Here's one (bad) solution, using output buffering:
File 1:
<?php
$name = 'OdO';
echo 'Go To File2';
?>
File 2:
<?php
ob_start();
include 'File1.php';
ob_end_clean();
echo $name;
?>

PHP - include a php file and also send query parameters

I have to show a page from my php script based on certain conditions. I have an if condition and am doing an "include" if the condition is satisfied.
if(condition here){
include "myFile.php?id='$someVar'";
}
Now the problem is the server has a file "myFile.php" but I want to make a call to this file with an argument (id) and the value of "id" will change with each call.
Can someone please tell me how to achieve this?
Thanks.
Imagine the include as what it is: A copy & paste of the contents of the included PHP file which will then be interpreted. There is no scope change at all, so you can still access $someVar in the included file directly (even though you might consider a class based structure where you pass $someVar as a parameter or refer to a few global variables).
You could do something like this to achieve the effect you are after:
$_GET['id']=$somevar;
include('myFile.php');
However, it sounds like you are using this include like some kind of function call (you mention calling it repeatedly with different arguments).
In this case, why not turn it into a regular function, included once and called multiple times?
An include is just like a code insertion. You get in your included code the exact same variables you have in your base code. So you can do this in your main file :
<?
if ($condition == true)
{
$id = 12345;
include 'myFile.php';
}
?>
And in "myFile.php" :
<?
echo 'My id is : ' . $id . '!';
?>
This will output :
My id is 12345 !
If you are going to write this include manually in the PHP file - the answer of Daff is perfect.
Anyway, if you need to do what was the initial question, here is a small simple function to achieve that:
<?php
// Include php file from string with GET parameters
function include_get($phpinclude)
{
// find ? if available
$pos_incl = strpos($phpinclude, '?');
if ($pos_incl !== FALSE)
{
// divide the string in two part, before ? and after
// after ? - the query string
$qry_string = substr($phpinclude, $pos_incl+1);
// before ? - the real name of the file to be included
$phpinclude = substr($phpinclude, 0, $pos_incl);
// transform to array with & as divisor
$arr_qstr = explode('&',$qry_string);
// in $arr_qstr you should have a result like this:
// ('id=123', 'active=no', ...)
foreach ($arr_qstr as $param_value) {
// for each element in above array, split to variable name and its value
list($qstr_name, $qstr_value) = explode('=', $param_value);
// $qstr_name will hold the name of the variable we need - 'id', 'active', ...
// $qstr_value - the corresponding value
// $$qstr_name - this construction creates variable variable
// this means from variable $qstr_name = 'id', adding another $ sign in front you will receive variable $id
// the second iteration will give you variable $active and so on
$$qstr_name = $qstr_value;
}
}
// now it's time to include the real php file
// all necessary variables are already defined and will be in the same scope of included file
include($phpinclude);
}
?>
I'm using this variable variable construction very often.
The simplest way to do this is like this
index.php
<?php $active = 'home'; include 'second.php'; ?>
second.php
<?php echo $active; ?>
You can share variables since you are including 2 files by using "include"
In the file you include, wrap the html in a function.
<?php function($myVar) {?>
<div>
<?php echo $myVar; ?>
</div>
<?php } ?>
In the file where you want it to be included, include the file and then call the function with the parameters you want.
I know this has been a while, however, Iam wondering whether the best way to handle this would be to utilize the be session variable(s)
In your myFile.php you'd have
<?php
$MySomeVAR = $_SESSION['SomeVar'];
?>
And in the calling file
<?php
session_start();
$_SESSION['SomeVar'] = $SomeVAR;
include('myFile.php');
echo $MySomeVAR;
?>
Would this circumvent the "suggested" need to Functionize the whole process?
I have ran into this when doing ajax forms where I include multiple field sets. Taking for example an employment application. I start out with one professional reference set and I have a button that says "Add More". This does an ajax call with a $count parameter to include the input set again (name, contact, phone.. etc) This works fine on first page call as I do something like:
<?php
include('references.php');`
?>
User presses a button that makes an ajax call ajax('references.php?count=1'); Then inside the references.php file I have something like:
<?php
$count = isset($_GET['count']) ? $_GET['count'] : 0;
?>
I also have other dynamic includes like this throughout the site that pass parameters. The problem happens when the user presses submit and there is a form error. So now to not duplicate code to include those extra field sets that where dynamically included, i created a function that will setup the include with the appropriate GET params.
<?php
function include_get_params($file) {
$parts = explode('?', $file);
if (isset($parts[1])) {
parse_str($parts[1], $output);
foreach ($output as $key => $value) {
$_GET[$key] = $value;
}
}
include($parts[0]);
}
?>
The function checks for query params, and automatically adds them to the $_GET variable. This has worked pretty good for my use cases.
Here is an example on the form page when called:
<?php
// We check for a total of 12
for ($i=0; $i<12; $i++) {
if (isset($_POST['references_name_'.$i]) && !empty($_POST['references_name_'.$i])) {
include_get_params(DIR .'references.php?count='. $i);
} else {
break;
}
}
?>
Just another example of including GET params dynamically to accommodate certain use cases. Hope this helps. Please note this code isn't in its complete state but this should be enough to get anyone started pretty good for their use case.
You can use $GLOBALS to solve this issue as well.
$myvar = "Hey";
include ("test.php");
echo $GLOBALS["myvar"];
If anyone else is on this question, when using include('somepath.php'); and that file contains a function, the var must be declared there as well. The inclusion of $var=$var; won't always work. Try running these:
one.php:
<?php
$vars = array('stack','exchange','.com');
include('two.php'); /*----- "paste" contents of two.php */
testFunction(); /*----- execute imported function */
?>
two.php:
<?php
function testFunction(){
global $vars; /*----- vars declared inside func! */
echo $vars[0].$vars[1].$vars[2];
}
?>
Try this also
we can have a function inside the included file then we can call the function with parametrs.
our file for include is test.php
<?php
function testWithParams($param1, $param2, $moreParam = ''){
echo $param1;
}
then we can include the file and call the function with our parameters as a variables or directly
index.php
<?php
include('test.php');
$var1 = 'Hi how are you?';
$var2 = [1,2,3,4,5];
testWithParams($var1, $var2);
Your question is not very clear, but if you want to include the php file (add the source of that page to yours), you just have to do following :
if(condition){
$someVar=someValue;
include "myFile.php";
}
As long as the variable is named $someVar in the myFile.php
I was in the same situation and I needed to include a page by sending some parameters... But in reality what I wanted to do is to redirect the page... if is the case for you, the code is:
<?php
header("Location: http://localhost/planner/layout.php?page=dashboard");
exit();
?>

modify array value from php file in codeigniter or php

i have php file like below and i want to read this php file and get all array value in this php file and i can update value of array
<?php
$lang['country_name']="Country Name";
$lang['zip_code']="Zip Code";
$lang['flag']="Flag";
$lang['site_enabled']="Site Enabled";
$lang['save']="Save";
$lang['cancel']="Cancel";
$lang['country_info']="Country Information";
$lang['new_country']="New Country";
$lang['edit_country']="Edit Counry";
$lang['country']="Country";
$lang['home']="Home";
$lang['no']="No";
$lang['action']="Action";
$lang['show']="Show";
?>
If you want to include this PHP array in another script, you can use the include function.
For example, if you have another file, index.php in the same directory, you can include it and then you will have access to the variable. You can modify it like a normal variable, like so:
index.php
<?php
include `lang_array.php`; // will get the file with the array
echo $lang["no"]; // should output "No"
$lang["show"] = "value"; // update $lang["show"]
?>
Simply you just have include file using php include function.
<?php
include 'file_name.php';
$lang['new_country']="new country 1";
?>

Categories