I have a ajax.php file that contains the following sample code:
switch($_REQUEST['request_name'])
{
case 'edit':
echo "edit mode";
break;
case 'delete':
echo "delete mode";
break;
default:
die("Error: wrong request name ".$_REQUEST['request_name']);
break;
}
I have another file index.php that I want to call results from ajax.php. Hmm.. how do I do it? I normally use javascript to call results from ajax.php. But is there a way I can call results from within index.php as well? Code is wrong below but something to this effect.
$result = include("ajax.php?request_name=delete");
echo $result;
You were correct to use include but instead of passing in the vars like a query string you can just define them before your include and they'll be brought in to the file.
$_REQUEST['request_name'] = 'edit';
include('ajax.php');
Any variables that are then defined in your included file will now be available in the parent file as well. If you were to process the edit action and store the results in a var called $results in ajax.php you would have access to that same variable from within the including file (after the include statement).
$_REQUEST['request_name'] = 'edit';
include('ajax.php');
echo $results;
Related
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;
I have a cms admin section with the option comments; when i press comments on the admin menu it should take me to comments.php which includes the code below; by default it should load all my comments on a grid, however when i press comments its not displaying anything the page is blank ? My code:
<?php
if(isset($_GET['source'])){
$source1=$_GET['source'];
if(!empty($source1)){
switch($source1){
case 'add_post':
include"includes/add_posts.php";
break;
case 'edit_post':
include"includes/edit_post.php";
break;
case 'view_all_comments':
include "includes/view_all_comments.php";
break;
default:
include "includes/view_all_comments.php";
}
}
}
?>
when u load comments.php the url doesnt sent any parameter via get, on your code you are checking if the source is not empty which on your case its empty at first. Then preform switch statment, in your case it will not preform the switch as the source is empty and thats why you are not seeing anything. You can fix that by adding an else on your if and include view_all_comments.php or like the code below:
<?php
$source1=isset($_GET['source']);
switch($source1){
case 'add_post':
include"includes/add_posts.php";
break;
case 'edit_post':
include"includes/edit_post.php";
break;
case 'view_all_comments':
include "includes/view_all_comments.php";
break;
default:
include "includes/view_all_comments.php";
}
?>
I have several links on a page, all of which need to execute a different method in PHP.
A link for "Create File", one for "Rename File" and one for "Delete file".
The only way I know of to execute PHP code with each hyperlink is by giving the URL of a different PHP file to each hyperlink.
Is there a way to link the URL (HREF) to a SPECIFIC method in a PHP file?
Here are a few lines of code that do not work, but might help you understand what I want to achieve:
Create File
Rename File
Rename File
I'm also pretty sure I'm taking the wrong approach, but I'm too much of a PHP novice to know better :)
Common approach in your situation would be setting a GET parameter called something like fileAction and then switching it's value, so your links would look like this:
Create File
Rename File
Delete File
And your filemanagement.php logiŃ would look somewhat like this:
<?php
$fileAction = $_GET['fileAction'];
switch ($fileAction) {
case 'create':
createFile();
break;
case 'rename':
renameFile();
break;
case 'delete':
deleteFile();
break;
default:
//your default logic here
break;
}
?>
you can send the method name as a $_GET value and execute the corresponding function, like so:
HTML:
Run some method
PHP:
<?php
if (isset($_GET['method'])) {
$method = $_GET['method'];
$method();
}
<?php
#$Method = $_GET['Method'];
if (!(isset($Method)))
{
$Method = "0"; // If URL does not contain ?Method=1 Then Assign It To 0
}
if ($Method > "3")
{
$Method = "0";
// If ?Method= value is higher than 3 Then Set it to 0
}
if ($Method == "0")
{
echo "Create File";
echo "Rename File";
echo "Delete File";
}
elseif ($Method == "1")
{
// Method = 1 Is Create File So:
// CreateFile();
}
elseif ($Method == "2")
{
// Method 2 is Rename File
// renameFile();
}
elseif ($Method == "3")
{
// Method 3 Is Delete File
// deleteFile();
}
?>
What you are describing is the perfect scenario for using an MVC framework. There are tons of these frameworks out there and they help you in organising your code better. If you are just starting out in PHP, I highly suggest you to look at a framework and some code samples on the web in order to get your head around the MVC principle.
When using an MVC framework, you simply define routes which map to a particular function (action) in a particular class (controller). I won't get too far in this answer, but I suggest you go through these ressources to get you started :
MVC definition on Wikipedia
CodeIgniter, an MVC framework for PHP
i am new to php, but im trying. i need you guys help.
i have the following url in the browser address bar www.dome.com\mypage.php?stu=12234342
i am trying to pass the url from the main page to the select case page call select.php
if i should echo the url i get www.dome.com\select.php. so i have decided to echo $_SERVER['HTTP_REFERER']
instead, this gives me the correct url. how can i echo the variable from www.dome.com\mypage.php?stu=12234342 (12234342)
unto select.php. select.php contains code that needs the $var stu=12234342 in order to display the correct message.
$request_url=$_SERVER['HTTP_REFERER'] ; // takes the url from the browers
echo $request_url;
$cOption = $_GET['id'];
switch($cOption) {
case 1:
echo ' some text';
break;
case 2:
echo ' this page.php';
break;
case 3:
echo 'got it';
break;
default:
echo 'Whoops, didn\'t understand that option: <i>'.$cOption.'</i>';
}
?>
You may use parse_url() and parse_string() to grab the variable from a url:
<?php
//assuming www.dome.com/mypage.php?stu=12234342;
$url=$_SERVER['HTTP_REFERER'];
//parse the url to get the query_string-part
$parsed_url=parse_url($url);
//create variables from the query_string
parse_str($parsed_url['query'], $unsafe_vars);
//use the variables
echo $unsafe_vars['stu'];//outputs 12234342
?>
But note: you can't rely on the availability of HTTP_REFERER.
try
echo $_GET['stu'];
on select.php
That's why you need to call the select.php file like this:
www.dome.com/select.php?stu=12234342
and then you can add:
echo $_GET['stu'];
By the way, you need to research about XSS, because that's a huge vulnerability.
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();
?>