Turning a form's GET into a PHP variable? - php

I'm trying to make the following form's GET function to be part of a predefined variable.
Any ideas? Thanks in advance!
Let me explain a little more of what I'm really trying to do. I currently run a website concentrating on the U.S. stock market. I've created an HTML form with a method=GET. This form is used like a search box to look up stock ticker symbols. With the GET method, it places the ticker symbol at the end of the URL, and I created a quotes.php page that captures this information and displays a stock chart based on what ticker symbol is keyed into the box. For the company names, I've created a page called company.php that declares all of the variables for the company names (which happens to be a $ followed by the ticker symbol). The file, company.php, is the only file included in quotes.php.
This is where this came in: ' . $$_GET["symbol"] . '
The above code changes the GET into the variable based on what was typed into the form. I've used "die" to display an error message if someone types something into the box that doesn't match a variable in the company.php page.
I've also added into the company.php page variables for each company that will display which stock exchange each stock is listed on. These variables begin with "$ex_". So, what I was trying to do was have the symbol keyed into the box appended to "$ex_" so that it would display the corresponding stock exchange.
My questions are:
Is there a way to have what is typed into the form added to "$ex_"?
Is this an insecure way to code something like this (can it be hacked)?
Thank you all!

Rather than prefixing your variables and using variable variables (that are potentially insecure especially with user input), try this:
$ex = array(
"foo" => "bar",
...
);
if( !isset($ex[$_GET['symbol']])) die("Error: That symbol doesn't exist!");
$chosen = $ex[$_GET['symbol']];

Here's another approach:
extract($_GET, EXTR_PREFIX_ALL, "ex");
Although it's better to use it like this just to make sure there is no security issues.
extract($_GET, EXTR_SKIP);

PHP's extract() does what exactly what you want, and you should specify "ex_" as the prefix you want.
However, there are security issues and unintended consequences to using such a function blindly, so read up on the additional paragraphs following the function parameters.

Will the below achieve what you need?
$myGetVariable = $_GET['symbol'];
$ex_{$myGetVariable} = "Something";

$_GET['symbol'] = 'APPL';
if (!empty($_GET)) {
foreach ($_GET as $k => $v) {
$var = 'ex_'.$k ;
$$var=$v;
}
}
var_dump($ex_symbol);
APPL

Related

Showing a href without needing to input text(Wordpress and html issue)

I'm on wordpress atm and I'm stuck with a small issue.
To save the people receiving the site some work I hoped i'd be able to make things as easy as possible.
So what I did was add a plugin called "advanced custom fields", and I made a custom field.
What I wanted was to have 1 custom field that'd show a link(as text) in the following way:
The issue
My issue is that I want the link(example) to show without needing to fill in "The issue", because in the backend(the wordpress cms) it's a lot of trouble for the person to fill in an extra sub field called name with the exact same value.
So my question is, is it possible to show a link without needing to fill in "The Issue" or is there a different html tag for this?
Thanks in advance!
You can check if the field "The Issue" is empty and only in this case reprint in this place the "example" field.
if (!empty(the_field('The issue'))) {
<?php the_field('The issue'); ?>
} else {
<?php the_field('example'); ?>
}
If you need to ensure that a link input from the user is external (that always begins with http://) you can do something like this (of course, before printing the $link variable in the href):
if (strpos($x, "http://") == 0) {
$link = $x;
} else {
$link = "http://" . $x;
}
strpos search the position of the first occurrence of a substring on your string ($x, for example). So if the position is 0 means that the string begins with "http://", so it is external, but if this is not the case you have to add it at the beggining of the string.
One have to note that user inputs are tricky (imagine that the user writes " http: //..." with a space before the url) so it is possible that one needs more validation than this, but I think that the idea is clear.

Get an id then put it into a href

I'm a bit new to this so sorry if this has been covered already but i'm going around in circles searching.
I've had a look around learn t how to edit htaccess and use the get function, I then even found a plugin called redirection that did similar.
What I would like to do is if I have a URL http://example.com/file.php?id=blue
is to grab the id which is "blue"
then in a href link dynamically add it to the end of another url
Link Example
If someone could help show me or point me in the right direction on how to get the id blue and add it into a href that would be great.
Many Thanks
You have to use $_GET. People might be dicks about it here - but I had a hard time when I was first learning to program too. You'll get it, don't worry.
This is how get works (at least, all you need to know about how it works):
if you have the file index.php
if you add a query string to the end of it like index.php?id=1
You can access id=1 by doing the following in your code:
$id = $_GET['id'];
Similarly if the query string contains the following index.php?id=1&page=5&par=3&club=putter&upnext=tigerwoods
On the left hand of the equal sign is the Key(id, page, par, club, upnext) and on the right side their value(1,5,3,putter,tigerwoods)
One thing to remember is that when retrieving numbers from the query string they will always be of the string type, so you cant do something like
if ( $_GET['page'] === 5 )
you'll have to do
if ( $_GET['page'] == 5 )
and to echo it into a link:
$club = $_GET['club'];
if ( $club == 'NRA' ) {
echo "Gun Show";
echo 'Buy tickets to my gunshow ^^';
}
Hope this helps!
You can also do things like set your website up so that it has one template and use the $_GET parameter to determine which files to include into the content sections of the site via a switch command. I do this, but not across my whole site. For my user control panel, I do this to simply include only the file necessary (change email, update password, delete account, update profile, etc)
Cah'piche?
Use the $_GET parameter.
YAY!!

pass a value from one page to another outside querystring and without javascript?

One solution to automatically building navigation for a site is by scanning a folder for documents like this:
foreach(glob('pages/*.pg.php') as $_SITE_NAV_filePath):
$_SITE_NAV_filePath = explode('.pg',pathinfo($_SITE_NAV_filePath,PATHINFO_FILENAME));
$_SITE_NAV_fileName = $_SITE_NAV_filePath[0];
$_SITE_NAV_qv = preg_replace('/([A-Z])/','-$1',$_SITE_NAV_fileName); $_SITE_NAV_qv = trim($_SITE_NAV_qv,'-');
$_SITE_NAV_name = preg_replace('/([A-Z])/',' $1',$_SITE_NAV_fileName);
?>
<li><?=$_SITE_NAV_name?></li>
<?php
endforeach;
This code will turn "AnAwesomePage.pg.php" into a menu item like this :
<li>An Awesome Page</li>
This might be bad practice (?).
Anyway; I don't use this method very often since most of the time the sites have a database, and with that comes better solutions...
But my question is this:
Is there a way to prefix the filename with a integer followed by and underscore (3_AnAwesomePage.pg.php), for sorting order purposes, and pass it somehow to the destination page outside of the querystring and without any async javascript?
I could just explode the filename once again on "_" to get the sort order and store it somewhere, somehow?
This is the code for handeling the page query request:
$_SITE_PAGE['qv'] = $_GET['page'];
if (empty($_SITE_PAGE['qv'])){ $_SITE_PAGE['qv'] = explode('-','Home'); }
else { $_SITE_PAGE['qv'] = explode('-',$_GET['page']); }
$_SITE_PAGE['file'] = 'pages/'.implode($_SITE_PAGE['qv']).'.pg.php';
This code turns "An-Awesome-Page" back into "AnAwesomePage.pg.php" so it's possible to include it with php.
But with a prefix, it's not so easy.
The probliem is; Now there's no way to know what prefix number there was before since it has been stripped away from the query string. So I need to send it somehow along in the "background".
One very bad solution I came up with was to transform the navigation link into a form button and just _POST the prefix interger along with the form. At fist it sounded like a nice solution, but then I realized that once a user refreshes their page, it didn't look very good. And after all, that's not what forms are for either...
Any good solutions out there?
Or some other and better way for dealing with this?
There are two ways to keep that number saved, you can use cookies or php session variables.
But in this case, if user first enter the url in the browser or in a new browser, then he should be taken to default number.
Like you have:
1_first-page.php
2_first-page.php
3_first-page.php
If user enter the url like: domain.com/?page=first-page, you have to take him to 1_first-page.php to any number which you want to be default.

Increase cohesion by reusing a PHP function for multiple RSS feeds

My homepage contains weather for three cities around the world as displayed in the image
In the home page I declare 3 variables storing the RSS URL for each city
$newYorkWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f';
$londonWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=UKXX0085&u=c';
$parisWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=FRXX0076&u=c';
I pull identical tags out of the three URL's displayed above and use 3 identical functions apart apart from the variable passed into it.
Below shows the variable being passed into the function. Obviously other functions are used before $weather can be returned.
function new_york_current_weather($newYorkWeatherSource) {
// Get XML data from source
if (isset($newYorkWeatherSource)) {
$feed = file_get_contents($newYorkWeatherSource);
} else {
echo 'Feed not found. Check URL';
}
checkWeatherFeedExists($feed);
$xml = new SimpleXmlElement($feed);
$weather = get_dateTime($xml);
$weather = get_temperature_and_convert($xml);
$weather = get_conditions($xml);
$weather = get_icon($xml);
return $weather;
}
As I mentioned, I current repeat this function 3 times just replacing the $newYorkWeatherSource variable that is passed in the above example. Any ideas how I could reuse this function 3 times but yet pass in different URL to keep my homepage showing weather from the 3 cities? Ofcourse, it's easy to reuse the function if each city was represented on individual pages but the purpose is to keep them together for comparison.
Any ideas?
Thanks in advance.
As I mentioned, I current repeat this function 3 times just replacing the $newYorkWeatherSource variable that is passed in the above example. Any ideas how I could reuse this function 3 times but yet pass in different URL to keep my homepage showing weather from the 3 cities?
Maybe I'm entirely missing the point of your question, but are you asking how to rename the function and variables? Because, if so, it's just a matter of search and replace on the first few lines of the function...
function get_current_weather($rss_url) {
// Get XML data from source
if (isset($rss_url)) {
$feed = file_get_contents($rss_url);
} else {
echo 'Feed not found. Check URL';
}
// ...
Simply replace the city-specific functions with one starting out like this, and call it three times, one time for each specific city RSS feed URL.
From the comments:
but I'm just wondering what I will do with the 3 RSS URL variables because I can't replace rename them all to $rss_url as I will just be overwriting them until eventually the only URL will be Paris
I believe you may be suffering from a misunderstanding about PHP variable scope. Let's take this snippet as an example:
function bark($dog) {
echo 'The dog says ', $dog, ".\n";
}
$cat = 'meow';
bark($cat);
This code will emit The dog says meow. When you call the bark function with a variable, PHP takes a copy of the data* and passes it into the function as the variable name specified in the function. You don't need to name the variable the same thing both inside and outside. In fact, you can't** even see variables defined outside of a function:
function i_see_you() {
echo 'The dog heard the cat say ', $cat, ".\n";
}
$cat = 'meow';
i_see_you();
This code will emit The dog heard the cat say ., as $cat is out of scope here.
Getting back to the problem at hand, we still have three weather URLs.
$newYorkWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f';
$londonWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=UKXX0085&u=c';
$parisWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=FRXX0076&u=c';
All you need to do in order to make things work is:
echo get_current_weather($newYorkWeatherSource);
echo get_current_weather($londonWeatherSource);
echo get_current_weather($parisWeatherSource);
Inside the function, the proper variable with the proper name will have the proper data, and the right thing will happen.
*: PHP uses something called "copy-on-write", which does what you think it might do. It's completely safe to pass around variables containing large data. It will not consume unexpected amounts of memory. There's no need to use references. In fact, forget I ever said anything about references, you don't need them right now.
**: It's possible to see variables from the global scope by using the global keyword. Globals are bad practice and lead to spaghetti code. You might want to read more about variable scope in PHP.

Multiple $_GET through links

I'm doing a website. There's a pagination, you click on links and they take you to the page you need, the links pass $_GET variable ( a href="?pn=2" ) and that works fine.
However when i add the category links (also contain $_GET variable
(a href="?sort=english") on the same page, which kind of sort the content on the page, and click it, the system simply overrides the url and deletes all the previous $_GET's.
For example, I'm on page 2 (http://website.com/index.php?pn=2)
and then I click this sorting link and what I'm expecting to get is this (http://website.com/index.php?pn=2&sort=english), but what I get is this:
(http://website.com/index.php?sort=english). It simply overrides the previous $_GET, instead of adding to it!
A relative URI consisting of just a query string will replace the entire existing query string. There is no way to write a URL that will add to an existing query. You have to write the complete query string that you want.
You can maintain the existing string by adding it explicitly:
href="?foo=<?php echo htmlspecialchars($_GET['foo']); ?>&bar=123"
Try using this:
$_SERVER['REQUEST_URI'];
On this link you can see examples. And on this link I have uploaded test document where you can try it yourself, it just prints out this line from above.
EDIT: Although this can help you get the current parameters in URL, I think it's not solution for you. Like Quentin said, you will have to write full link manually and maintain each parameter.
You could create a function that will iterate through your $_GET array and create a query string. Then all you would have to do is change your $_GET array and generate this query string.
Pseudocode (slash I don't really know PHP but here's a good example you should be able to follow):
function create_query_string($array) {
$kvps = array();
for ($key in $array) {
array_push($kvps, "$key=$array[$key]");
}
return "?" . implode("&", $kvps);
}
Usage:
$_GET["sort"] = "english";
$query_string = create_query_string($_GET);
You need to maintain the query parameters when you create the new links. The links on the page should be something like this:
Sort by English
The HTTP protocol is stateless -- it doesn't remember the past. You have to remind it of what the previous HTTP parameters were via PHP or other methods (cookies, etc). In your case, you need to remind it what the current page number is, as in the example above.

Categories