Here is my question
I have a class say ABC and a function XYZ defined inside it and that function is returning something based on the above logic in it.
class ABC {
function XYZ{
..........
.......
return "--- ";
}
}
Now there is an object on another page of this class which calls this method.
$z= new ABC;
if( $z->XYZ() )
{
some output
}
else{
another output
}
My problem is i dont have access to PAGE 2. but i need to change the output of else statement. I have only access to class ABC because i am overriding it in a module. so, in short i can only alter function XYZ. Whats the solution??
If its of any significance, i am working on MAGENTO ECOMMERCE Platform and class is a block class and page 2 is a template
You can alter the output html with an observer with the http_response_send_before event.
Capture the html and do your stuff.
You have a good explanation here
I hope this can help you
you can also do as follow :
<?php
ob_start();
// do your stuff
// ...
// here you capture all the output that it is generated by your scripts
$v = ob_get_contents();
// alter the value of $v by detecting if it should be changed. you can user regex for example to
// detect and update
// ...
// here you clean all data stored in buffer
ob_clean();
// and put the updated data in buffer
print $v;
// end of buffer operations
ob_end_flush();
?>
hope it helps,
You need a way to differentiate PAGE1 from PAGE2, lets say by the URL if it's possible. So you would have to change your method that will check on which page is currently and according to it, it will change the output, but you must write the output in the method itself instead of writing it in the template.
class ABC {
function XYZ {
$result = $this->getResult(); //Helper method to get the result.
if ($result) {
//Do something when result is true.
} else {
$url = $this->checkUrl(); //Check URL of the page.
if ($url == PAGE2) { //If you are on PAGE2
//Do something specific for the PAGE2
} else {
//Do something for all other pages
}
}
}
}
I know it's not the perfect solution, but I hope it will help you somehow.
The page number has to be specified somewhere in the $_GET or the $_POST array (or in another query). Check that variable and implement the alternative logic.
Related
I have created a page on which a form posts its value. So I add some lines to get those values like
$parameter = mysqli_real_escape_string($con,$_POST['Parameter']);
But when I open that page without that form it shows Notice that
Undefined index parameter in page on line.
So I want to make something like if I post the values then only specific area will work.
Otherwise remaining area will work just like if condition.
For ex.
if(post)
{}
else
{}
How can I do this?
First you would need to check if the values are set properly..You can do it with the if condition which would be like
if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST)){
// do the things after form processing
}else{
//things you want to do after form breaks.
}
Use isset() to check
if(isset($_POST['Parameter'])){
//desired tasks
//$parameter = mysqli_real_escape_string($con,$_POST['Parameter']);
}else{
//other task
}
You can use isset() function. In your case if should be like
if(isset($_POST['param']))
{
//Do something
}
else
{
//Do something else
}
I'm working with a page that, once a link is called this script checks and if the POST contains the keyword it and then finds that page. However no matter how I organize this if it doesn't work.
<?PHP
if($_POST['page']) {
$page = (int)$_POST['page'];
$exists = file_exists('pages/page_'.$page.'html');
if($exists) {
echo file_get_contexnts('pages/page_'.$page.'html');
} else {
echo 'There is no such page!';
}
} else if ($_POST['course']) die("0"); {
$course = (int)$_POST['course'];
$exists = file_exists('courses/course_'.$course.'html');
if($exists) {
echo file_get_contexnts('courses/course_'.$course.'html');
die("1");
} else {
echo 'There is no such page!';
}
}
?>
The error I'm currently receiving with this setup is:
Notice: Undefined index: course in C:\wamp\www\Home Page\load_page.php on line 12
Call Stack
# Time Memory Function Location
1 0.0003 253944 {main}( ) ..\load_page.php:0
Is it because there is no 'course' in the page? I might be confused of the code I'm modifying a tutorial of a simple ajax website. It is possible what I am trying to do does not work.
In that case how could I possible go about doing what I want to do.
Right now I have a home page and it loads in another page without switching pages. I like the floridness of it. I would like to have a sort of sub call. So if you are on the home page and you go to courses page then you can click on a specific course and that will load from a different directory within the courses directory.
Homepage (when you click on courses you go to...)
pages/courses_home.html (when you click on a course you go to...)
courses/course_1.html (you can view course and then click back to directory above or go to home)
That is the structure I'm looking to try to achieve.
If more information is needed please let me know what and I'll do my best to include it. Thank you.
The syntax should be:
if(isset($_POST["page"])) {
} elseif(isset($_POST["course"])) {
}
I am not sure why you have a die statement there, but I don't think it belongs. Also, keep in mind the logic for what happens if neither of these conditions is met.
Edit: also keep in mind that isset doesn't prevent empty strings, so you may want to check for that as well. A function you could use is
function checkPost($value) {
return isset($_POST[$value]) && $_POST[$value] !== "";
}
To use:
if(checkPost('page')) {
//some logic
}
Wrong syntax.
elseif ($_POST['course']) {
without die statement.If 'course' undefined else statement works and does not get error. Sorry for bad English.
Try this:
if isset(($_POST['page'])) {
...
} else if isset(($_POST['course'])) die("0"); {
instead of this:
if($_POST['page']) {
...
} else if ($_POST['course']) die("0"); {
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"){
}
}
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
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();
?>