I'm building a php system which allow users to resend their invoices that need to be rechecked,
My problem is i need to make a condition to my system so it can't accept any url expect urls that looks like the following example
$url = http://mydomain.com/$id/invoice/$num
http://mydomain.com/murad/invoice/6589445564555
http://mydomain.com/ludmilla/invoice/9764564252
code:
} elseif(preg_match("|^http(s)?://(www.)?mydomain.com/([a-z]+)/(.*)?$|i", $url)){
$msg = '<div class="msg"><div class="error">'.$lang['er_01'].'</div></div>';
but it didn't work , Can i know how to make it work correctly ?
AFAIK, you need to reverse the test and change a bit the regex, try this:
} elseif( ! preg_match("|^http(s)?://(www.)?mydomain.com/([a-z]+)/invoice/(\d+)$|i", $url) ){
$msg = '<div class="msg"><div class="error">'.$lang['er_01'].'</div></div>';
Related
I'm using below function to redirect a specific url to a specific php script file:
add_action('wp', function() {
if ( trim(parse_url(add_query_arg(array()), PHP_URL_PATH), '/') === 'pagename' ) {
include(locate_template('give_some.php'));
exit();
}});
it works only for the specified url and i want to make it work for multiple urls. Suppose a file urls.txt contain numbers of url and for which above code have to be triggered. Any idea how to do this?
I’m a long-time WordPress developer, and one of the best responses to a WordPress problem is “that’s not a WordPress problem, just simple PHP (or JavaScript)” one. That’s a really good thing because it makes it really easy to talk about.
Your problem, as I understand it, is that you want to compare the current URL to a “file” of possible paths. You’ve got the WordPress equivalent of “current URL”, so I’ll take that for granted, and I’ll also assume you can take a file and convert it into an array. But once you do that, you are parsing a URL (which you already did) and seeing if it is in the array:
$url = 'https://www.example.com/pagename?a=b&c=d';
$paths = [
'gerp',
'pagename',
'cheese',
];
$path = trim(parse_url($url, PHP_URL_PATH), '/');
if ( in_array($path, $paths )) {
echo 'yes';
} else {
echo 'no';
}
Demo: https://3v4l.org/NOmpk
You can use different hook request. Which allow you to manipulate request.
add_filter( 'request', function( $request ){});
My simple example ( not tested ).
add_filter( 'request', function( $request ){
$data = file_get_contents("database.txt"); //read the file
$rows = explode("\n", $data); //create array separate by new line
$rows = array_map("trim", $rows); // for removing any unwanted space
$rowCount = count($rows); // Count your database rows
for ($i=0; $i < $rows ; $i++) {
if( isset( $request['pagename'] ) && $rows[$i] == $request['pagename'] ){
include(locate_template('give_some.php'));
}
}
return $request;
});
My advice, don't use .txt files, save your data into database, and then use it, or create wp_option field, and manage from Settings page.
I think my question is some stupid because the code work, I only want know if I can do it better hehe, I want get a text from a URL usin GET, but I want check if it is empty, check if the text have numbers, and if the text is not a option of two options required condition_text_1 and condition_text_2, so I need do it with conditionals (IF), I will show my code:
if (isset($_GET['TEXT'])&&!empty($_GET['TEXT'])) {
if (!preg_match("/^[A-Za-z]+$/", $_GET['TEXT'])) {
$url = "DEFAULT_TEXT";
}else{
if ($_GET['TEXT'] !== 'condition_text_1' && $_GET['TEXT'] !== 'condition_text_2') {
$url = "DEFAULT_TEXT";
}else{
$url = $_GET['TEXT'];
}
}
}else{
$url = "DEFAULT_TEXT";
}
I dont know if its explained correct, but Im not talk english and Im new on php so it is a explosive post. Advanced thanks!!
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
I’ve tried for some time now to solve what probably is a small issue but I just can’t seem get my head around it. I’ve tried some different approaches, some found at SO but none has worked yet.
The problem consists of this:
I’ve a show-room page where I show some cloth. On each single item of cloth there is four “views”
Male
Female
Front
Back
Now, the users can filter this by either viewing the male or female model but they can also filter by viewing front or back of both gender.
I’ve created my script so it detects the URL query and display the correct data but my problem is to “build” the URL correctly.
When firstly enter the page, the four links is like this:
example.com?gender=male
example.com?gender=female
example.com?site=front
example.com?site=back
This work because it’s the “default” view (the default view is set to gender=male && site=front) in the model.
But if I choose to view ?gender=female the users should be able to filter it once more by adding &site=back so the complete URL would be: example.com?gender=female&site=back
And if I then press the link to see gender=male it should still keep the URL parameter &site=back.
What I’ve achived so far is to append the parameters to the existing URL but this result in URL strings like: example.com?gender=male&site=front&gender=female and so on…
I’ve tried but to use the parse_url function, the http_build_query($parms) method and to make my “own” function that checks for existing parameters but it does not work.
My latest try was this:
_setURL(‘http://example.com?gender=male’, ‘site’, ‘back’);
function _setURL($url, $key, $value) {
$separator = (parse_url($url, PHP_URL_QUERY) == NULL) ? '?' : '&';
$query = $key."=".$value;
$url .= $separator . $query;
var_dump($url); exit;
}
This function works unless the $_GET parameter already exists and thus should be replaced and not added.
I’m not sure if there is some “best practice” to solve this and as I said I’ve looked at a lot of answers on SO but none which was spot on my issue.
I hope I’ve explained myself otherwise please let me know and I’ll elaborate.
Any help or advice would be appreciated
You can generate the links dynamically using the following method:
$frontLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=front':'mydomain.com?site=front';
$backLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=back':'mydomain.com?site=back';
This is a 1 line if statement which will set the value of the variables $frontLink and $backlink respectively. The syntax for a 1 line if statement is $var = (if_statement) ? true_result:false_result; this will set the value of $var to the true_result or false_result depending on the return value of the if statement.
You can then do the same for the genders:
$maleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=male&site='.$_GET['site']:'mydomain.com?gender=male';
$femaleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=female&site='.$_GET['site']:'mydomain.com?gender=female';
Found this by searching for a better solution then mine and found this ugly one (That we see a lot on the web), so here is my solution :
function add_get_parameter($arg, $value)
{
$_GET[$arg] = $value;
return "?" . http_build_query($_GET);
}
<?php
function requestUriAddGetParams(array $params)
{
$parseRes=parse_url($_REQUEST['REQUEST_URI']);
$params=array_merge($_GET, $params);
return $parseRes['path'].'?'.http_build_query($params);
}
?>
if(isset($_GET['diagid']) && $_GET['diagid']!='') {
$repParam = "&diagid=".$_GET['diagid'];
$params = str_replace($repParam, "", $_SERVER['REQUEST_URI']);
$url = "http://".$_SERVER['HTTP_HOST'].$params."&diagid=".$ID;
}
else $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."&diagid=".$ID;
I created a bit of code that just condition checks, like below
if ( $pretty_link_url==$_SERVER['HTTP_REFERER']) {
If this condition is true and working, then someone is using their browser with the same URL which is in "$pretty_link_url". "$pretty_link_url" is found in the database, and the if condition runs if they match. Now my question is
Is there anyway to get the result where both url from above $pretty_link_url==$_SERVER['HTTP_REFERER'] the same same as ...
$url = "result";
I don't know if it possible thankyou
I'm not sure what you really want but from your comment I think your looking for:
<?PHP
if ( $pretty_link_url == $_SERVER['HTTP_REFERER']) {
$url = $_SERVER['HTTP_REFERER'];
}else{
$url = ""; // empty or some other value you want to use instead
}
?>
I'm taking a guess at what exactly you're looking for, but is this it?:
$url = '';
if ( $pretty_link_url==$_SERVER['HTTP_REFERER']) {
$url = $_SERVER['HTTP_REFERER'];
}