Link value of form in PHP - php

I have an html file, basically a simple form: The purpose is to submit a value that runs a piece of code on a PHP file ('alternative.php') See sample of html code:
<form name="input" action="alternative.php" method="POST">
Area: <input type="text" name="area"><br><br>
<input type="submit"><br>
</form><br><br>
This runs smoothly
Now I have a second PHP file ('alternative2.php') and this file automatically needs to link to the data that is input in the form.
Excerpt of php code for alternative2:
<?php
require_once 'header.php';
/** Create HTTP POST */
$accomm = 'ACCOMM';
$region = '';
foreach ($result->area as $entry) {
$region = $entry->attributes()->area_name;
break;
}
$page = '10';
Both alternative.php and alternative2.php require header.php.
Excerpt of header.php:
<?php
/** Create HTTP POST */
$country = 'Australia';
$area = htmlspecialchars($_POST["area"]);
$seek = '<parameters>
<row><param>COUNTRY</param><value>'. $country .'</value></row>
<row><param>AREA</param><value>'. $area .'</value></row>
</parameters>';
Currently it returns "Notice: Undefined index: area in C:\xampp\htdocs...." when I run it.
How do I go about this?
Thanks

The error suggest that $_POST["area"] is not defined, if you don't reach alternative2 from your form, then that's why you see this; if you want to reach alternative2 from other place (for example directly), or if the value of a variable must be the same on several pages, then you may want to consider using Sessions.

Check if the $_POST values exist before using them...
if (isset($_POST["area"])){
//do stuff
}

Basically it has to do with which file your form actually submits to. If your form submits to only alternative.php then you aren't receiving the POST information to your second page. The easiest and logical choices in my opinion (based on what I see from your code) is to merge the functionality of alternative.php and alternative2.php into a single page, or use sessions to store the POST information which will then be available to both pages. If you were to use sessions you would be doing something like shown below.
Start with the file that handles your form input (alternative.php I presume) and add
session_start();
to the top of that file. Then, in whatever block of code you have getting your form information add the following line:
$_SESSION['area'] = $_POST['area'];
Now your information is stored and will be available from request to request.
Then in your head.php file, access the info via $_SESSION variables.
<?php
/** Start Session */
session_start();
/** Create HTTP POST */
$country = 'Australia';
$area = htmlspecialchars($_SESSION['area']); //Access your session variable.
$seek = '<parameters>
<row><param>COUNTRY</param><value>'. $country .'</value></row>
<row><param>AREA</param><value>'. $area .'</value></row>
</parameters>';
?>

Related

How to get a username in the url after the /?

I am using PHP to create a social media platform. I have a fully sizeable page for the user you are viewing that is adjusting by who you are trying to view in the URL. If you go to profile.php?user=(USERNAME) it will display the data of that user.
But I want something extra to that. I do not want my users to have to fill in a difficult URL like that. I want them to be able to type profile/(USERNAME) and that it will show the data of the user they are viewing.
So how can I make it possible that the GET from ?user=(USERNAME) is in the /(USERNAME).
I hope my question is clear. Looking forward to questions or answers.
Kind regards,
Serge
The following should work for you.
Set up an input field and set the value to /profile -> <input value="profile/">, (see below HTML code for example), so that auto populates in the field for the users to type into. Then run your post value through php and check if set, sanitize (see https://www.php.net/manual/en/function.urlencode.php for more info), then build your url, lastly run that through a header redirect to redirect to the profile page.
Example below:
HTML:
<form method="post"><!--// No action needed as we will redirect with php `header()` if submit is pushed. //-->
View Users Profile:
<input type="text" value="profile/" name="searchUser" id="searchUser" ><br><br>
<input type="submit" name="submit" value="Submit">
<?=$url?><!--// Used simply to echo out your url string for testing purposes, if you are testing, simply comment out the header line in the php so the code does not redirect you to the url //-->
</form>
PHP:
$url = null; // Declare an empty variable to display URL for testing purposes
// * Not needed if your not displaying this url to test the output of your url string
// Make sure the $_POST globals are set using isset()
if(isset($_POST['submit']) && isset($_POST['searchUser'])){
// Remove the `profile/` string from the input value so we only have the user being searched
$post = str_replace("profile/","",$_POST['searchUser']);
// More sanitation may be needed depending on what you allow your users to use for usernames
$cleanPost = filter_var ( $post, FILTER_SANITIZE_STRING);
// Get the server host
$host = $_SERVER['HTTP_HOST'];
// Get the directory
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
// Get the root
$root = 'myawesomesocialsite.com';
// Set the path to profile and add the field input from user
$profile = "/profile?user=".$cleanPost;
// Construct the URL using the declared variables
$url = "http://$host$uri/$root$profile";
// Redirect user using header()
// Comment the header("Location: $url"); out to test the output of your $url string if you're getting errors with redirect
header("Location: $url");
exit();
}
Using a function:
function constURL($root, $dir){
$post = str_replace("profile/","",$_POST['textInput']);
$cleanPost = filter_var ( $post, FILTER_SANITIZE_STRING);
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$urlPost = "?user=".$cleanPost;
$url = "http://$host$uri/$root$dir$urlPost";
header("Location: $url");
exit();
}
// USE FUNCTION
// Make sure you set the values for root and dir
if(isset($_POST['submit']) && isset($_POST['searchUser'])){
$root = 'myawesomesocialsite.com';
$dir = "/profile";
constURL($root, $dir);
}

How to stop url param manipulation

I have the following URL on a web application that I have created (currently running locally):
http://localhost:8080/trustsurvey/questionView.php?question=1
The question=1 is from a GET parameter that increments each time the user clicks on the Next button.
$questionNumber = $_GET['question'];
What would be the best recommended way to hide or encode the parameter in URL after the ? thus making it difficult for a user to manipulate the URL and manually change the parameter?
You could make use of session variables instead of URL parameters.
Something like this (not "complete" code, some isset checks are missing etc):
questionView.php
<?php
session_start();
$questionNumber = $_SESSION['questionNumber'] = $_SESSION['questionNumber'] ?? 1;
?>
<form method="post" action="answer.php">
<!-- Display question $questionNumber here -->
</form>
answer.php
<?php
session_start();
$questionNumber = $_SESSION['questionNumber'];
if (answerOk()) { // This checks answer with $_POST data
$_SESSION['questionNumber']++;
header('Location: questionView.php');
die;
}

Get the value of a variable in page1.php in page2.php

I have a question about how I can access the value from a variable from one page on another one.
I have a registration script and the registration form is on my homepage. I want to dynamically create a random name for every input field (change the value of the name attribute). The current name attribute for the input is just firstName, but I want it to be like firstName_345635. The 345635 is a randomly generated number and will change everytime the page refreshes.
Here is my random number variable:
$firstNameInputName = 'firstName_' . rand(10000, 50000);
The output becomes: firstName_[randomNumer].
The problem is, the register.php has all the post variables to get the form data. What I have now is this:
$firstName = $_POST["firstName"]);
I need to get the value from the random number variables from the homepage and instead of giving the $firstname variable the name firstName, it should get the name that the random number generating variable has produced on the homepage.
How can I achieve this?
You should use a session (or cookies) var to save this dynamic name.
Approach 1. Session (or cookies)
page1.php
<?php
session_start();
$customCode = rand(5, 15);
$_SESSION['customCode'] = $customCode; ?>
<form action="page2.php" method="post">
<input type="text" name="firstName_<?php echo $customCode; ?>" />
</form>
page2.php
<?php
session_start();
$customCode = $_SESSION['customCode']; ?>
$firstName = $_POST['firstName_'.$customCode];
Approach 2. You can put a input hidden field in your form like:
<input type="hidden" name="customCode" value="345635" />
And get it in second page like:
$firstName = $_POST['firstName_'.$_POST['customCode']];
Approach 3. You can iterate over your $_POST array to get firstName like:
foreach($_POST in $key => $value) {
if(strpos($key, "firstName")) {
$firstName = $value;
}
}
The solution is sessions, session variables are superglobal variables which means you can use them in different files as long as its the same session, to use them you need to start the session at every page you'll use them in, also, starting the session has to be done before any output is shown.
Ex (registeration page):
<?php
session_start();
/**
** HTML AND FORM HERE WHATEVER ELSE YOU NEED TO DISPLAY
**/
$_SESSION['FirstName'] = $firstNameInputName;
?>
Ex (processing page):
<?php
session_start();
echo $_POST[$_SESSION['FirstName']]; // Output: Whatever was entered inside the field
?>

passing variables between functions and files in php

I have a file called admin.php in which I have a button with the name send. What I want to do is when I click it, to make visible a link on the user's page, user.php. How can I do this?
I have a file with all my functions called functions.php in which I have a function called onSubmit($var); I initialize the variable $var is admin.php with the value $_POST['send'] but when I call the function in the file user.php I have no way of telling him who the variable $var is so I get 'undefined index'.
Is there another way to do this?
EDIT Added code
This is admin.php
<input type="button" name="send" value="Submit" /><br/>
require 'functions.php';
$posted = $_POST['send'];
onSubmit($posted);
This is user.php
require 'functions.php';
onSubmit($var); //here it says undefined index var because it doesn't know who the variable is
if($isSent == 1) {
<a style="visibility:visible;" href="test3.html" id="test3">Test3</a> <br/>
}
And this is functions.php
global $isSent;
function onSubmit($var) {
if(isset($var)) {
$isSent = 1;
}
}
Basically you need to use sessions like below:
if(isset($_SESSION['makeVisible']) && $_SESSION['makeVisible'] == true){
echo '<button>Button init</button>'; //you could also use html like the comment below.
}
/*
if(condition){?> <!-- this is now html --> <button>Button init</button><?}
*/
Then to set this variable on your admin page use:
if(isset($_POST['submitButton'])){
$_SESSION['makeVisible'] == true;
}
You'll also need a form for this method to work but there are other methods but I prefer this one.
<form name="buttonMakerThing" method="POST">
<input name="submitButton" value="Make button init Visible" type="submit"/>
</form>
Without an action the form defaults to 'POSTING' the form information to the current page. Making the condition if(isset($_POST)) return true.
You will need to add a $_SESSION declaration at the top of every php page you have on your site for this to work. It MUST go on the very first line of every page! for example:
01: | <?php session_start();
02: |//rest of script;
Please look more into $_SESSIONS for unnsetting/destroying your sessions and more uses for them :) http://php.net/manual/en/reserved.variables.session.php
Right I've done a bit of research on Caching and this is what I've come up with. It might not be 100% correct but it's a start as like I've said I've never tried it myself lol
In your admin.php I'd put this function in:
if(isset($_POST['send'])){
if($enabled == true){
$enabled == false;
}
else{
$enabled == true;
}
apc_add('enabled',$enabled);
}
Now to 'get' our $enabled var:
$enabled = apc_fetch('enabled');
Then to check the the var within your client page:
if($enabled == true){
echo ' button';
}
Now the only things I haven't fully looked at is the security of the apc_ function and the client usage. I believe it works for all clients of the server but I'm not 100% certain. Here the php manual to give better examples.
This is the method I was thinking of. But again I'm not sure on the security of it but I'm sure you can find something to keep it secure. The video is actually is tutorial for a Youtube API. But he does cover saving a variable to a cache text file which should be of use to you :)
If you have functions.php which defines functions, simply include it in admin.php file and then you can call the function from there and also pass value.

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.

Categories