Grab number from URL and use it as variable in PHP - php

I'm working from a Wordpress website, and I need to be able to create a template for a real quick-and-simple custom order page.
The plan is to create pages so that the URL of said page will be http://www.website.com/order-1234
And then, the template being used for that page will have PHP in it that will try and grab the "1234" portion of the URL, and use it as a variable.
$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$order_id = intval(substr($url, strrpos($url, '/order-') + 4));
echo $order_id;
But the above code is returning a zero "0"

try by using
www.website.com/order?id=1234
and use
$getid = $_GET['id']
also when you want to use the get to show the page use the request function
if ($_REQUEST['id'] == $getid) {
// do something here
}
something like that :)

Related

Make a $_GET into variable or place into URL

How do you place a $_GET['****']; into a string or make it into a variable.
For Example i have this url:
http://localhost/PhpProject2/product_page.php?rest_id=3/area=Enfield.
I want to get the area and rest_id from the url. in order to redirect another page to this exact page.
echo"<script>window.open('product_page.php?rest_id= 'put get here'/area='put get here'','_self')</script>";
I have so far done this:
if(isset($_GET['rest_id'])){
if(isset($_GET['rest_city'])){
$_GET['rest_id'] = $rest_id;
}
}
This obviously does not work, so my question is how do i make the 2 $_GET into a variable or call the $_GET into the re-direct string.
What i have tired so far
echo"<script>window.open('product_page.php?rest_id=' . $GET['rest_id'] . '/area='put get here'','_self')</script>";
How or what is the best practice?
ok, first things first. in your URL you have to separate the parameters using an ampersand "&", like this
http://localhost/PhpProject2/product_page.php?rest_id=3&area=Enfield
Also, you have to assign the $_GET value to a variable, not the other way around, like this
$rest_id = $_GET['rest_id'];
so if you create a PHP file named product_page.php and use the url i gave you, and your PHP code looks like this, it should work..
<?php
if (isset($_GET['rest_id'])){
$rest_id = $_GET['rest_id'];
}
if (isset($_GET['rest_id'])){
$area = $_GET['area'];
}
$url = 'other_page.php?rest_id=' . $rest_id . '&area=' . $area;
header("Location: $url");
?>
The question here is why do you want to redirect from this page to the other, and not send the parameters directly to the "other_page.php"????

Redirecting to affiliate links based on words

I am working on PHP code for automatically redirecting a URL to an affiliate URL based on words in the URL.
This is the code I am using:
if (stripos($mylink, "amazon.in") > 0) {
if (strpos($mylink, "?") > 0) {
$tmp = $mylink."&affiliate_id";
} else {
$tmp = $mylink."?affiliate_id";
}
$loc = "Location:".$tmp;
header($loc);
exit();
}
But the problem is that when the Amazon URL is like: http://www.amazon.in/English-Movies-TV-Shows/b/ref=sa_menu_movies_all_hindi?ie=UTF8&node=4068584031 it adds the affiliate id like this: ie=UTF8&affiliate_id (it automatically removes the node and its value) but I want it to be like: ie=UTF8&node=4068584031&affiliate_id.
This means that I need to add &affiliate_id at the end of the URL every time if it is an Amazon link.
Actually I just want to achieve the following simple thing: if the URL doesn't have any ?s, I need to place ?affiliateid and if the URL has a ?, I just need to append &affiliateid at the end.
Can you suggest the very simple method for implementing what I require?
Let PHP do the string parsing for you. Let's say your affiliate id is XYWZ.
if (strpos($mylink, "amazon.in") !== 0) {
$urlarray=parse_url($mylink);
$urlarray['query']='affiliate_id=XYWZ&'.$urlarray['query'];
$newurl= $urlarray['scheme'].'://'.$urlarray['host'].$urlarray['path'].'?'.$urlarray['query'];
echo $newurl;
}
will output
http://www.amazon.in/English-Movies-TV-Shows/b/ref=sa_menu_movies_all_hindi?affiliate_id=XYWZ&ie=UTF8&node=4068584031
see? I didn't need to worry if there's a question mark. It will be stripped in the output of parse_url;
Edit: using $mylink instead of $theurl

HREF to call a PHP function and pass a variable?

Is it possible to create an HREF link that calls a PHP function and passes a variable along with it?
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='search($id)' >$name</a>";
}
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
You can do this easily without using a framework. By default, anything that comes after a ? in a URL is a GET variable.
So for example, www.google.com/search.html?term=blah
Would go to www.google.com/search.html, and would pass the GET variable "term" with the value "blah".
Multiple variables can be separated with a &
So for example, www.google.com/search.html?term=blah&term2=cool
The GET method is independent of PHP, and is part of the HTTP specification.
PHP handles GET requests easily by automatically creating the superglobal variable $_GET[], where each array index is a GET variable name and the value of the array index is the value of the variable.
Here is some demo code to show how this works:
<?php
//check if the get variable exists
if (isset($_GET['search']))
{
search($_GET['search']);
}
function Search($res)
{
//real search code goes here
echo $res;
}
?>
Search
which will print out 15 because it is the value of search and my search dummy function just prints out any result it gets
The HTML output needs to look like
anchor text
Your function will need to output this information within that format.
No, you cannot do it directly. You can only link to a URL.
In this case, you can pass the function name and parameter in the query string and then handle it in PHP as shown below:
print "<a href='yourphpscript.php?fn=search&id=$id' >$name</a>";
And, in the PHP code :
if ($_GET['fn'] == "search")
if (!empty($_GET['id']))
search($id);
Make sure that you sanitize the GET parameters.
No, at least not directly.
You can link to a URL
You can include data in the query string of that URL (<a href="myProgram.php?foo=bar">)
That URL can be handled by a PHP program
That PHP program can call a function as the only thing it does
You can pass data from $_GET['foo'] to that function
Yes, you can do it. Example:
From your view:
<p>Edit
Where 1 is a parameter you want to send. It can be a data taken from an object too.
From your controller:
function test($id){
#code...
}
Simply do this
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='?search=" . $id . "' > " . $name . "</a>";
}
}
if (isset($_REQUEST['search'])) {
search($_REQUEST['search']);
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
Also make sure that your $json_output is accessible with is the sample() function. You can do it either way
<?php
function sample(){
global $json_output;
// rest of the code
}
?>
or
<?php
function sample($json_output){
// rest of the code
}
?>
Set query string in your link's href with the value and access it with $_GET or $_REQUEST
<?php
if ( isset($_REQUEST['search']) ) {
search( $_REQUEST['search'] );
}
function Search($res) {
// search here
}
echo "<a href='?search='" . $id . "'>" . $name . "</a>";
?>
Yes, this is possible, but you need an MVC type structure, and .htaccess URL rewriting turned on as well.
Here's some reading material to get you started in understanding what MVC is all about.
http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
And if you want to choose a sweet framework, instead of reinventing the MVC wheel, I highly suggest, LARAVEL 4

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.

Remove querystring value on page refresh

I am redirecting to a different page with Querystring, say
header('location:abc.php?var=1');
I am able to display a message on the redirected page with the help of querystring value by using the following code, say
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
echo 'Done';
}
}
But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.
Thanks in advance.
You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.
Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.
Option two is to save the message in a server-side session and display it once. E.g., something like:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
This can cause confusion with parallel requests though, but is mostly negligible.
Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:
if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
echo $_SESSION['messages'][$_GET['message']];
unset($_SESSION['messages'][$_GET['message']]);
}
Better use a session instead
Assign the value to a session var
$_SESSION['whatever'] = 1;
On the next page, use it and later unset it
if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
//Do whatever you want to do here
unset($_SESSION['whatever']); //And at the end you can unset the var
}
This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users
There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.
When the message prompt ask for a non exsisting session. If false, show the message, if true, do nothing. session_start(); is only needed, if there is no one startet before.
session_start();
if ($_GET['var']==1 && !isset($_SESSION['message_shown']))
{
$_SESSION['message_shown'] = 1;
echo 'Done';
}
Try this way [Using Sessions]
<?php
//abc.php
session_start();
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
if(isset($_SESSION['views']))
{
//$_SESSION['views']=1;
}
else
{
echo 'Done';
$_SESSION['views']=1;
}
}
}
?>
Think the question mean something like this?
$uri_req = trim($_SERVER['REQUEST_URI']);
if(!empty($_SERVER['REQUEST_URI'])){
$new_uri_req = str_replace('?avar=1', '?', $uri_req);
$new_uri_req = str_replace('&avar=1', '', $new_uri_req);
$pos = strpos($new_uri_req, '?&');
if ($pos !== false) {
$new_uri_req = str_replace('?&', '?', $new_uri_req);
}
}
if( strrchr($new_uri_req, "?") == '?' ){
$new_uri_req = substr($new_uri_req, 0, -1);
}
echo $new_uri_req; exit;
You can use then the url to redirect without vars. You can also do the same in js.
str_replace() can pass array of values to be replaced. First two calls to str_replace() can be unified, and filled with as many vars you like that needs to be removed. Also note that with preg_replace() you can use regexp that can so manage any passed var which value may change. Cheers!

Categories