How do you create domain.com/?stringhere without a .php extension - php

I want to create a link like the following:
http://www.myurl.com/?IDHERE
What i want to be able to do is be able to goto the above link, and then pull whats after the ? (in this case IDHERE) and be able to use that information to perform a MySQL lookup and return a page.
Can anyone point me into the right direction? please know this is using PHP not ASP

The issue here is not with your scripting language, but with your web server setup. I'll refer to these by their Apache names, but the features should be available in most web servers.
There are three features you might want to use:
1) content negotiation (mod_negotiation), which allows your web server to try a specified list of extensions in a specified order, for example: http://example.com/foo might be http://www.example.com/foo.html or http://example.com/foo.php
2) DirectoryIndex, which tells the web server that when a client asks for http://example.com it should look for a specified list of files in order, so it might server up http://example.com/index.html or http:/example.com/index.php
3) mod_rewrite, which allows you to basically rewrite the URL format received by the server. This allows you to do things like translate http://example.com/foo/bar/baz to http://example.com/foo/bar.php?page=baz
The rest is done by the backend script code as normal.

Create a default PHP file in that directory that will get loaded when no file name is specified (e.g. index.php). In your PHP script you can get the part after the question mark from the variable $_SERVER['QUERY_STRING'].

Do the following in your site's main index.php:
list($id) = array_keys($_GET);
// right now, $id represents the ID you're looking for.
// Do whatever you want with it.

In the link, form or whatever - index.php?id=someid
In your index.php file:
$_GET['id'] = $id
Now you can use it:
e.g.
echo $id;
Since it's your default page, it will work without the extension.

list($id) = array_keys($_GET);
// right now, $id represents the ID you're looking for.
// Do whatever you want with it.
this was exactly what i was looking for, though now i just need to create something to notify if nothing is there or not. Thank you all for your responses.

I would solve it by using .htaccess file if possible.
create a .htaccess file in the main directory with the content:
RewriteEngine on
RewriteRule cat/(.*)/(.*)/(.*)/$ /$1/$2.php?$3
that should translate "example.com/foo/bar/baz" to "example.com/foo/bar.php?page=baz"

Related

What is the function of using php for site links?

I am working on a site and the builders have used a mix of php and html for links. For example:
<li>Variable Speed Drives</li>
<li>Corrosion Resistant Baseplates</li>
and
<li>MP Repair</li>
<li>MTA Repair</li>
The php is referenced in another file in this way:
<?php
$pdf_link = "../pdf/";
$external_pdf_link = "../../pdf/";
$video_link = "../video/";
$external_video_link = "../../video/";
?>
My concern is not knowing the function of the php, other than it being a placeholder, and given that the links work both ways, I don't want to break something because I am clueless to its purpose.
In doing my due diligence researching, I ran across this post, which is close, but still no cigar, Add php variable inside echo statement as href link address?. All of the research seems to be about how rather than why. This is the site, and they only used it for the "Downloads" links: http://magnatexpumps.com/
Thank you...
B
There is no right way. They are just different.
Let's forget the PHP for a while. If you have this link in a page:
<a href='about.html'/>About</a>
What will happen? The browser will change the URL of the document. If you are at the root of the site like: "www.example.com", will redirect to "www.example.com/about.html". If you are in a URL like "www.example.com/news/index.html" will redirect you to "www.example.com/new/about". That's why sometimes it is useful to have a variable before, to force a full path URL.
Another case of URL variable interpolation is when you have different systems running in the same url. In this case, you will have to append the system name in order to get to where you want. If you don't know where your application will run if it will run on the doc root, or in a subfolder, use a variable to indicate the base path.

what is difference between "someurl/?a=2" and "someurl?a=2"

i know that we can send variables in url by this syntax:
http://www.example.com/index.php?a=1&b=2
and i know that we have some default files like index.html,index.php,...to redirect and we can rewrite above code as below:
http://www.example.com/?a=1&b=2
but i dont understand what is this :
http://www.google.com/search?q=e
this must be :
https://www.google.com/search/?q=e
are they same ?
This:
http://www.google.com/search
would technically be a file called search
and this:
https://www.google.com/search/
a directory called search and will usually be rewritten to the index file automatically.
Read this article by Google for more info about the so called "trailing slash": http://googlewebmastercentral.blogspot.de/2010/04/to-slash-or-not-to-slash.html
someurl/?a=2 will call someurl/index.php?a=2
someurl?a=2 will call someurl
From a strict URL standpoint, no, they are not the same. Depending on the handler that processes the request, they could give you the same result, but they are different URLs.
Not necessarely. "search" can be seen as a file without ending, while "search/" can be seen as a folder, where the default page (eg. index.php) will be loaded. It also can be customized with URL rewriting.
Frankly,
http://www.example.com/?a=1&b=2 is a shortcut for http://www.example.com/index.php?a=1&b=2
While someurl in http://www.example.com/someurl?a=1&b=2 is just a resource name, similar to someurl.php or someurl.html or whatever. a dot is not obligatory for the resource name
Yes, URIs that end in directory names (not file names) are usually treated the same as if you typed a / after them. So
http://domain.tld/directory
and
http://domain.tld/directory/
are both taken to mean http://domain.tld/directory/default.file
And it's the same whether you have a ? and parameters behind it or not.
In other words, in your examples, search is the name of a directory.

How to detect the path to the application root?

I'm trying to dynamically detect the root directory of my page in order to direct to a specific script.
echo ($_SERVER['DOCUMENT_ROOT']);
It prints /myName/folder/index.php
I'd like to use in a html-file to enter a certain script like this:
log out
This seems to be in bad syntax, the path is not successfully resolved.
What's the proper approach to detect the path to logout.php?
The same question in different words:
How can I reliably achieve the path to the root directory (which contains my index.php) from ANY subdirectory? No matter if the html file is in /lib/subfolder or in /anotherDirectory, I want it to have a link directing to /lib/logout.php
On my machine it's supposed to be http://localhost/myName/folder (which contains index.php and all subdirectories), on someone else's it might be http://localhost/project
How can I detect the path to application root?
After some clarification from the OP it become possible to answer this question.
If you have some configuration file being included in all php scripts, placed in the app's root folder you can use this file to determine your application root:
$approot = substr(dirname(__FILE__),strlen($_SERVER['DOCUMENT_ROOT']));
__FILE__ constant will give you filesystem path to this file. If you subtract DOCUMENT_ROOT from it, the rest will be what you're looking for. So it can be used in your templates:
log out
Probably you are looking for the URL not the Path
log out
and you are not echoing the variable in your example.
Your DOCUMENT_ROOT is local to your machine - so it might end up being c:/www or something, useful for statements like REQUIRE or INCLUDE but not useful for links.
If you've got a page accessible on the web - linking back to a document on C: is going to try and get that drive from the local machine.
So for links, you should just be able to go /lib/logout.php with the initial slash taking you right to the top of your web accessible structure.
Your page, locally - might be in c:/www/myprojects/project1/lib/logout.php but the site itself might be at http://www.mydomain.com/lib/project.php
Frameworks like Symfony offer a sophisticated routing mechanism which allows you to write link urls like this:
log out
It has tons of possibilities, which are described in the tutorial.
Try this,
log out
This jumps to the root directly.
DOCUMENT_ROOT refers to the physical path on the webserver. There is no generic way to detect the http path fragment. Quite often you can however use PHP_SELF or REQUEST_URI
Both depend on how the current script was invoked. If the current request was to the index.php in a /whatever/ directory, then try the raw REQUEST_URI string. Otherwise it's quite commonly:
<?= dirname($_SERVER["SCRIPT_NAME"]) . "/lib/logout.php" ?>
It's often best if you use a configurable constant for such purposes however. There are too many ifs going on here.
I'm trying to figure this out for PHP as well. In asp.net, we have Request.ApplicationPath, which makes this pretty easy.
For anyone out there fluent in PHP who is trying to help, this code does what the OP is asking, but in asp.net:
public string AppUrl
{
get
{
string appUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
if (appUrl.Substring(appUrl.Length - 1) != "/")
{
appUrl += "/";
}
// Workaround for sockets issue when using VS Built-int web server
appUrl = appUrl.Replace("0.0.0.0", "localhost");
return appUrl;
}
}
I couldn't figure out how to do this in PHP, so what I did was create a file called globals.php, which I stuck in the root. It has this line:
$appPath = "http://localhost/MyApplication/";
It is part of the project, but excluded from source control. So various devs just set it to whatever they want and we make sure to never deploy it. This is probably the effort the OP is trying to skip (as I skipped with my asp.net code).
I hope this helps lead to an answer, or provides a work-around for PHPers out there.

To convert an absolute path to a relative path in php

I would like to convert an absolute path into a relative path.
This is what the current absolute code looks like
$sitefolder = "/wmt/";
$adminfolder = "/wmt/admin/";
$site_path = $_SERVER["DOCUMENT_ROOT"]."$sitefolder";
// $site_path ="//winam/refiller/";
$admin_path = $site_path . "$adminfolder";
$site_url = "http://".$_SERVER["HTTP_HOST"]."$sitefolder";
$admin_url = $site_url . "$adminfolder";
$site_images = $site_url."images/";
so for example, the code above would give you a site url of
www.temiremi.com/wmt
and accessing a file in that would give
www.temiremi.com/wmt/folder1.php
What I want to do is this I want to mask the temiremi.com/wmt and replace it with dolapo.com, so it would say www.dolapo.com/folder1.php
Is it possible to do that with relative path.
I'm a beginner coder. I paid someone to do something for me, but I want to get into doing it myself now.
The problem is that your question, although it seems very specific, is missing some crucial details.
If the script you posted is always being executed, and you always want it to go to delapo.com instead of temiremi.com, then all you would have to do is replace
$site_url = "http://".$_SERVER["HTTP_HOST"]."$sitefolder";
with
$site_url = "http://www.delapo.com/$sitefolder";
The $_SERVER["HTTP_HOST"] variable will return the domain for whatever site was requested. Therefore, if the user goes to www.temiremi.com/myscript.php (assuming that the script you posted is saved in a file called myscript.php) then $_SERVER["HTTP_HOST"] just returns www.temiremi.com.
On the other hand, you may not always be redirecting to the same domain or you may want the script to be able to adapt easily to go to different domains without having to dig through layers of code in the future. If this is the case, then you will need a way to figuring out what domain you wish to link to.
If you have a website hosted on temiremi.com but you want it to look like you are accessing from delapo.com, this is not an issue that can be resolved by PHP. You would have to have delapo.com redirect to temiremi.com or simply host on delapo.com in the first place.
If the situation is the other way around and you want a website hosted on delapo.com but you want users to access temiremi.com, then simply re-writing links isn't a sophisticated enough answer. This strategy would redirect the user to the other domain when they clicked the link. Instead you would need to have a proxy set up to forward the information. Proxy scripts vary in complexity, but the simplest one would be something like:
<?php
$site = file_get_contents("http://www.delapo.com/$sitefolder");
echo $site;
?>
So you see, we really need a little more information on why you need this script and its intended purpose in order to assist you.
This would be a lot easier to do in the HTTP server configuration. For example, using Apache's VHost
I'm not really sure what you're going for bc this doesnt look like absolute path to relative path, but rather one absolute path to another.
Are you always trying to simply change "www.temiremi.com/wmt/" to "delapo.com"? If thats the case, you just want simple string replacement rather than $_SERVER variables or path functions.
$alteredPath = str_replace("www.temiremi.com/wmt/", "delapo.com", $oldPath);
OR
$alteredParth "www.delapo.com/" . basename($oldPath)
If i misunderstand please explain, I don't know if you need this to be more robust/generic, and you kind of threw me for a loop with "dolapo.com" (when i first thought your title, i originally thought of comparing path to a value from $_SERVER and removing common parts,)
And as mentioned, if you are just trying to make the URL displayed the the user (in the address bar or links) look different PHP can't do this.

Redirect files to simple form before downloading

Hi I am trying to redirect all links to any pdf file in my site to a page with a form in it that collects user info before they can proceed to download/view the pdf.
Eg
I want to redirect *.pdf files in web site to request.php?file=name_of_pdf_being_redirected
Where request.php is the page with the form on it asking for a few details before proceeding.
All pdf's in the site are held inside /pdf folder.
Any ideas?
EDIT: sorry I'm using Apache on the server.
OK I'M GETTING THERE:
I have it working now using:
RewriteEngine on
RewriteRule ^pdf/(.+.pdf)$ request.php?file=/$1 [R]
But now when it goes to the download page when i want to let the person actually download the file my new rule is spitting the download link back to the form :-P haha so is there anyway to let it download the file once the form has been submitted and you're on download.php?
Ideas? You could start by telling us which web/app server you're using, that might help :-)
In Apache, you should be able to use a RewriteRule to morph the request into a different form. For example, turning /pub/docs/x.pdf into request.php?file=/pub/docs/x.pdf could be done with something like:
RewriteRule ^/pdf/(.*)\.pdf/ request.php?file=/$1.pdf
Keep in mind this is from memory (six years since I touched Apache and still clean :-), the format may be slightly different.
Update:
Now you've got that sorted, here's a couple of options for your next problem.
1/ Rename the PDFs to have a different extension so that they're not caught by the rewrite rule. They should be configured to push out the same MIME type to the client so that they open in the clients choice of viewer.
2/ Do the download as part of the script as well, not as a direct access to the PDF. Since the submission of the form is a HTTP request, you should be able to answer it immediately with the PDF contents rather than re-directing them again to the download page.
That second option would be my choice since it:
stops people figuring out they can get to the PDFs just by requesting xx.pdfx instead of xx.pdf.
makes it quicker for the person to get the PDF (they don't have to click on the link again).
You can try this:
Move your files to a folder "outside" your web root so that no one can access it thru a browser
Use sessions to detect whether a person has completed the form or not
Use a php powered file download script. In its naivest form, it might look like this:
if ( isset( $_SESSION[ 'OK_TO_DOWNLOAD' ] ) == false )
{
header( "Location: must_fill_this_first.php" );
exit( 0 );
}
header( "Content-type: application/pdf" );
// double check the above, google it as i am not sure
echo file_get_contents( 'some_directory_inaccessible_thru_www/' . $_GET[ 'pdf_name' ] );
// ideally a binary-safe function needs to be used above
This is a tried and tested technique I used on a website. The code example is a draft outline and needs refinement.
Note, my answer is with respect to a .NET website, but I'm sure the same constructs exist somewhere in PHP.
I would have an HTTPModule with a path of *.pdf that simply does a Response.Redirect to request.php?...etc (in my case request.aspx) And then in the event handler for the button click on that page, when you know which pdf to display and that they're authorized, simple do a Response.ContentType = [MIME type of pdf], and then Response.WriteFile(pdfFile), and finally Response.End().
There are other things you can add to make it better, such as filesize, etc. But in the minimal case, this would work. If you want the code for it in C# I could come up with something in about 3 minutes, but in PHP i'm quite lost. I'd start out looking for HTTPModules and how to write them in PHP.
Googling for "PHP HTTPModule" leads to this: Equivalent of ASP.NET HttpModules in PHP so, I may be a little wrong, but hopefully that's a starting point.
Use an .htaccess file if you're using an Apache web server. You'll need to make certain that you have mod_rewrite enabled, but once you do you can rewrite all files using these two simple lines:
RewriteEngine On
RewriteRule ^.pdf$ /rewrite.php [NC,L]
If you are using IIS, you can accomplish something similar using ISAPI_Rewrite.
Your other alternative is to place your pdf's inside of a directory that is not publicly accessible and then any request made for a pdf resource would return an access denied error and the files could only be accessed through the appropriate download script.
if($user==authenticated){
//set pdf headers
echo file_get_contents('actual.pdf');
no mod re-writes, hides actual source and is what i normally do - hope this helps

Categories