Viewed   58 times

I am currently working on a blog where I would like to create links to my individual articles in the following form:

http://www.mysite.com/health/2013/08/25/some-random-title
                      ------            -----------------
                        |                       |
                     category                 title

However I have no idea how to achieve this.

I have found something that would give me the URI.

$uri = $_SERVER["REQUEST_URI"];

I would then go ahead and extract the needed parts and make requests against the database. This may seem a very very dumb question, but I do not know how to look this up on google (I tried...) but how exactly am I going to handle the link ?

I try to explain it step-by-step:

User clicks on article title -> the page reloads with new uri --> Where am I supposed to handle this new uri and how ? If the request path looked like this:

index.php?title=some-random-article-title

I would do it in the index.php and read the $_GET array and process it accordingly. But how do I do it with the proposed structure at the beginning of this question ?

 Answers

2

You will need a few things:

  1. Setup an .htaccess to redirect all request to your main file which will handle all that, something like:

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>
    

    The above will redirect all request of non-existent files and folder to your index.php

  2. Now you want to handle the URL Path so you can use the PHP variable $_SERVER['REQUEST_URI'] as you have mentioned.

  3. From there is pretty much parse the result of it to extract the information you want, you could use one of the functions parse_url or pathinfo or explode, to do so.

Using parse_url which is probably the most indicated way of doing this:

$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "https" : "http";
$url = $s . '://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
var_dump(parse_url($url));

Output:

["scheme"] => string(4) "http" 
["host"]   => string(10) "domain.com" 
["path"]   => string(36) "/health/2013/08/25/some-random-title" 
["query"]  => string(17) "with=query-string"

So parse_url can easily break down the current URL as you can see.

For example using pathinfo:

$path_parts = pathinfo($_SERVER['REQUEST_URI']);

$path_parts['dirname'] would return /health/2013/08/25/

$path_parts['basename'] would return some-random-title and if it had an extension it would return some-random-title.html

$path_parts['extension'] would return empty and if it had an extension it would return .html

$path_parts['filename'] would return some-random-title and if it had an extension it would return some-random-title.html

Using explode something like this:

$parts = explode('/', $path);
foreach ($parts as $part)
    echo $part, "n";

Output:

health
2013
08
25
some-random-title.php

Of course these are just examples of how you could read it.

You could also use .htaccess to make specific rules instead of handling everything from one file, for example:

RewriteRule ^([^/]+)/([0-9]+)/([0-9]+)/([0-9]+)/([^/]+)/?$ blog.php?category=$1&date=$2-$3-$4&title=$5 [L]

Basically the above would break down the URL path and internally redirect it to your file blog.php with the proper parameters, so using your URL sample it would redirect to:

http://www.mysite.com/blog.php?category=health&date=2013-08-25&title=some-random-title

However on the client browser the URL would remain the same:

http://www.mysite.com/health/2013/08/25/some-random-title

There are also other functions that might come handy into this for example parse_url, pathinfo like I have mentioned early, server variables, etc...

Wednesday, September 14, 2022
5

UPDATE: Casimir's commented solution is more direct/clean.

Code: (Demo) (Pattern Demo)

echo preg_replace('~[url(?|]((https?://[^[]+))|(?:="(https?://[^"]+)")](.+?))[/url]~i', '<a href="$1">$2</a>', $bbcode);

By doubling the capture of the first alternative in the pattern, you can ensure that you always have a $1 and $2 to apply to the replacement string.

Here is a slightly extended variation of the pattern that considers single quoting and no quoting.


(Start of previous solution)

By using preg_match_callback() you can determine if there was a url provided inside of the opening no.http.example.com', '[url]https://any.com/any" target="_blank"> tag -- in which case, you will want to preserve the text that is located between the opening and closing tags.

If the text between the tags IS the url, you use it in both places in the <a> tag string.

Invalid strings will not be converted.

Code: (Demo) (Pattern Demo)

$bbcodes = [
    'no.http.example.com',
    '[url]https://any.com/any',
    'nourl',
    'text text',
    '',
    'http://www.any.com/any?any=44#sss',
    'http://differenturl'
];

foreach ($bbcodes as $bbcode) {
    echo preg_replace_callback('~[url(?:](https?://[^[]+)|(?:="(https?://[^"]+)")](.+?))[/url]~i',
                          function($m) {
                              if (isset($m[2])) {
                                  return "<a href="{$m[2]}">{$m[3]}</a>";
                              }
                              return "<a href="{$m[1]}">{$m[1]}</a>";
                          },
                          $bbcode);
    echo "n---n";
}

Output:

no.http.example.com
---
<a href="https://any.com/any">https://any.com/any</a>
---
nourl
---
<a href="https://any.com/any?any=333">text text</a>
---

---
<a href="http://www.any.com/any?any=44#sss">http://www.any.com/any?any=44#sss</a>
---
<a href="https://conflictinglink">http://differenturl</a>
---

Pattern Breakdown:

~                    #start of pattern delimiter
[url                #match literally [url
(?:                  #start non-capturing group #1
  ]                  #match literally ]
  (https?://[^[]+)   #match and store as Capture Group #1 http , an optional s , colon , two forward slashes, then one or more non-opening square brackets (since valid href values cannot have square brackets)
  |                  #or
  (?:                #start non-capturing group #2
    ="               #match literally ="
    (https?://[^"]+) #match and store as Capture Group #2 (same logic as Capture Group #1)
    "                #match literally "
  )                  #end non-capturing group #2
  ]                  #match literally ]
  (.+?)              #match (lazily) and store as Capture Group #3 one or more characters (this is the innerHTML component)
)                    #end non-capturing group #1
[/url]              #match literally [/url]
~                    #end of pattern delimiter

The callback function assesses the elements in the matches array ($m) and conditionally generates and returns the desired output. If there are any matches, the output will either contain:

array(
    0 => [the fullstring match]
    1 => [the url of a bbcode tag that does not have a quoted url]
)

or

array(
    0 => [the fullstring match]
    1 => ''  // <-- empty string
    2 => [the quoted url of the bbcode tag]
    3 => [the text between the opening an closing bbcode tags]
)
Tuesday, September 6, 2022
 
4

You are not concatenating your strings properly.

for($i=0; $i < $numberOfRows; $i++) {
        $row = $result->fetch_assoc();
        echo '<tr>';
        echo '<td>' . $row['artistName'] . '</td>';
        echo '<td><a href="' . $row['url'] . '" >' . $row['songTitle'] . '</a></td>';
        echo '<td>' . $row['yOR'] . '</td>';
        echo '</tr>';
    }
Tuesday, October 11, 2022
2

I'd turn the byte array into a memory stream. Then instantiate a binary reader on that stream. And then define helper functions that take a binary reader and parse a single class.

The built in BinaryReader class always uses little endian.

I'd use classes instead of structs here.

class PacketHeader 
{
    uint16_t magic;
    uint16_t packet_size;
    uint32_t unknown1;
    uint32_t unknown2;
    uint32_t unknown3;
    uint32_t unknown4;
    uint16_t unknown5;
    uint16_t unknown6;
    uint32_t unknown7;
    uint32_t unknown8;
    string packet_type; // replaced with a real string
};

PacketHeader ReadPacketHeader(BinaryReader reader)
{
  var result=new PacketHeader();
  result.magic = reader.ReadInt16();
  ...
  result.packet_type=ReadCString();//Some helper function you might need to define yourself
  return result;
}
Sunday, August 7, 2022
5

Found the answer:

jQuery.ajax success callback function not executed

When I took out the dataType: "json", it worked!

Sunday, December 18, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :