I have a small bug in the construction of my URL, I've setup a test for when I am not using port:80 and for some reason if I use say port:8080 it is applying the port number twice for some reason in the code cant explain it.
public function get_full_url()
{
/** get $_SERVER **/
$server = self::get('SERVER');
$page_url = 'http';
if(isset($server['HTTPS']) and $server['HTTPS'] == 'on')
{
$page_url .= 's';
}
$site_domain = (isset($server['HTTP_HOST']) and trim($server['HTTP_HOST']) != '') ? $server['HTTP_HOST'] : $server['SERVER_NAME'];
$page_url .= '://';
if($server['SERVER_PORT'] != '80')
{
$page_url .= $site_domain.':'.$server['SERVER_PORT'].$server['REQUEST_URI'];
}
else
{
$page_url .= $site_domain.$server['REQUEST_URI'];
}
return $page_url;
}
$_SERVER['HTTP_HOST'] would contain port number as it is set in the Host: header
Related
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.
I have two code blocks that are PHP functions that do two different things. They are:
<?php
if (!function_exists('UserPhotoDefaultUrl')) {
function UserPhotoDefaultUrl($User) {
$Email = GetValue('Email', $User);
$HTTPS = GetValue('HTTPS', $_SERVER, '');
$Protocol = (strlen($HTTPS) || GetValue('SERVER_PORT', $_SERVER) == 443) ? 'https://secure.' : 'http://www.';
$Url = $Protocol.'gravatar.com/avatar.php?'
.'gravatar_id='.md5(strtolower($Email))
.'&size='.C('Garden.Thumbnail.Width', 50);
if (C('Plugins.Gravatar.UseVanillicon', FALSE))
$Url .= '&default='.urlencode(Asset('http://vanillicon.com/'.md5($Email).'.png'));
else
$Url .= '&default='.urlencode(Asset(C('Plugins.Gravatar.DefaultAvatar', 'plugins/Gravatar/default.gif'), TRUE));
return $Url;
}
}
and...
<?php
class GravatarPlugin extends Gdn_Plugin {
public function ProfileController_AfterAddSideMenu_Handler($Sender, $Args) {
if (!$Sender->User->Photo) {
$Email = GetValue('Email', $Sender->User);
$Hash = md5($Email);
$Sender->User->Photo = 'http://w'.substr($Hash, 0, 1).'.vanillicon.com/'.$Hash.'_200.png';
}
}
}
The first shows the Gravatar image for User avatar in post content of my script (Vanilla forums), and the second one shows the Vanillicons (Vanillicon is similar to Gravatar) of all the users participating in a discussion in the sidebar (under 'In This Discussion'). I hope you get the idea as to what the two code blocks do now?
Using the how-it's-done code in the first code block, I need to modify the second code block to show Gravatar icons of all users participating in a discussion instead of Vanillicons. Can someone who knows PHP help?
<?php
if (!function_exists('UserPhotoDefaultUrl')) {
function UserPhotoDefaultUrl($User) {
$Email = GetValue('Email', $User);
$HTTPS = GetValue('HTTPS', $_SERVER, '');
$Protocol = (strlen($HTTPS) || GetValue('SERVER_PORT', $_SERVER) == 443) ? 'https://secure.' : 'http://www.';
$Url = $Protocol.'gravatar.com/avatar.php?'
.'gravatar_id='.md5(strtolower($Email))
.'&size='.C('Garden.Thumbnail.Width', 50)
.'&default='.urlencode(Asset(C('Plugins.Gravatar.DefaultAvatar', 'plugins/Gravatar/default.gif'), TRUE));
return $Url;
}
}
you class:
<?php
class GravatarPlugin extends Gdn_Plugin {
public function ProfileController_AfterAddSideMenu_Handler($Sender, $Args) {
if (!$Sender->User->Photo) {
$Sender->User->Photo = UserPhotoDefaultUrl($Sender->User); // not sure about the $Sender->User part because it is not displayed
}
}
}
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'm using the jquery address plugin to build an ajax driven site, and i've got it working! Yay! For the purposes of this question we can use the test site:
http://www.asual.com/jquery/address/samples/crawling
http://www.asual.com/download/jquery/address
(I had to remove two calls to urlencode() to make the crawling example work.)
I'm encountering a problem with the $crawling->nav() call. It basically uses js and php to load parts of an xml file into the dom. I (mostly) understand how it works, and I would like to modify the example code to include sub pages.
For example, I would like to show 'subnav-project.html' at '/!#/project' and '/!#/project/blue', but not at '/!#/contact'. To do this, I figure php should 'know' what page the user is on, that way I can base my logic off of that.
Is this crazy? Can php ever know the current state of the site if I'm building it this way? If not, how does one selectively load html snippets, or modify what links are shown in navigation menus?
I've never gotten too crazy with ajax before, so any feedback at all would be helpful.
EDIT
This is the crawling class.
class Crawling {
const fragment = '_escaped_fragment_';
function Crawling(){
// Initializes the fragment value
$fragment = (!isset($_REQUEST[self::fragment]) || $_REQUEST[self::fragment] == '') ? '/' : $_REQUEST[self::fragment];
// Parses parameters if any
$this->parameters = array();
$arr = explode('?', $fragment);
if (count($arr) > 1) {
parse_str($arr[1], $this->parameters);
}
// Adds support for both /name and /?page=name
if (isset($this->parameters['page'])) {
$this->page = '/?page=' . $this->parameters['page'];
} else {
$this->page = $arr[0];
}
// Loads the data file
$this->doc = new DOMDocument();
$this->doc->load('data.xml');
$this->xp = new DOMXPath($this->doc);
$this->nodes = $this->xp->query('/data/page');
$this->node = $this->xp->query('/data/page[#href="' . $this->page . '"]')->item(0);
if (!isset($this->node)) {
header("HTTP/1.0 404 Not Found");
}
}
function base() {
$arr = explode('?', $_SERVER['REQUEST_URI']);
return $arr[0] != '/' ? preg_replace('/\/$/', '', $arr[0]) : $arr[0];
}
function title() {
if (isset($this->node)) {
$title = $this->node->getAttribute('title');
} else {
$title = 'Page not found';
}
echo($title);
}
function nav() {
$str = '';
// Prepares the navigation links
foreach ($this->nodes as $node) {
$href = $node->getAttribute('href');
$title = $node->getAttribute('title');
$str .= '<li><a href="' . $this->base() . ($href == '/' ? '' : '?' . self::fragment . '=' .html_entity_decode($href)) . '"'
. ($this->page == $href ? ' class="selected"' : '') . '>'
. $title . '</a></li>';
}
echo($str);
}
function content() {
$str = '';
// Prepares the content with support for a simple "More..." link
if (isset($this->node)) {
foreach ($this->node->childNodes as $node) {
if (!isset($this->parameters['more']) && $node->nodeType == XML_COMMENT_NODE && $node->nodeValue == ' page break ') {
$str .= '<p><a href="' . $this->page .
(count($this->parameters) == 0 ? '?' : '&') . 'more=true' . '">More...</a></p>';
break;
} else {
$str .= $this->doc->saveXML($node);
}
}
} else {
$str .= '<p>Page not found.</p>';
}
echo(preg_replace_callback('/href="(\/[^"]+|\/)"/', array(get_class($this), 'callback'), $str));
}
private function callback($m) {
return 'href="' . ($m[1] == '/' ? $this->base() : ($this->base() . '?' . self::fragment . '=' .$m[1])) . '"';
}
}
$crawling = new Crawling();
You won't be able to make server-side decisions using the fragment-identifier (i.e., everything to the right of the # character). This is because browsers don't send fragment-identifiers to the server. If you're going to want to make server-side decisions, you'll need to use some JavaScript assistance (including AJAX) to communicate what the current fragment-identifier is.
This question already has answers here:
PHP - Getting Current URL
(3 answers)
Closed 7 years ago.
I'm working on this page: http://localhost/projectname/custom.php
Both <?php echo $_SERVER['REQUEST_URI']; ?> and <?php echo $PHP_SELF; ?> don't give full location. What should I use to grab the full url location?
function selfURL()
{
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}
function strleft($s1, $s2) { return substr($s1, 0, strpos($s1, $s2)); }
There isn't a native method as far as I know, but you could use this:
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
If you are trying to add variables back onto the end of an URL that you are passing through a link tracking script, for example, you could try this:
$URI = array();
foreach($_GET as $key=>$val)
{
if ($key!="link"&&$key!="id"&&$key!="type") $URI[] = "$key=".urlencode($val);
}
if (sizeof($URI)>0) $link.="&".join("&",$URI);
In this case, "link", "id" and "type" were the variables I needed for the tracking, but the URL I wanted to track had a variable on the end of it that got stripped off by my script as if it was part of the query being sent to it; I needed the add it back to the link URL before passing it to header("Location:".$link).
If this is what you are trying to achieve this works great and is shorter than above example.
check this one... a bit long and dirty but works good...
function absolutizeUrl ( $u, $p )
{
$url = parse_url( $u );
$page = parse_url( $p );
if ( strpos( $u , '/' ) === 0 )
{
//already absolute
} else {
$basePath = '';
if (
isset( $page[ 'path' ] )
&& strpos( ltrim( $page[ 'path' ], '/' ), '/' )
)
{
$baseTokens = explode( '/', $page[ 'path' ] );
array_pop( $baseTokens ); // strip basename
$baseTokens[] = $u;
$u = join( '/', $baseTokens );
}
}
if ( ! isset( $url[ 'host' ]))
{
$u = 'http://'.$page[ 'host' ].'/'.ltrim( $u, '/' );
}
return $u;
}
I found this code very helpful
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') ===
FALSE ? 'http' : 'https'; // Get protocol HTTP/HTTPS
$host = $_SERVER['HTTP_HOST']; // Get www.domain.com
$script = $_SERVER['SCRIPT_NAME']; // Get folder/file.php
$params = $_SERVER['QUERY_STRING'];// Get Parameters occupation=odesk&name=ashik
$currentUrl = $protocol . '://' . $host . $script . '?' . $params; // Adding all
echo $currentUrl;