I have a redirect character strip script, that takes the original URL, strips the requested strings out of it (foo , bar) and then redirects to the same URL only without these strings.
It's currently set up to work with HTTP Only, as users always requests the HTTP page. But now I'm adding HTTPS, so some users will land on HTTPS. in that case, I'd like the redirect to be to the HTTPS.
How Can I do it?
I've tried simply changing:
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
Into:
$url = "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
But it created an invalid request (mydomain.com//mydomain.com....)
CODE:
function unparse_url($parsed_url) {
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
$port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
$user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
$pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
$pass = ($user || $pass) ? "$pass#" : '';
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
$query = !empty($parsed_url['query']) ? '?' . trim($parsed_url['query'], '&') : '';
$fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
return "$scheme$user$pass$host$port$path$query$fragment";
}
function strip_query($url, $query_to_strip) {
$parsed = parse_url($url);
$parsed['query'] = preg_replace('/(^|&)'.$query_to_strip.'[^&]*/', '', $parsed['query']);
return unparse_url($parsed);
}
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url2 = (strip_query($url, 'foo')); # query to strip - foo
$new_url = (strip_query($url2, 'bar')); # strip also - bar
$filtered = array_filter(array_keys($_GET), function($k) {
return strpos($k, 'foo') === 0;
});
if ( !empty($filtered) ) {
$_SESSION['trackParam'] = $_GET; // #### Save original request data and url before redirection
$_SESSION['REQUEST_URI'] = $_SERVER[REQUEST_URI];
$_SESSION['redirected'] = true;
header ("Location: $new_url");
}
You can use $_SERVER['HTTPS'] to decide whether to use https in your $url:
function check_https() {
return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| $_SERVER['SERVER_PORT'] == 443;
}
$url = (check_https() ? "https" : "http")
."://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
You can check if the request is made to HTTPS and put a condition:
if( isset($_SERVER['HTTPS'] ) ) { $url= ... } else {$url= ... }
Related
I want to store session data right before a 302 redirect occurs, to the same page, only without some of the original request parameters.
for example:
Visitor goes to domain.com/?ab_saveme=hey
hey value will get stored
Visitor will get redirected to domain.com/
Page will output hey
This is the code I came with, it does the redirect, but it doesn't manage to store the value (hey is not being outputed).
Without the redirect block, it does store it correct.
<?php
session_start();
session_name("hello");
$_SESSION['cache']=$_GET['ab_saveme']; // store the `saveme` value
// begin self redirect code
function unparse_url($parsed_url) {
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
$port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
$user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
$pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
$pass = ($user || $pass) ? "$pass#" : '';
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
$query = !empty($parsed_url['query']) ? '?' . trim($parsed_url['query'], '&') : '';
$fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
return "$scheme$user$pass$host$port$path$query$fragment";
}
function strip_query($url, $query_to_strip) {
$parsed = parse_url($url);
$parsed['query'] = preg_replace('/(^|&)'.$query_to_strip.'[^&]*/', '', $parsed['query']);
return unparse_url($parsed);
}
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$new_url = (strip_query($url, 'ab')); # or whatever query you want to strip/keep
$filtered = array_filter(array_keys($_GET), function($k) {
return strpos($k, 'ab') === 0;
});
if ( !empty($filtered) ) {
header ("Location: $new_url");
}
// end self redirect code
echo $_SESSION['cache']; // needs to echo original `saveme` value
echo session_id();
if (is_writable(session_save_path()))
{
echo "writable";
}
?>
Edit:
Thanks to Zimmi, I noticed I was re-storing a null value.
Is the best practice to handle this is change:
$_SESSION['cache']=$_GET['ab_saveme']; // store the `saveme` value
into:
if (!empty($_GET['ab_saveme'])) {
$_SESSION['cache']=$_GET['ab_saveme']; // store the `saveme` value
}
Or is there a better way? as I might have to do this for various parameters (such as ab_1,ab_2)
I'm trying to create a QR code based on current URL using goqr.me API: https://api.qrserver.com/v1/create-qr-code/?size=150x150&data= so I need generate this code
<img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=**currentURL**">
Things I've tried:
1)
<?php
function getUrl() {
$url = #( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : ""; $url .= $_SERVER["REQUEST_URI"];
echo '<img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data='.$url;
} ?>
2)
<img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=<?php function getUrl() {
$url = #( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : ""; $url .= $_SERVER["REQUEST_URI"]; echo $url;} ?>">
As you can see, I'm not very good at PHP programming. I really hope you can help me.
In you second example you declare the function and don't call it, so nothing gets written.
The second example can be changed to this:
<img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=<?php function getUrl() {
$url = #( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : ""; $url .= $_SERVER["REQUEST_URI"]; echo $url;} getUrl(); ?>">
or it would look better like this:
<?php
function getUrl() {
$url = #( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : ""; $url .= $_SERVER["REQUEST_URI"];
return $url;
}
?>
<img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=<?= getUrl(); ?> ">
I was trying to make this function more comprehensive to parse more of a url
Currently the function I have is this
function _pagepeeker_format_url($url = FALSE) {
if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
return FALSE;
}
// try to parse the url
$parsed_url = parse_url($url);
if (!empty($parsed_url)) {
$host = (!empty($parsed_url['host'])) ? $parsed_url['host'] : '';
$port = (!empty($parsed_url['port'])) ? ':' . $parsed_url['port'] : '';
$path = (!empty($parsed_url['path'])) ? $parsed_url['path'] : '';
$query = (!empty($parsed_url['query'])) ? '?' . $parsed_url['query'] : '';
$fragment = (!empty($parsed_url['fragment'])) ? '#' . $parsed_url['fragment'] : '';
return $host . $port . $path . $query . $fragment;
}
return FALSE;
}
This function turns urls that look like this
http://www.google.com/url?sa=X&q=http://www.beautyjunkiesunite.com/WP/2012/05/30/whats-new-anastasia-beverly-hills-lash-genius/&ct=ga&cad=CAcQARgAIAEoATAAOABA3t-Y_gRIAlgBYgVlbi1VUw&cd=F7w9TwL-6ao&usg=AFQjCNG2rbJCENvRR2_k6pL9RntjP66Rvg
into this
http://www.google.com/url
Is there anyway to make this array return the entire url instead of just part of it ?
I have looked at the parse_url php page and it helps and searched the stackoverflow and found a couple of things I am just having a bit of trouble grasping the next step here.
Let me know if I can clarify in any way
thanks!!
return $url;
Or am I missing something?
this is what i use (getting rid of parse_url and such):
function get_full_url() {
// check SSL
$ssl = "";
if ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"]=="on") || (isset($_SERVER["SERVER_PORT"]) && $_SERVER["SERVER_PORT"]=="443"))
{ $ssl = "s"; }
$serverport = ($_SERVER["SERVER_PORT"]!="80"?":".$_SERVER["SERVER_PORT"]:"");
return "http".$ssl."://".$_SERVER["SERVER_NAME"].$serverport.$_SERVER["REQUEST_URI"];
}
just call get_full_url(); from anywhere in your script.
Soooo it's me again with this function..
I have the function working.
function http_file_exists($url)
{
$f = #fopen($url,"r");
if($f)
{
fclose($f);
return true;
}
return false;
}
And this is the usage :
if ($submit || $preview || $refresh)
{
$post_data['your_url'] = "http://www.google.com/this"; //remove the equals and url value if using in real post
$your_url = $post_data['your_url'];
$your_url_exists = (isset($your_url)) ? true : false;
$your_url = preg_replace(array('#&\#46;#','#&\#58;#','/\[(.*?)\]/'), array('.',':',''), $your_url);
if ($your_url_exists && http_file_exists($your_url) == true)
{
trigger_error('exists!');
}
How do I let it check the whole url and not the domain name only ? for example http://www.google.com/this
url tested is http://www.google.com/abadurltotest
source of code below = What is the fastest way to determine if a URL exists in PHP?
function http_file_exists($url)
{
//$url = preg_replace(array('#&\#46;#','#&\#58;#','/\[(.*?)\]/'), array('.',':',''), $url);
$url_data = parse_url ($url);
if (!$url_data) return FALSE;
$errno="";
$errstr="";
$fp=0;
$fp=fsockopen($url_data['host'],80,$errno,$errstr,30);
if($fp===0) return FALSE;
$path ='';
if (isset( $url_data['path'])) $path .= $url_data['path'];
if (isset( $url_data['query'])) $path .= '?' .$url_data['query'];
$out="GET /$path HTTP/1.1\r\n";
$out.="Host: {$url_data['host']}\r\n";
$out.="Connection: Close\r\n\r\n";
fwrite($fp,$out);
$content=fgets($fp);
$code=trim(substr($content,9,4)); //get http code
fclose($fp);
// if http code is 2xx or 3xx url should work
return ($code[0] == 2 || $code[0] == 3) ? TRUE : FALSE;
}
add the top code to functions_posting.php replacing previous function
if ($submit || $preview || $refresh)
{
$post_data['your_url'] = " http://www.google.com/abadurltotest";
$your_url = $post_data['your_url'];
$your_url_exists = (request_var($your_url, '')) ? true : false;
$your_url = preg_replace(array('#&\#46;#','#&\#58;#','/\[(.*?)\]/'), array('.',':',''), $your_url);
if ($your_url_exists === true && http_file_exists($your_url) === false)
{
trigger_error('A bad url was entered, Please push the browser back button and try again.');
}
Use curl and check the HTTP status code. if it's not 200 - most likely the url doesn't exist or inaccessible.
also note that
$your_url_exists = (isset($your_url)) ? true : false;
makes no sense. It seems you want
$your_url_exists = (bool)$your_url;
or just check $your_url instead of $your_url_exists
I use the "Current url" function to get the current link when user changing page language
$uri = explode('&', $_SERVER['REQUEST_URI']);
$uri = $uri[0];
$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$uri : "http://".$_SERVER['SERVER_NAME'].$uri;
Problem is, when I have a link like this:
http://127.0.0.1/index.php?id=shop&id2=13&lang=lt
id2, of course, disappears. What can I do about this? It is possible if id2 is set to use explode with a second & or something like this?
You can use the parse_url function, here is an example:
$uri = parse_url( $_SERVER['REQUEST_URI']);
$protocol = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
$url = $protocol . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'] . '?' . ( isset( $uri['query']) ? $uri['query'] : '');
I did not see in your code where you get the script's filename, so I used $_SERVER['SCRIPT_NAME'].
Edit: My mistake, I did not see that you need to manipulate / remove the last $_GET parameter. Here is an example on how to do that using a method similar to the above in conjunction with parse_str. Note that this method will work regardless of the location of the lang parameter, it does not have to be the last one in the query string.
$protocol = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
$params = array();
if( isset( $_SERVER['QUERY_STRING']) && !empty( $_SERVER['QUERY_STRING']))
{
parse_str( $_SERVER['QUERY_STRING'], $params);
$params['lang'] = 'anything';
// unset( $params['lang']); // This will clear it from the parameters
}
// Now rebuild the new URL
$url = $protocol . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'] . ( !empty( $params) ? ( '?' . http_build_query( $params)) : '');
Thanks to #Yzmir Ramirez for an improvement in the second version that eliminates the extraneous call to parse_url.
$uri = explode('&', '/index.php?id=shop&id2=13&lang=lt');
$uri = $uri[0];
echo $uri; //echos /index.php?id=shop
You'll want to use
$_SERVER['QUERY_STRING']
to get just the query string. And if you want to keep all the variables, then just keep $uri set to the explode then cycle through them with a foreach.
$uri = explode('&', $_SERVER['QUERY_STRING'];
foreach ($uri as $var_val) {
$var_val = explode('=', $var_val);
$var = $var_val[0];
$val = $var_val[1];
}
Try this: http://codepad.org/cEKYTAp8
$uri = "http://127.0.0.1/index.php?id=shop&id2=13&lang=lt";
$uri = substr($uri, 0, strrpos($uri, '&'));
var_dump($uri); // output: string(41) "http://127.0.0.1/index.php?id=shop&id2=13"
Here is the code I have always used, it also supports ports.
$protocol = (!isset($_SERVER["HTTPS"]) || strtolower($_SERVER["HTTPS"]) == "off") ? "http://" : "https://";
$port = ((isset($_SERVER["SERVER_PORT"]) &&
// http:// protocol defaults to port 80
(($_SERVER["SERVER_PORT"] != "80" && $protocol == "http://") ||
// https:// protocol defaults to port 443
($_SERVER["SERVER_PORT"] != "443" && $protocol == "https://")) &&
// Port is not in http host (port is followed by : at end of address)
strpos($_SERVER["HTTP_HOST"], ":") === false) ? ":" . $_SERVER["SERVER_PORT"] : '');
return $protocol . $_SERVER["HTTP_HOST"] . $port . $_SERVER["REQUEST_URI"];