At the moment i'm calling the following via GET
$RimWidth = $_GET['RimWidth'];
$TyreWidth = $_GET['TyreWidth'];
$Aspect = $_GET['Aspect'];
$TyreDia = $_GET['TyreDia'];
$TyreMan = $_GET['TyreMan'];
However in my paginiation, after page 1 it looses the variables and doesn't work. I understand i need to store them in the session. How do i do this as i've seen a few way of doing it and can't get it to work and how do i place them onto the end of the pagination links which look like this
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
thanks
If you want to just repeat the $_GET values, you can make a function to do that:
//A function to get and repeat arguments in every link
function repeatvars(){
if(isset($_GET) && empty($_GET) == false){
$variables = "?";
$arraycount = count($_GET) - 1;
$count = 0;
foreach ($_GET as $var => $value){
if(empty($value) == true){
$variables .= $var;
}else{
$variables .= $var."=".$value;
}
if ($count !== $arraycount){
$variables .= "&";
}
$count++;
}
return $variables;
}}
//Example
echo 'Next Page (Link: nextpage.php'.repeatvars().')';
You need this at the top of your PHP pages if using sessions:
session_start();
Then, you should really do this for each one:
$RimWidth = isset($_GET['RimWidth']) ? trim(strip_tags($_GET['RimWidth'])) : null;
$_SESSION['RimWidth'] = $RimWidth;
// and so on
trim() and strip_tags() removes any unwanted white-space and removes any malicious script tags being sent to your page. Never trust any POST, GET or SESSION data. They can all be compromised by hackers. If RimWidth always returns an integer, then put (int) before, like this:
(int) $RimWidth = isset($_GET['RimWidth']).............
You shouldn't need to add the session variables to the end of your pagination links, they're session variables and will be available on the next page, or any other page.
To call them on another page, do this:
echo $_SESSION['RimWidth'];
Related
This question already has answers here:
PHP foreach overwrite all items with last item
(5 answers)
Closed last year.
Please see the test page here https://wintoweb.com/sandbox/question_3.php
I use $_SESSION to store results of DB searches but only the last value is stored in the session. Looks like the latter is emptied upon each search.
I've used session before on that server and had no problems. My code is probably faulty but I cannot figure it out. session_start is called at top of file.
<?php
if(isset($_GET['search'])){
} else if(isset($_GET['display_this'])){
$rets = getNames(); //The $rets will hold the value returned by your function getName().
if(!empty($rets)){
echo '</br><b>Your selections so far :</b></br></br>';
}
//But yet, only the last search is stored in the session (why?)
echo "Echo of session array : " . $_SESSION['author'] . "<br>";
}
function getNames(){
$rets = '';
if(isset($_GET['choices']) and !empty($_GET['choices'])){
foreach($_GET['choices'] as $selected){
$rets .= $selected . ' -- ';
// This should add every $rets to the session array. Right?
$_SESSION['author'] = $rets;
//session_write_close();
}
}
return $rets;
}
?>
I expect the session to retain all info from subsequent searches but only the last value is stored.
A couple of things. I'll explain within the code.
// make sure that the function is before it is called.
// computers execute code top to bottom, and so getNames wouldn't even exist yet
// so therefore your if statement (below) will always evaluate to false
function getNames($choices){
// use parameters instead of $_GET inside of a function
$rets = '';
if(isset($choices) && !empty($choices)){
foreach($choices as $selected){
$rets .= $selected . ' -- ';
// you need to append using '.=' not '=' otherwise all the data will be overwritten
$_SESSION["author"] .= $rets;
}
}
return $rets;
}
// you shouldn't be checking if something isset and then doing nothing about it
// you might as well just be checking if it isn't.
if(!isset($_GET["search"]) && isset($_GET['display_this'])){
$rets = getNames($_GET["choices"]);
if(!empty($rets)){
echo '</br><b>Your selections so far :</b></br></br>';
}
echo "Echo of session array : " . $_SESSION['author'] . "<br>";
}
// you need to move this to the end of your script, otherwise the session will be closed
// before the second iteration of your loop begins and you won't be able to change values
// or access them later on (like in the above if statement)
session_write_close();
You are overwriting your Session array everytime with new value. You need to append to it, just like you are appending to $rets variable.
$_SESSION['author'] .= $rets;
I have read many things around the use of isset() and empty, but am not able to find the answer I am looking for.
Basically this: A user fills in some html inputs on post, which calls a php script. Prior to calling a separate web service to look up an address, I need to create a string with all of the address elements that have been populated. Where an input field has not been populated I want to exclude it from the list.
In short:
Check posted $vars 1 to 10 to see if they contain a value.
For each one that has no value, remove it from the string. Where a value is present, add it to the string.
I have tried using empty, !empty, isset and still haven't worked it out.
Sample code:
<?php
if
(empty($Lot_no))
{ $Lot_no = $v1;
}
if (empty($Flat_unit_no))
{$Flat_unit_no = $v2;
}
$str= $v1. $v2;
?>
Do something like
$address = '';
foreach ($_POST as $post) {
if (!empty($post)) {
$address .= $post . ', ';
}
}
Here is another similar question that is similar.
Why check both isset() and !empty()
If you want to add it to an array do something like this (I'm not sure on your form input names but as an example with form input names of street, city, state
$address = [];
$addressKeys = ['street', 'city', 'state'];
foreach ($_POST as $key => $post) {
if (in_array($key, $addressKeys)) {
$address[$key] = $post;
}
}
I didn't test this but it looks fine.
Try this one. You can check the value if it is equals to 0 or not.
<?php
if((empty($Lot_no)) && ($Lot_no =='0')){
$Lot_no = $v1;
}if ((empty($Flat_unit_no)) && ($Lot_no =='0')){
$Flat_unit_no = $v2;
}
$str= $v1. $v2;
?>
I'm trying to redirect users based on the query string on a php file. I created a php file go.php and pasted following code,
<?php
if ($v = 'AAAAA') {$link = 'https://example1.com/';}
if ($v = 'BBBBB') {$link = 'https://exapmle2.com/';}
header( 'Location: $link' ) ;
exit();
?>
I thought I will be able to redirect user to example1.com with mydomain.com/go.php?v=AAAAA
But it's not working. The script redirects user to mydomain.com/$link
Can anyone help me achieve this? I'm using nginx as webserver with php 7.
Thanks in advance.
You should do something like this
$v = $_GET['V'];
if ($v == 'AAAAA'){
$link = 'https://example1.com/';
}elseif ($v == 'BBBBB') {
$link = 'https://exapmle2.com/';
}else{
$link = false; //you could output an error or put a default redirect in here instead. Then you wouldn't need the second if condition ( with a default redirection )
}
if( $link ){
header( "Location: $link" ) ;
exit();
}
A few things to note:
You are using assignment = not comparison == in your if condition. In the original both conditions will pass with the end value of $link being the last one ( although its set in the first, the second replace it ), the $v variable will be set to equal BBBBB as well, nither of which is what you want.
Variable interpolation ( automatic inserting the value ) only works when using double quotes not single quotes. " $link " vs ' $link ' the first will fill in the value of $link the second will literally be $link as a string.
You have no default value if $v is not equal to either condition, what happens?
You should use an if elseif because $v cannot be equal to both. In the case it equals the first condition the rest are skipped, performance wise its better but something like that it dosn't matter so much, it's just best practice and more readable.
When you want to user variable inside header function please use double quotes
header("Location: $link") ;
Also make sure that you are getting the value of url parameter using $v = $_GET['v'];
I have a problem with $_GET array. On my page a value comes from URL like this.
http://localhost/search.php?subject=Mathematics
I check this $_GET value something like this..
// Check for a valid keyword from search input:
if ( (isset($_GET['subject'])) && (is_string ($_GET['subject'])) ) { // From SESSION
foreach ( $_GET AS $key => $subject) {
$searchKey = $key;
$searchKeyword = '%'.$subject.'%';
}
} else { // No valid keyword, kill the script.
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
Now its working for me. But my problem is I am using another two variables to pass through URL on same page to filter my database values.
echo '<li>Tutor</li>
<li>Institute</li>';
This two links I used to filter my database values (clicking on this link).
$tutor = isset($_GET['institute']) ? '0' : '1';
$institute = isset($_GET['tutor']) ? '0' : '1';
My problem is when I am trying filter database result clicking on the above link its always going this code instead of displaying filtered result.
} else { // No valid keyword, kill the script.
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
Can anybody tell me how I use this 3 $_GET values.
Why not just add a clause in the else:
elseif(!isset($_GET['institute']) && !isset($_GET['tutor']))
{
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
You need to make sure the url looks like this:
http://localhost/search.php?subject=Mathematics&tutor=tutorName&institute=instituteName
A ? denotes the beginning of the URL parameters, an & marks the separation between url parameters
Your problem doesn't seem to be, that you're running into the else loop (or better said: not the only problem). It looks like your first parameter gets lost with the second link. I think, the second link should react like some kind of extended search filter, that shoud be applied to the recently displayed content, or am I totally wrong at understanding you?
Perhaps this could solve your problem for creating the follow-up URLs.
$params = array();
foreach($_GET as $key => $value) {
$params[] = '&'.$key.'='.$value;
}
$url1 = '?tutor=link'.implode('', $params);
$url2 = '?institute=link'.implode('', $params);
And when you output the links:
echo '<li>Tutor</li>
<li>Institute</li>';
Your problem is that you are only checking the $_GET['subject'] variable, which is no being passed in. You could do this in a few ways, all resulting in changing:
if ( (isset($_GET['subject'])) && (is_string ($_GET['subject'])) ) { // From SESSION
1) include all variables in the conditional string:
if ( ((isset($_GET['subject'])) && (is_string ($_GET['subject']))) || ((isset($_GET['institute'])) && (is_string ($_GET['institute']))) || ((isset($_GET['tutor'])) && (is_string ($_GET['tutor']))) ) {
2) Pass in searchKey=1 or something in all your links and use:
if ( isset($_GET['searchKey']) ) { // From SESSION
Revised links:
echo '<li>Tutor</li>
<li>Institute</li>';
If you are looking to pass in more than one variable at once, you will need to put the search keys into an array.
I want to look through my PHP $_POST variables and change anything that is "undefined" (because of how jQuery is sending it) to "" or at least " " so that when the email form is submitted it doesn't say "undefined" wherever the value wasn't filled out (optional fields).
Thanks!
I recommend you consider altering your javascript to handle the undefines better, BUT..
Here is a no loops approach to do it:
$_POST = unserialize(str_replace('s:9:"undefined";', 's:0:"";', serialize($_POST)));
There is also the more typical approach of using a single loop like so:
foreach($_POST as &$p) if($p=='undefined') $p = '';
Note: The serialize + unserialize approach is cool in that is does not use a loop, but the loop approach is probably slightly faster, especially when $_POST is large.
In PHP if you use an & symbol in an foreach loop it will use it as a reference instead of a value. Changing a reference will set the original value.
<?php
$_POST['text1'] = 'undefined';
$_POST['text2'] = 'undefined';
foreach($_POST as &$var)
{
if($var == 'undefined')
$var = '';
}
print_r($_POST);
?>
<!-- Will output -->
array(
text1=>
text2=>
)
if (isset($_POST['var'])) {
// it is set
} else {
// it isnt set
}
foreach ($_POST as &$var) {
if ($var === 'undefined') {
$var = '';
}
}