html & php question (get command) - php

Want to include another value in my urls
so far I have
# valid pages
$page = array('splash', 'portraits', 'weddings', 'studio', 'about', 'mobile', 'personal');
# validate GET, default to splash if not provided
$_GET['q'] = (isset($_GET['q'])) ? strtolower(trim($_GET['q'])) : 'splash';
if (!in_array($_GET['q'], $page))
$_GET['q'] = 'splash';
require_once "{$_GET['q']}.html";
but I want to include sections into my site so I need an extra value (ie. ?q=portraits?z=studio )
I assume I could probably just duplicate the $get command and replace q with z... but suppose I don't want the second value to be necessary (so the default pages will display without extra commands) and i want it to target a div or frame within the page? Not sure if I can even target divs.

Just use a default value:
if (isset($_GET['z'])) {
$z = $_GET['z'];
}
else {
$z = NULL; // or 'default' or whatever you want.
}
You can in short write the above in one line:
$z = isset($_GET['z']) ? $_GET['z'] : NULL;
I am not sure what you mean with "target a div", but if you mean an anchor, you can do that via identifiers (id).
Call your PHP script via index.php?q=splash#text and in your splash.html file you somewhere have <div id="splash">. The browser should scroll there.

Related

transfer variable betweet two php page

i have 3 page the first is html where i use then i send the data to the second page (php) with post where i have some condition, then i will send the data again for the third php page where i will put it in table (html)
my probleme is the data don't send to the third php page
the 2nd page
if(isset($_POST['matier']) and isset($_POST['semaine']))
{
$matier = $_POST['matier'] ;
$semain = $_POST['semaine'] ;
header('Location:EmploiMetierSemaine.php?'.$matier.' & '.$semaine);
}
the third page
<?php
$matier = $_GET['m'] ;
$semaine = $_GET['s'] ;
?>
any help please
You are not passing the params as parameters again but only values here:
header('Location:EmploiMetierSemaine.php?'.$matier.' & '.$semaine);
If you want to pass them as m and s you have to tell your location header so:
header('Location:EmploiMetierSemaine.php?m='.$matier.'&s='.$semaine);
Note that I also removed the spaces around the & since they don't make any sense in the URL.
in second page url should be like this EmploiMetierSemaine.php?m=matier&s=semaine
if(isset($_POST['matier']) and isset($_POST['semaine']))
{
$matier = $_POST['matier'] ;
$semaine = $_POST['semaine'] ;
header('Location:EmploiMetierSemaine.php?m='.$matier.'&s='.$semaine);
}
Nowdays If in same case you need to pass a values to multiple pages consecutive with redirection, maybe it's better to review and redesign your program. in other word it's like you are doing something in wrong way.
However, your 2th page must be somthing like this:
$matier = $_POST['matier'] ?? NUll;
$semain = $_POST['semaine'] ?? NUll;
header('Location:EmploiMetierSemaine.php?m='.$matier.'&s'.$semaine);
And use $_GET on 3th page.

random(non- repeating) file generator on click of button in php

i want to display 5 php files content randomly but non repeating when clicked a button [NEXT] using php/javascript (that works in php desktop as well).
the code i used did displayed random web page on page load but i did came across repeated web page
this is the code i used for index.php file:
<?php
$RandomList = array();
$RandomList[] = "/review/review-a1.php";
$RandomList[] = "/review/review-a2.php";
$RandomList[] = "/review/review-a3.php";
$RandomList[] = "/review/review-a4.php";
readfile($_SERVER['DOCUMENT_ROOT'].$RandomList[rand(0,count($RandomList)-1)]);
?>
please suggest how to get non repeated files .
Just save paths you already used in the session:
//Read visited paths from session or create a new list.
//?? works only in PHP7+. Use isset()?: instead of ?? for previous versions
$visitedPaths = $_SESSION['visitedPaths'] ?? [];
//Your list, just slightly changed syntax. Same thing
$randomList = [
"/review/review-a1.php",
"/review/review-a2.php",
"/review/review-a3.php",
"/review/review-a4.php"
];
//Remove all paths that were already visited from the randomList
$randomList = array_diff($randomList, $visitedPaths);
//You need to check now if there are paths left
if (!empty($randomList)) {
//The user did not load all files, so we can show him the next one
//Use array_rand() rather than $array[rand(0, count($array) -1)]
$randomPath = $randomList[array_rand($randomList)];
readfile($_SERVER['DOCUMENT_ROOT'] . $randomPath);
//Now we need to save, that the user loaded this file
$visitedPaths[] = $randomPath;
//And we need to save the new list in the session
$_SESSION['visitedPaths'] = $visitedPaths;
} else {
//TODO: Add some logic in case all paths have been visited
}

How to pass multiple variables in a URL and have each one replaced by a default value if not supplied

In need of a little PHP help here.
The following PHP code works perfectly to pass an affiliate ID on a given website where the user adds their affiliate ID to the end of the URL, otherwise the default is used (I have been using this successfully).
Example:
www.example.com (uses 'defaultid' from the PHP code)
www.example.com/?id=test1 (uses the affiliate ID 'test1' supplied by
the user)
<?php
/* DEFAULT SETTINGS */
$DEFAULT_ID = "defaultid";
/* Function to display ID value */
function displayID($defaultValue) {
global $_GET, $DEFAULT_ID;
if (isset($_GET['id']) and strlen(trim($_GET['id']))) {
echo $_GET['id'];
} else if (strlen(trim($defaultValue))) {
echo $defaultValue1;
} else {
echo $DEFAULT_ID;
}
}
/* End of function to display ID value */
?>
What I'd like to know is how to modify above code to work for 3 different affiliate IDs where there are 3 hyperlinks on a given web page for 3 different affiliate offers.
Example:
www.example.com (uses 3 default IDs that I've defined in the code)
www.example.com/?id1=test1 (uses default IDs 'defaultid2' and
'defaultid3') www.example.com/?id1=test1&id2=test2 (uses just the
default ID 'defaultid3')
www.example.com/?id1=test1&id2=test2&id3=test3 (uses the 3 IDs
supplied in the URL by the affiliate)
Please note I am not PHP savvy, so a modification of the above code would be preferred (if possible), rather than a complete rewrite that I may not understand.
Well, to have a default value you can add this to your code:
$id1="test1";
$id2="test2";
$id3="test3";
if (isset($_GET['id1']) && strlen(trim($_GET['id1'])))
$id1=$_GET['id1'];
if (isset($_GET['id2']) && strlen(trim($_GET['id2'])))
$id2=$_GET['id2'];
if (isset($_GET['id3']) && strlen(trim($_GET['id3'])))
$id3=$_GET['id3'];
How this code works: You have three variables, one for each ID.
The conditional will verify if there is anything in the $_GET array with the name for this id. If there is, it will overwrite the previous value, and if not, the default value will remain in there.
Also, if you're a fan of ternary, this does the same and looks prettier:
$id1= (isset($_GET['id1']) && strlen(trim($_GET['id1']))) ? $_GET['id1'] : "test1";
$id2= (isset($_GET['id2']) && strlen(trim($_GET['id2']))) ? $_GET['id2'] : "test2";
$id3= (isset($_GET['id3']) && strlen(trim($_GET['id3']))) ? $_GET['id3'] : "test3";

Display pages on index?action=

I would like to open a page using index.php?do=settings,
I'm using following code:
$do='';
if (isset($_GET['do'])){
$do = strip_tags($_GET['action']);
}
if ($do == 'settings') {
header("location:settings.php");
}
if ($do == 'posts') {
header("location:posts.php");
}
but the problem is that I have manually add all menu in actions like above to make it work and when it redirects me, the index.php?do=settings disappears and just show me settings.php which I do not want
To avoid having to set it manually you can store the pages in an array with the keys as the page name and the value as the file and then include the file:
$pages = array(
'settings' => 'settings.php',
'otherpage' => 'somePage.php'
);
if (isset($pages[$do])) {
include $pages[$do];
}
You should include the file as the reason the URL changes is because of the redirect.
add the get var back in like so
header("location: http://yoursite.com/settings.php?do=".$do);
NB: that should be the full uri not a relative one
You can use http_build_query($_GET) to generate the query string for links that need to conserve GET data.
If you need to modify a GET key, save GET to a temp array, modify that and pass it to http_build_query.

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