How to get current webpage name and echo with some modification - php

I am trying something strange with code i just want to know weather it is possible to perform a php code like this one
<?php
$cururl= ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME));
$nexurlw = $cururl-1;
echo "$nexurlw";
?>
I have a problem in this code. My current page url is 30.php and i have a button on page "go to previous page" i want to change its url 29.php with the help of this function.
But this function echo 30 every time.

Try this :
$cururl = ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME));
$intUrl = ((int) $cururl) - 1;
$nexurlw = (string) $intUrl.'.php';
echo "$nexurlw";

Even if it happens to be true in your case (because that's the default in a raw PHP installation) there's often no direct mapping between URL locations and filesystem objects (files / directories). For instance, this question's URL is
https://stackoverflow.com/questions/68504314/how-to-get-current-webpage-name-and-echo-with-some-modification but the Stack Overflow server does not have a directory called 68504314 anywhere on its disk.
You want to build a URL from another URL, thus there's no even any benefit in having the filesystem involved, you can just gather the information about current URL from $_SERVER['REQUEST_URI']. E.g.:
$previous_page_url = null;
if (preg_match('#/blah/(\d+)\.php#', $_SERVER['REQUEST_URI'], $matches)) {
$current_page_number = (int)$matches[1];
if ($current_page_number > 1) {
$previous_page_url = sprintf('/blah/%d.php', $current_page_number - 1);
}
}

Related

Dynamically created directory returns "Array" 1 in 1000 times

I'm fixing up some old code that is supposed to create a directory for a customer based on the customer's last name. 999 out of 1000 times it works as expected but every now and then I get an "Unable to create base directory" error message and the debug shows me that the $file_directory in that case is simply "Array" instead of something like "\\network\path\order_data\1234567890_Smith".
Could anyone explain how this code could work the vast majority of the time but still consistently fail about .1% of instances? Or is it something other than the code? Thanks!
Note: I did not originally write this code but am tring to leave it as close to the original as possible
Edit I had a typo in my previous code but I think tliokos and Fluinc had a very good point but just wanted to fix my mistake
Code:
<?php
$file_directory = build_directory($customer, $UID);
if(!is_dir($file_directory)){ //Check to make sure it does not already exist
if(!mkdir($file_directory)){
mail("debug#example.com","Unable to create base directory","$file_directory");
}
}
function build_directory($customer, $UID){
if($customer->related_orders){
$related = explode(",", $customer->related_orders);
foreach($related as $r_UID){
$rel_order = get_order($r_UID); //fetches order object
if((isset($rel_order->file_directory) && $rel_order->file_directory != "")){
return $rel_order->file_directory;
}
}
}
//Here is where I made my correction
$paths = array('\\\\network\\path');
$base = $paths[0];
//Test if directory is already assigned
if(is_dir($base . "\\order_data\\".$UID."_".str_replace(" ","_",$customer->last_name)."\\")){
return $base . "\\order_data\\".$UID."_".str_replace(" ","_",$customer->last_name)."\\";
}
if($base){
return $base . "\\order_data\\".$UID."_".str_replace(" ","_",$customer->last_name)."\\";
}
}
?>
Change $base = array('\\network\path');
To $base = '\\network\path';
I think the problem is in the build_directory() function and more specifically after the first if.
So if the customer has no related orders, you are trying to concatenate an Array with a string and the result is like
Array\order_data\....
Try o change
$base = array('\\network\path');
to
$base = '\\network\path';
So the problem ended up being framework/user related.
We discovered that if the user refreshed the page during the directory creation it would create the same directory twice which our framework would save as an array of identical paths.

PHP Auto-correcting URLs

I dont wan't reinvent wheel, but i couldnt find any library that would do this perfectly.
In my script users can save URLs, i want when they give me list like:
google.com
www.msn.com
http://bing.com/
and so on...
I want to be able to save in database in "correct format".
Thing i do is I check is it there protocol, and if it's not present i add it and then validate URL against RegExp.
For PHP parse_url any URL that contains protocol is valid, so it didnt help a lot.
How guys you are doing this, do you have some idea you would like to share with me?
Edit:
I want to filter out invalid URLs from user input (list of URLs). And more important, to try auto correct URLs that are invalid (ex. doesn't contains protocol). Ones user enter list, it should be validated immediately (no time to open URLs to check those they really exist).
It would be great to extract parts from URL, like parse_url do, but problem with parse_url is, it doesn't work well with invalid URLs. I tried to parse URL with it, and for parts that are missing (and are required) to add default ones (ex. no protocol, add http). But parse_url for "google.com" wont return "google.com" as hostname but as path.
This looks like really common problem to me, but i could not find available solution on internet (found some libraries that will standardize URL, but they wont fix URL if it is invalid).
Is there some "smart" solution to this, or I should stick with my current:
Find first occurrence of :// and validate if it's text before is valid protocol, and add protocol if missing
Found next occurrence of / and validate is hostname is in valid format
For good measure validate once more via RegExp whole URL
I just have feeling I will reject some valid URLs with this, and for me is better to have false positive, that false negative.
I had the same problem with parse_url as OP, this is my quick and dirty solution to auto-correct urls(keep in mind that the code in no way are perfect or cover all cases):
Results:
http:/wwww.example.com/lorum.html => http://www.example.com/lorum.html
gopher:/ww.example.com => gopher://www.example.com
http:/www3.example.com/?q=asd&f=#asd =>http://www3.example.com/?q=asd&f=#asd
asd://.example.com/folder/folder/ =>http://example.com/folder/folder/
.example.com/ => http://example.com/
example.com =>http://example.com
subdomain.example.com => http://subdomain.example.com
function url_parser($url) {
// multiple /// messes up parse_url, replace 2+ with 2
$url = preg_replace('/(\/{2,})/','//',$url);
$parse_url = parse_url($url);
if(empty($parse_url["scheme"])) {
$parse_url["scheme"] = "http";
}
if(empty($parse_url["host"]) && !empty($parse_url["path"])) {
// Strip slash from the beginning of path
$parse_url["host"] = ltrim($parse_url["path"], '\/');
$parse_url["path"] = "";
}
$return_url = "";
// Check if scheme is correct
if(!in_array($parse_url["scheme"], array("http", "https", "gopher"))) {
$return_url .= 'http'.'://';
} else {
$return_url .= $parse_url["scheme"].'://';
}
// Check if the right amount of "www" is set.
$explode_host = explode(".", $parse_url["host"]);
// Remove empty entries
$explode_host = array_filter($explode_host);
// And reassign indexes
$explode_host = array_values($explode_host);
// Contains subdomain
if(count($explode_host) > 2) {
// Check if subdomain only contains the letter w(then not any other subdomain).
if(substr_count($explode_host[0], 'w') == strlen($explode_host[0])) {
// Replace with "www" to avoid "ww" or "wwww", etc.
$explode_host[0] = "www";
}
}
$return_url .= implode(".",$explode_host);
if(!empty($parse_url["port"])) {
$return_url .= ":".$parse_url["port"];
}
if(!empty($parse_url["path"])) {
$return_url .= $parse_url["path"];
}
if(!empty($parse_url["query"])) {
$return_url .= '?'.$parse_url["query"];
}
if(!empty($parse_url["fragment"])) {
$return_url .= '#'.$parse_url["fragment"];
}
return $return_url;
}
echo url_parser('http:/wwww.example.com/lorum.html'); // http://www.example.com/lorum.html
echo url_parser('gopher:/ww.example.com'); // gopher://www.example.com
echo url_parser('http:/www3.example.com/?q=asd&f=#asd'); // http://www3.example.com/?q=asd&f=#asd
echo url_parser('asd://.example.com/folder/folder/'); // http://example.com/folder/folder/
echo url_parser('.example.com/'); // http://example.com/
echo url_parser('example.com'); // http://example.com
echo url_parser('subdomain.example.com'); // http://subdomain.example.com
It's not 100% foolproof, but a 1 liner.
$URL = (((strpos($URL,'https://') === false) && (strpos($URL,'http://') === false))?'http://':'' ).$URL;
EDIT
There was apparently a problem with my initial version if the hostname contain http.
Thanks Trent

PHP - Display results from this 'Detect' array?

re: Home Site = http://mobiledetect.net/
re: this script = Mobile_Detect.php
Download script here: https://github.com/serbanghita/Mobile-Detect
This script functions perfectly detecting the different parameters of a user's device.
However, this is how I am currently detecting these parameters:
// each part of the IF statement is hard-coded = not the way to do this
if($detect->isiOS()){
$usingOS = 'iOS';
}
if($detect->isAndroidOS()){
$usingOS = 'Android';
}
echo 'Your OS is: '.$usingOS;
My goal is to use a FOREACH to iterate thru the various arrays in this script to determine a user's device's parameters. I would need to have the "($detect->isXXXXOS())" be dynamic... (which, would be based upon the KEY). The results would display the KEY. But the detection would be based upon the VALUE.
Also, since my web page uses a REQUIRE to access this script... in the Mobile_Script.php script, the arrays are "protected." I think this is also causing me problems (but I don't know for sure).
Any help is appreciated.
In foreach loop you can call dynamic method look like this :
$array = array('Android','Windows','Linux','Mac');
foreach( $array as $value) {
$method = "is{$value}OS";
if($detect->$method()) {
$os = $value;
echo "Your OS is : {$os}";
}
}
Please rearrange your code what you want. I give you an example.
you can try to use somethin like this:
$OSList = $detect->getOperatingSystems();// will give array of operating system name => match params
foreach($OSList as $os_name=>$os_params/*unused*/)
{
$method = 'is'.$os_name;
if($detect->$method())
{
$usingOS = $os_name;
}
}

PHP Wordpress gallery not finding the XMLl file

The code is below - it uses a wordpress shortcode which is [my_hmg=widget.xml] but if you try change the xml file like this [my_hmg=example_gallery.xml] it just always reverts to the default widget.xml
The problem is in the function my_hmg_filter_Callback in particular these 2 lines;
#$my_hmg_file = #$output['filename'];
if($my_hmg_file==""){$my_hmg_file = "widget.xml";}
For some reason it always thinks the file name is blank so always reverts to widget.xml.
The files can be downloaded from here - http://www.gopiplus.com/work/2010/07/18/horizontal-motion-gallery/
function my_hmg_show_filter($content){
return preg_replace_callback('/\[my_hmg=(.*?)\]/sim','my_hmg_filter_Callback',$content);
}
function my_hmg_filter_Callback($matches)
{
$my_hmg_package = "";
$var = $matches[1];
parse_str($var, $output);
#$my_hmg_file = #$output['filename'];
if($my_hmg_file==""){$my_hmg_file = "widget.xml";
}
Firstly change the short code to [my_hmg file='file.xml']
Then if you have a quick read of Wordpress's short code API you'll see that the first argument in the callback function are the attributes of the short code.
This way you can the reference the attribute 'file' in the array and get the proper url.

finding current url and splitting them into parts and checking if there is index.php or not in the url

I am suffering from a problem while i take the current url of the page and spliting them into parts and then checking for the index.php phrase.So far i have done this:
<?php
$domain=$_SERVER['REQUEST_URI'];
$values = parse_url($domains);
$path = explode('/',$values['path']);
if(array_search($path[2], "index.php"))
{
echo "hello";
}
?>
but its not working so guys help me out and thank you in advance coz i know i will be satisfied by your answers.
Try this:
$pathToFile = $_SERVER['PHP_SELF'];
$currentFilename = substr($pathToFile, strrpos($pathToFile, '/') + 1);
if($currentFilename == 'index.php')
{
echo 'This file is index.php!';
}
$_SERVER['PHP_SELF'] is the path to the current file on the local system. Since you don't care about the domain name or the query string, this is easier.
strrpos($pathToFile, '/') gets the index of the last occurrence of / in $pathToFile.
substr($pathToFile, strrpos($pathToFile, '/') + 1) get the portion of $pathToFile starting with the character after the index found by strrpos() in step 2.
You should be left with only the filename in $currentFilename, which you can compare with whatever you choose.
Note that this will match any index.php file, not just the one at your domain root. For example, if your site is located at http://example.com, http://example.com/subdir/index.php would also be true for $currentFilename == 'index.php'. If that's not what you want, you'd do it a little differently.
Use this:
$domain=$_SERVER['REQUEST_URI'];
$path = explode('/',$domain);
if(array_search($path[2], "index.php"))
{
echo "hello";
}
I'm not sure what parse_url() is, but it didn't seem to do anything in your code.

Categories