View included by $this->include does note recieve passed params - php

Is possible pass parameter to view when i use $this->include method in another view?
In example:
<?php
foreach ($destaques as $camping) {
$this->include('partial', ['camping' => $camping])
}
?>
But partial.php dont recieve $camping value.

When using $this->include you're making an echo of a view into an other one. So by default, the view you're loading will have acces to any data you gave to the parent view but not variables you declared into it.
A few options in your case :
Using the view method :
foreach ($destaques as $camping) {
echo view('partial', ['camping' => $camping]);
}
Moving your foreach loop in the partial view so you'll use $destaques into it.
<?php
// dont forget to echo
echo $this->include('partial')
?>
// or this way with short tags enabled
<?= $this->include('partial') ?>
And just embed your partial view in your previous foreach loop
foreach ($destaques as $camping) {
// whatever your partial view is
}

Hello I try using the parameter option. I test code and it s working. But note the include view layout method work like php default include function and it does not display until you echo it.
Here is my code which I use to test yours and it worked for me. Check it
$inc = '';
foreach ($destaques as $camping) {
$inc .= $this->include('partial', ['camping' => $camping])
}
echo $inc;
And this displayed and worked for me check it. if this is not what you were expecting, just call my attention

Related

Replace Content on Page Based on URL Parameter with PHP

I'd like to replace content within my page based on the URL parameter.
Ideally I'd like to use PHP to get:
if {{parameter is X}} display {{content X}}
if {{parameter is Y}} display {{content Y}}
..for a few pages.
Current set up:
<?php if ($CURRENT_PAGE == "Index") { ?>
<div id="firstDiv">this is the standard page</div>
<?php } ?>
<?php if ($CURRENT_PAGE == "p1") { ?>
<div id-"secondDiv">this is a variation of the page</div>
<?php } ?>
And using include("includes/content.php"); to call the html blocks to the page
The firstDiv displays in index.php as expected, but adding the URL parameter changes nothing - the same div still shows (I'd like it to be replaced with the secondDiv)
It seems $CURRENT_PAGE doesn't like URL parameters - what is the alternative?
Hopefully this makes sense, I'm pretty new to PHP. Happy to provide more details if required.
Thanks in advance for any help.
-- UPDATE --
Thank you for the answers so far!
It seems I missed part of my own code (Thanks to vivek_23 for making me realise this - I'm using a template, excuse me!!)
I have a config file that defines which page is which, as so:
<?php
switch ($_SERVER["SCRIPT_NAME"]) {
case "index.php/?p=1":
$CURRENT_PAGE = "p1";
break;
default:
$CURRENT_PAGE = "Index";
}
?>
Before I learn $_GET, is there a way I can use my current set up?
Thanks again.
-- UPDATE 2 --
I have switched to using the $_GET method, which seems to be working well so far. My issue now is when the parameter is not set it is giving an undefined error. I'll try to remember to update with the fix.
$p = ($_GET['i']);
if($p == "1"){
echo '<div id="firstDiv"><p>this is the first div</p></div>';
}
Thanks to the two answerers below who suggested using $_GET
You can used $_GET like
if($_GET['p']==1){
echo '<div id="firstDiv">this is the standard page</div>';
}else if($_GET['p']==2){
echo '<div id="secondDiv">this is a variation of the page</div>';
}
The other way! you can used basename() with $_SERVER['PHP_SELF']
//echo basename($_SERVER['PHP_SELF']); first execute this and check the result
if(basename($_SERVER['PHP_SELF']) == 'index'){
echo '<div id="firstDiv">this is the standard page</div>';
}else{
echo '<div id="secondDiv">this is a variation of the page</div>';
}
You need to send the parameters on the URL query string, like:
yourdomain.com?p=1
So, with this URL, the query string is "?p=1", where you have a GET parameter named 'p' with a value of '1'.
In PHP to read a GET parameter you can use the associative array $_GET, like this:
$current_page = $_GET['p'];
echo $current_page; // returns '1'
The rest of your logic is OK, you can display one div or the other based on the value of the p parameter.
You can read more about how to read query string parameters here: http://php.net/manual/en/reserved.variables.get.php

How to update an array in another PHP file?

I have index.php file and it contains:
1.class eachObject
class eachObject
{
function outPut()
{
echo '<td> </td>';
}
}
2.class wall
class wall extends eachObject
{
function outPut()
{
echo '<td class="wall"> </td>';
}
}
3.class blank
class blank extends eachObject
{
function outPut()
{
echo '<td class="blank"> </td>';
}
}
I got instances from them:
$wall = new wall();
$blank = new blank();
and I have an array called room including wall and blank:
$room = array();
$room[0] = array($wall, $wall, $blank, $wall, $blank);
and then I will use it in a table to show walls and blanked areas:
<html>
<body>
<?php
echo '<table>';
foreach ($room as $row) {
echo '<tr>';
foreach ($row as $tool) {
$tool->outPut();
}
echo '</tr>';
}
echo '</table>';
?>
</body>
</html>
The question is: how can I change this array in another php file called test.php to have:
$room[0] = array($wall, $wall, $wall, $wall, $blank);
As you can see, the third value changed from $blank to $wall.
and then when I refresh the div which contains the table, I will have a wall instead of blank area.
Since test.php is included/required to index.php, $rooms can be modified there using
$rooms[0][3] = $wall;
but note that this is only possible if both $rooms and $wall are reachable. If you declare them as globals before you include/require test.php and after you include/require index.php you do some changes for $room[0], then it should work and you should have a new value. From your description it seems that you either included/required test.php before $rooms and/or $wall is defined, or the variables are out of context, for instance, inside a function. You will need to make sure that the variables are reachable in the other file and when the other file starts to use them, they are already declared. However, you might want to rethink the way your code is structured and use some ideas like MVC. If this answer is not enough for you to solve your problem, then you will need to add more details about your code.
Create a functional construct (class with methods, function, ...) that first deletes your old test.php file, then creates a new one, adding line by line the content you wanted to add. (See the Php filesystem functions for such an application)
That is a way that works, but it is not a way I would recommend. (But I do not know your project, I might not see the whole image) Better would be a way using a serialised array. So you serialise your new array, save that string to your file and each time you want to use your array, just deserialise the string in your file. And last method: use a database, if possible.
you can change the value per
$room[0][3] = $wall;

How to use variable inside parameter $_GET? example: ($_GET[$my_var])

I'm developing a plugin for wordpress, the parameter of the $ _GET is recorded in the database according to the preference of the User via the Wordpress Admin Panel. The following validation has to be via the $ _GET, this is the function:
$db_url = get_option('my_get_url');
// returns the value of the database entered by User
// on this case return --> page=nosupport
$url_explode = explode("=", $db_url);
$url_before = $url_explode[0]; // --> page
$url_after = $url_explode[1]; // --> nosupport
echo "Before: ".$url_before; // here are ok, return --> page
echo "After: ".$url_after; // here are ok, return --> nosupport
My problem is here:
// here $_GET no have any value, dont work on validate...
if($_GET[$url_before] != ""){
if($_GET['$url_before']=="nosupport"){
// my function goes here...
}
}
I using for test the parameter:
echo $_GET[$url_before];
But dont return any value...
I found the problem, i had already tested all of these options, but ever dont working, the problem was that I was testing the function inside the main page of my site, and on the main page (mysite.com) does not get the parameter (?page=nossuport), so always returning null values​​, when I used the variable in the GET or used the echo $GET[$my_var] to test.. It was a great carelessness of mine, would never work...
by the way, the two parameters works correctly:
$_GET[$url_before]
$_GET["$url_before"]
The Problem are solved, Thanks for help.
if($_GET[$url_before] != ""){
if($_GET[$url_before]=="nosupport"){ // note no "" here
// my function goes here...
}
}
In your solution, the key was treated as a string, with no variables evaluated.
You forgot to take out the ' in the second condition.
You wrote:
$_GET['$url_before']
I'm guessing it should be:
$_GET[$url_before]
foreach($_GET as $key => $value){
if($key == "nosupport"){
}
}

HREF to call a PHP function and pass a variable?

Is it possible to create an HREF link that calls a PHP function and passes a variable along with it?
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='search($id)' >$name</a>";
}
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
You can do this easily without using a framework. By default, anything that comes after a ? in a URL is a GET variable.
So for example, www.google.com/search.html?term=blah
Would go to www.google.com/search.html, and would pass the GET variable "term" with the value "blah".
Multiple variables can be separated with a &
So for example, www.google.com/search.html?term=blah&term2=cool
The GET method is independent of PHP, and is part of the HTTP specification.
PHP handles GET requests easily by automatically creating the superglobal variable $_GET[], where each array index is a GET variable name and the value of the array index is the value of the variable.
Here is some demo code to show how this works:
<?php
//check if the get variable exists
if (isset($_GET['search']))
{
search($_GET['search']);
}
function Search($res)
{
//real search code goes here
echo $res;
}
?>
Search
which will print out 15 because it is the value of search and my search dummy function just prints out any result it gets
The HTML output needs to look like
anchor text
Your function will need to output this information within that format.
No, you cannot do it directly. You can only link to a URL.
In this case, you can pass the function name and parameter in the query string and then handle it in PHP as shown below:
print "<a href='yourphpscript.php?fn=search&id=$id' >$name</a>";
And, in the PHP code :
if ($_GET['fn'] == "search")
if (!empty($_GET['id']))
search($id);
Make sure that you sanitize the GET parameters.
No, at least not directly.
You can link to a URL
You can include data in the query string of that URL (<a href="myProgram.php?foo=bar">)
That URL can be handled by a PHP program
That PHP program can call a function as the only thing it does
You can pass data from $_GET['foo'] to that function
Yes, you can do it. Example:
From your view:
<p>Edit
Where 1 is a parameter you want to send. It can be a data taken from an object too.
From your controller:
function test($id){
#code...
}
Simply do this
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='?search=" . $id . "' > " . $name . "</a>";
}
}
if (isset($_REQUEST['search'])) {
search($_REQUEST['search']);
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
Also make sure that your $json_output is accessible with is the sample() function. You can do it either way
<?php
function sample(){
global $json_output;
// rest of the code
}
?>
or
<?php
function sample($json_output){
// rest of the code
}
?>
Set query string in your link's href with the value and access it with $_GET or $_REQUEST
<?php
if ( isset($_REQUEST['search']) ) {
search( $_REQUEST['search'] );
}
function Search($res) {
// search here
}
echo "<a href='?search='" . $id . "'>" . $name . "</a>";
?>
Yes, this is possible, but you need an MVC type structure, and .htaccess URL rewriting turned on as well.
Here's some reading material to get you started in understanding what MVC is all about.
http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
And if you want to choose a sweet framework, instead of reinventing the MVC wheel, I highly suggest, LARAVEL 4

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();
?>

Categories