I have a number of url's with different query strings such as
view.php?id=5
view.php?id=6
view.php?id=7
on another php page Im using file_get_contents as below:
$page = file_get_contents('view.php?id=5');
$file = 'temp/form.html';
file_put_contents($page, $file);
This of course only writes the first id '5', so how can i retrieve the 'id' variable on this page and write it in my file_get_contents line so I dont have to write out all the id's in seperate lines
thanks
rifki
If I understand correctly, in the situation you demonstrate you could use a for loop or something like that. But that only works if the IDs are numeric and follow each other up.
Example:
for($i = 5; $i <=7; $i++) {
$page = file_get_contents('view.php?id='.$i);
$file = 'temp/form.html';
file_put_contents($page, $file);
}
Updated:
If your ID comes from database you could select all IDs and loop through that.
Eg.
$sql = 'SELECT id FROM tablename;';
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
$page = file_get_contents('view.php?id='.$row['id']);
$file = 'temp/form.html';
file_put_contents($page, $file);
}
If those urls are used to browse some pages you can use the $_GET array (Official PHP Manual for the $_GET method).
It simply gets the value of a variable passed via the get method (i.e. page.php?var1=1&var2=2) so, if you need to get the id value for your page the code should be something like this:
$id = $_GET['id'];
$request = 'view.php?id='.$id;
$page = file_get_contents($request);
$file = 'temp/form.html';
file_put_contents($page, $file);
The first line gets the id passed via url, then the second creates the request string to pass to your file_get_contents function, then the other are like your code.
This is the case if you request the data from inside of such pages, if, for example, you know all of the pages needed then you can use a for clause to solve this problem.
One of the solutions might be:
$first_page = 5;
$last_page = 7;
for ($i = $first_page; $i <= $last_page; $i++) {
$request = 'view.php?id='.$i;
$page = file_get_contents($request);
$file = 'temp/form.html';
file_put_contents($page, $file);
}
With this you simply set the first and the last page you want to request, then you use these values to cycle through the pages and then call your function to do your... "stuff" :D
This is a good approach because then you can set in runtime the values for the for statement so you won't have to change that file every time.
However I think that using an identification different from Integers for your pages would be better, like id=home, or something like that.
If you get the id in your query string I mean url, you should write something like this:
$page = file_get_contents('view.php?id='.$_GET['id']);
$file = 'temp/form_'.$_GET['id'].'.html';
file_put_contents($page, $file);
To retrive the variable from a query string use
$_GET['variable_name']
By default, whenever you make a request to the server it is GET method which is called unless you explicitly specify that the form method to be POST.
//variable_name is the name of the variable in the query string
Related
I'm working on a project, and it has a bunch of variables for some links that I define. But I want to add a string at the end of those variable only if I got some GET parameters. The thing is I don't want to have another huge amount of variables and I want to have the same name for the variables. After some research, I came with this operator .= which is perfect for me. I also made a for loop it works well for the variable value, but I don't have the same name.
Here is what I got:
$homeLink = $wURL.'government/'.$job.'/';
$databaseLink = $wURL.'government/'.$job.'/search/database';
$overviewLink = $wURL.'government/'.$job.'/overview';
// Other variables
if (!isset($_SESSION['steamid']) && isset($_GET['uID']) && isset($_GET['uToken'])) {
// redefine the variables like this:
$homeLink .= '?uID='.$userinfoVlife['id'].'&uToken='.$userinfoVlife['websiteMDP'];
/*
OUTPUT: $wURL.'government/'.$job.'/'.'?uID='.$userinfoVlife['id'].'&uToken='.$userinfoVlife['websiteMDP']
*/
// The for loop:
$arr = array($homeLink,$databaseLink,$overviewLink);
$nb = count($arr);
for ($i=0; $i < $nb ; $i++) {
$arr[$i] .= '?uID='.$userinfoVlife['id'].'&uToken='.$userinfoVlife['websiteMDP'];
echo $arr[$i]."<br>";
// have the same output that above but I have to call my variables with $arr[<a number>];
}
}
The thing is I don't want to have another huge amount of variables and I want to have the same name for the variables, any ideas on how I can proceed?
First, your 2 last links are actually both based on the first one, $homeLink:
$homeLink = $wURL.'government/'.$job.'/';
$databaseLink = $homeLink.'search/database';
$overviewLink = $homeLink.'overview';
then why not build the parameter string and then append it?
$homeLink = $wURL.'government/'.$job.'/'
$paramString = '';
if (!isset($_SESSION['steamid']) && isset($_GET['uID']) && isset($_GET['uToken'])) {
$paramString = '?uID='.$userinfoVlife['id'].'&uToken='.$userinfoVlife['websiteMDP'];
}
$databaseLink = $homeLink.'search/database'.$paramString;
$overviewLink = $homeLink.'overview'.$paramString;
$homeLink .= $paramString;
I don't get why you want to store your URLs in an array, these are different URLs, thus to be used in different contexts, having all of them in one array is of course possible but doesn't bring any value, in my opinion.
To conclude, if $userinfoVlife['websiteMDP'] contains a readable password, you definitely have a problem in your application architecture: it's very bad practice to handle raw passwords and it's even worse to pass it in the URL.
i have the need to break down a REQUEST_URI to perform a few functions for each string between the slashes
the request that is passed from the url looks something like the below url however i cannot assign them static variables as the url could get longer or shorter per different pages
https://www.domain.com/accounts/customers/details
what im looking to do is capture the "accounts/customers/details" section which i have done by this variable on the page
$requested_url = $_SERVER['REQUEST_URI']; // this outputs /accounts/customers/details
i wish to create a for loop extracting the information from between the brackets and displaying it on page like
accounts
customers
details
how can this be achieved
try this
$requested_url = $_SERVER['REQUEST_URI'];
$seperate = explode("/",$requested_url); //this will explode in to array with "/" seperator
foreach($seperate as $seprt) {
echo $seprt."<br/>"; //it echo's each array variable seperately
}
$requested_url = $_SERVER['REQUEST_URI'];
$seperate = explode("/",$requested_url);
$count = 0;
foreach($seperate as $seprt) {
$count++;
if($count == count($seperate)){
echo $seprt;
}
}
I am writing some code to create fields automatically, which will save me a load of time. I have got most of my code working, but I have came across one error with the code, which is preventing me from achieving my final goal.
The code is as follows:
while ($i <= $numFields) {
$type = "\$field{$i}_Data['type']";
$name = "\$field{$i}_Data['name']";
$placeholder = "\$field{$i}_Data['placeholder']";
$value = "\$field{$i}_Data['value']";
echo '<input type="'.$type.'" name="'.$name.'" placeholder="'.$placeholder.'" value="'.$value.'">';
$i++;
}
The $numFields variable is defined at the top of my script, and I have worked out that it is something to do with how I am setting the variables $type, $name etc.
The end result is to create inputs depending on properties set in variables at the top of the script, The only issue I am having is with the settings of the variables, as said above.
If any extra code/information is needed, feel free to ask.
Thank you.
NOTE - There is no physical PHP error, it's purely an error with this:
"\$field{$i}_Data['value']";
There are a few ways we could write this one out, but they are all extensions of variable expansion and/or variable-variables.
Basically, we just need to put the variable name in a string and then use that string as the variable (much like you're currently doing with $i inside the string):
$type = ${"field{$i}_Data"}['type'];
$name = ${"field{$i}_Data"}['name'];
// ...
However, if you don't mind an extra variable, this can be written more cleanly by saving it like so:
$data = ${"field{$i}_Data"};
$type = $data['type'];
$name = $data['name'];
// ...
I've got string based on current url, look like this:
domain.com/katalog_firm,p11.html?typ=lista&fraza=&search_group=1&search_type=1&kategoria=1&podkategoria=0&wojewodztwo=0&miejscowosc=0&page=1&limit=10
I want to do a pagination. How to replace in this strng page=x, and limit is choosen from dropdown so also limit=x
So I want to change exxample from above to
domain.com/katalog_firm,p11.html?typ=lista&fraza=&search_group=1&search_type=1&kategoria=1&podkategoria=0&wojewodztwo=0&miejscowosc=0&page=2&limit=25
I just want to make replacement from (page and limit)
domain.com/katalog_firm,p11.html?typ=lista&fraza=&search_group=1&search_type=1&kategoria=1&podkategoria=0&wojewodztwo=0&miejscowosc=0&page=1&limit=10
to
domain.com/katalog_firm,p11.html?typ=lista&fraza=&search_group=1&search_type=1&kategoria=1&podkategoria=0&wojewodztwo=0&miejscowosc=0&page=2&limit=25
where page will be variable from loop, and limit will be constant
You can break the string into an array then modify the required values and again create the string.
<?php
$url = "domain.com/katalog_firm,p11.html?typ=lista&fraza=&search_group=1&search_type=1&kategoria=1&podkategoria=0&wojewodztwo=0&miejscowosc=0&page=1&limit=10";
$params = explode("?",$url,2);
parse_str($params[1], $url_array);
$url_array['page'] = 2;
$url_array['limit'] = 5;
$newparams = http_build_query($url_array);
$newurl = $params[0]."?".$newparams;
?>
EDITED
I'm trying to setup a random link at the bottom of all my pages. I'm using the code below, but want to make it so the current page is not included in the random rotation of links.
Example:
I need code to randomly select and display ONE of these links. The exception being, IF article1.php is currently being viewed, I want it to be excluded from the random selection. That way only links to OTHER articles are seen on any given article.
http://mysite.com/article1.php
http://mysite.com/article2.php
http://mysite.com/article3.php
I would use array_rand with something like:
<?php
$links = array(array('url' => 'http://google.com', 'name'=>'google'),
array('url' => 'http://hotmail.com', 'name' => 'hotmail'),
array('url' => 'http://hawkee.com', 'name' => 'Hawkee'));
$num = array_rand($links);
$item = $links[$num];
printf('%s', $item['url'], $item['name'], $item['name']);
?>
Where links makes it easier to build an array. Nevertheless, I think we miss some details about how you grab your links.
What is the mean of "current page"? because the simplest way to do, is just not add the page to the array.
And the use of array_rand avoids confusion with size of array and so.
Edit: I suppose you use a database, so you may have an sql request like:
SELECT myfieldset FROM `articles` WHERE id = 'theid';
So you know the id of the current article. Now you just have to build an array with some other articles with a query like:
SELECT id FROM `articles` WHERE id NOT IN ('theid') ORDER BY RAND LIMIT 5
And build the candidate array with those results.
Each time you randomly choose a URL to display, pop it off of the array and store it in a temporary variable. Then, on the next rotation make your selection and THEN push the previously used URL back into the array.
$lastUrl = trim(file_get_contents('last_url.txt'));
while($lastUrl == ($randUrl = $urls[rand(0, count($urls) - 1)])){}
file_put_contents('last_url.txt', $randUrl);
// ...
echo $randUrl;
Ensures that on each page load, you will not receive the previous URL. This, however is just an example. You would want to incorporate file locking, exception handling (perhaps) or an entirely different storage medium (DB, etc.)
To ensure the URL is not the same as the current, this should do the trick:
// get current URL
$currentUrl = 'http://' . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
// randomize URLs until you get one that doesn't match the current
while($currentUrl == ($randUrl = $urls[rand(0, count($urls) - 1)])){ }
echo $randUrl;
Google "PHP get current URL", and you'll get considerably more detailed ways to capture the current URL. For example, conditions on whether or not you're use HTTPS, to append an 's' to the protocol component.
try the codes below :
$links = array(
'http://mysite.com/article1.php',
'http://mysite.com/article2.php',
'http://mysite.com/article3.php',
'http://mysite.com/article4.php',
'http://mysite.com/article5.php'
);
$currentPage = basename($_SERVER['SCRIPT_NAME']);
$count = 0;
$currentIndex = NULL;
foreach($links as $link) {
if(strpos($link, "/".$currentPage)>-1) $currentIndex = $count;
$count++;
}
if($currentIndex) {
do{
$random = mt_rand(0, sizeof($links) - 1);
} while($random==$currentIndex);
} else {
$random = mt_rand(0, sizeof($links) - 1);
}
$random_link = $links[$random];