Define A Variable By Calling Page Content - php

On my php buffering page, I am able to create and define a variable by using the contents of my form field, like this...
PHP:
<?php $data = $_POST['data']; ?>
And in my form, I am able to create the 'value' of the 'data' field by using php 'include' to call in the data from 'data_page.php' like this...
FORM:
<input name="data" type="text" value="<?php include "data_page.php";?>">
This process does work, however... I would like to bypass the form part of the process and still create that same variable.
I have tried a few ways to do this, including this...
<?php $data = $_REQUEST['data_page.php']; ?>
But so far, nothing seems to work.
Is there a way to create that variable with the same value (contained in data_page.php) which the form process would provide? And if so... what am I doing wrong?

If I right understand what you need then you should turn on output buffering
ob_start();
include('data_page.php');
$data = ob_get_contents();
ob_end_clean();
echo $data;
or use file_get_contents()
for ($i = 1; $i <= 5; $i++) {
${"data{$i}"} = (is_readable("data_page{$i}.php")) ? file_get_contents("data_page{$i}.php") : '';
}

Related

Post url in form with get method

I have a problem today!
I am trying to post a URL in form via GET method
When I post URL it automatically converts to http://example.com/?url=http%3A%2F%2Fanonylinq.com%2F%3Fi%3Dphpphp from http://anonylinq.com/?i=phpphpIs there any way to solve this problem? I am doing this via PHP.
because I want to echo "i" as - <?php echo $i; ?> Everything else is done but I am stuck at this point.
Already done this too -
$urlSplitted = explode('?i=', $_GET['url']); $i = $urlSplitted[1];
if you want to go this road:
$urlSplitted = explode('?i=', $_GET['url']); $i = $urlSplitted[1];
you should use
$urlSplitted = explode('%3Fi%3D', $_GET['url']); $i = $urlSplitted[1];
Take a look at http://php.net/manual/en/function.urldecode.php
That should do the trick for it.
e.g.
$string = $_GET['url'];
$decoded = urldecode($string);
$urlSplitted = explode('?i=', $decoded );
$i = $urlSplitted[1];
I have done this:
Just made form with post method to other file having meta refresh and echoed url in meta refresh value! Thats it! Meta refresh will not encode your url.

PHP include make the whole page appear? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Okay, my code is simple:
<?php include 'formvalidation.php';
echo $name; ?>
I want to make only the $name appear, but the whole 'formvalidation.php' shows up.
How can I fix that?
"I want that after I pressed the button, the function I had written will be excute to check the input, and then if the input is right, it'll redirect to another page, which can display the input."
If you wish to redirect after a form has been submitted and show a name afterwards, you will need to use sessions and a header.
Here is an example, (see comments in code) to be added inside formvalidation.php:
<?php
session_start();
// all other codes you already have
$name = "John"; // this is an example
// replace above with your POST variable
// such as $name = $_POST['name'];
$_SESSION['showname'] = $name;
header("Location: your_other_file.php");
exit; // keep this
N.B.: Make sure there is nothing else above <?php session_start(); such as your form, because this will throw a warning, stating Headers already sent...
your_other_file.php
<?php
session_start();
if(isset($_SESSION['showname'])){
$name = $_SESSION['showname'];
echo $name;
}
$name = "John"; // this is an example
Replace above in code with your POST variable.
Such as $name = $_POST['name']; as an example, since you have not provided additional code as to what your superglobal variable is for the name.
You can use session feature to call the variable instead of including a page, because it will indeed load an entire page. Please be more specific about your goal, perhaps we can help more by knowing more.
The whole HTML content of formvalidation.php will come up on the screen (so everything outside of <?php ?> just like all the outputs (echo etc ...) of the included file will come up on the screen.
You can avoid that by removing the outputs and only putting functions and variable declarations into the included file formvalidation.php.
The content of formvalidation.php could eg. be:
<?php
$name = 'test';
?>
It's going to execute whatever's in formvalidation.php. All the include function does is basically replace that line with the contents of your included file.
So if you don't want to show what's in that file - enclose the entire file in a function, or multiple functions. This is the way your library files (that you include) should be. Nothing in that file should be outside of a function definition.
Example (it's a crappy programming practice, but for example) -
formvalidation.php was ->
<?php
echo "hola";
if ($i = 5) {
echo 15;
}
?>
<form><input type="text" value= "10"/>
<?php
echo "macho, macho man.";
?>
Everything gets shown when I include it.
formvalidation.php now ->
<?php
function validate_form() {
echo "hola";
if ($i = 5) {
echo 15;
}
?>
<form><input type="text" value= "10"/>
<?php
echo "macho, macho man.";
}
?>
Now the way I've changed the file - nothing will get printed until I call validate_form();
Does that make sense?
When you use include 'someFile.php'; it's like you are taking all the contents of that file and pasting it in the code. For example if I had:
someFile.php
echo '<h1>Hello World</h1>';
echo '<p>I like pie</p>';
then:
include 'someFile.php';
echo $name;
Is the same as:
echo '<h1>Hello World</h1>';
echo '<p>I like pie</p>';
echo $name;
As others have said, that's what include does. I assume that you define $name inside the formvalidation.php file and that is why you are including it.
The right solution here would be to seperate the code in formvalidation.php into a function/class/file which does the data processing and another which creates the output. The you include/call only the first in the situation where you don't want the output
However, it is possible to capture the output and then discard it, using output buffering:
<?php
ob_start(); //Start capturing output
include 'formvalidation.php';
ob_end_clean(); // Stop capturing output and discard whatever was captured
echo $name;
?>
That said I would really not recommend this. The recommended way to fix this is to seperate your back-end code from your output generating code and only call what you actually need in any given situation.
Edit
An example of how to seperate the issues properly could be the following.
Lets assume your current formvalidation.php is something like:
<?php
$name = $_REQUEST['name'];
if( '' == $name ){ ?>
<p class="error">You must supply a name</p>
<form action="foo.php">
<input name="name" />
<button type="submit">Submit</button>
</form><?php
} else {
echo '<p>Form valid!</p>';
}
In a new file validator.php you could do:
<?php
class MyValidator{
public $name;
function read_data(){
$this->name = $_REQUEST['name'];
}
function validate(){
if( '' == $name ){ ?>
<p class="error">You must supply a name</p>
<form action="foo.php">
<input name="name" />
<button type="submit">Submit</button>
</form><?php
} else {
echo '<p>Form valid!</p>';
}
}
}
Then you change you formvalidtion.php to
<?php
require_once 'validator.php';
$val = new MyValidator();
$val->read_data();
$val->validate();
While the file you have above becomes
<?php
require_once 'validator.php';
$val = new MyValidator();
$val->read_data();
echo $val->name;

PHP | Captcha won't write to $_SESSION

i'm building a form + form validation class , and i also wanted to add captcha to this.
The captcha image is showing, however it itsn't storing anything in the $_SESSION.
I am using this captcha script:
https://github.com/gesf/captcha.class.php
Now in my controller i use this :
$data['regform']->addfield('user_captcha', 'Human verification', 'captcha', 'captcha' );
And that generates the following :
<label>
<span>Human verification</span>
<img name="user_captcha" src="http://www.websiteurl.com/dev/misc/captcha.php?c=1"><input type="text" name="user_captcha" value="" />
</label>
The image is showing like it should. However i'm not able to validate the input because it's not writing to the session. Now in the image file captcha.php it loads the class Captcha , and in this class constructor it tries to write to the session :
function Captcha($letter = '', $case = 5) {
$this->_capCase = $case;
if (empty($letter)) {
$this->StringGen();
} else {
$this->_capLength = strlen($letter);
$this->_capString = substr($letter, 0, $this->_capLength);
}
#session_start();
$_SESSION['asd'] = 'asd';
$_SESSION["CAPTCHA_HASH"] = sha1($this->_capString);
$this->SendHeader();
$this->MakeCaptcha();
}
My session always stays empty. But when i try the following :
<?php $_SESSION['bleh'] = 'asd'?>
<?php echo $form; ?>
It adds 'bleh' to the session like it should.
I really can't see why it won't write to the session..
could someone help me out ??
Thanks!!
Make sure, that session_start() is called before any output for every single page. As I can see, you are using # operator, that shuts up some errors. Can you remove it and tell us what does it output?
Also, your sessiaon_start() call is somewhere in the middle of the script. Perhaps there are some other output before that.

PHP quiz send data to next page

ok, i'm trying to do a quiz...all good by now. but when i'm trying to send the collected data(radio buttons values) through pages i can't get the logic flow. I have the main idea but i can;t put it into practice.
i want to collect all radio values
create an array containing this values
serialize the array
put the serialized array into a hidden input
the problem is that i want to send data on the same page via $_SERVER['PHP_SELF'] and i don;t know when in time to do those things.(cause on "first" page of the quiz i have nothing to receive, then on the "next" page i receive the S_POST['radio_names'] and just after the second page i can get that hidden input). i hope i made myself understood (it's hard even for me to understand what my question is :D )
You could try to use the $_SESSION object instead... For each page of your quiz, store up the results in the $_SESSION array. On the summary page, use this to show your results.
To accomplish this, on the beginning of each page, you could put something like:
<?
session_start();
foreach ($_POST as $name => $resp) {
$_SESSION['responses'][name] = $resp;
}
?>
Then, on the last page, you can loop through all results:
<?
session_start();
foreach ($_SESSION['responses'] as $name => $resp) {
// validate response ($resp) for input ($name)
}
?>
Name your form fields like this:
<input type="radio" name="quiz[page1][question1]" value="something"/>
...
<input type="hidden" name="quizdata" value="<?PHP serialize($quizdata); ?>"/>
Then when you process:
<?PHP
//if hidden field was passed, grab it.
if (! empty($_POST['quizdata'])){
$quizdata = unserialize($_POST['quizdata']);
}
// if $quizdata isn't an array, initialize it.
if (! is_array($quizdata)){
$quizdata = array();
}
// if there's new question data in post, merge it into quizdata
if (! empty($_POST)){
$quizdata = array_merge($quizdata,$_POST['quiz']);
}
//then output your html fields (as seen above)
As another approach, you could add a field to each "page" and track where you are. Then, in the handler at the top of the page, you would know what input is valid:
<?
if (isset($_POST['page'])) {
$last_page = $_POST['page'];
$current_page = $last_page + 1;
process_page_data($last_page);
} else {
$current_page = 1;
}
?>
... later on the page ...
<? display_page_data($current_page); ?>
<input type="hidden" name="page" value="<?= $current_page ?>" />
In this example, process_page_data($page) would handle reading all the input data necessary for the given page number and display_page_data($page) would show the user the valid questions for the given page number.
You could expand this further and create classes to represent pages, but this might give you an idea of where to start. Using this approach allows you to keep all the data handling in the same PHP script, and makes the data available to other functions in the same script.
You want to use a flow such as
if (isset $_POST){
//do the data processing and such
}
else {
/show entry form
}
That's the most straight forward way I know of to stay on the same page and accept for data.

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