Im currently trying to get a link:
<a href='?p=bid?Sale_ID=$Sale_ID'>BID</a>
to work but I keep getting a "Page you are requesting doesn´t exist" message, this page works if i use this link:
<a href='include/bid.php?Sale_ID=$Sale_ID'>BID</a>
this leads me to believe that my problem lies with the isset im using to include pages on link:
<?php
if (isset($_GET['p']) && $_GET['p'] != "") {
$p = $_GET['p'];
if (file_exists('include/'.$p.'.php')) {
#include ('include/'.$p.'.php');
} elseif (!file_exists('include/'.$p.'.php')) {
echo 'Page you are requesting doesn´t exist<br><br>';
}
} else {
#include ('include/login-form.php');
}
?>
Ive tried adding another isset replacing p with q which just throws my pages in to dissaray.
So my question is, is there a way around this?
Thanks
You have two question marks here:
?p=bid?Sale_ID=$Sale_ID
Multiple querystring parameters are separated by ampersand:
?p=bid&Sale_ID=$Sale_ID
The query string you show: ?p=bid?Sale_ID=$Sale_ID is not valid. The structure of a URL with a string is:
filename.extension?first_parameter=first_value&second_parameter=second_value
So, if you want p to indicate which page:
?p=bid&Sale_ID=$Sale_ID
.. use the ampersand (&) to separate your query string values.
Also, please note that the approach you are using to include a file is insecure. What if I sent this:
?p=../../.htpasswd&Sale_ID=0
An attacker could use this method to output the contents of files that you do not wish to expose to the public. Make sure you are checking the value of this variable more carefully before blinding including the file.
I also wants to warn you against using the error suppressor (#). Errors are your friends! You want to know exactly what happens in your code, using the error suppressor prevents critical problems from being brought to your attention. Really -- never, ever use the error suppressor. Instead of #include, use include
I suggest something more like this:
$file_exists = false;
$page = false;
if (
isset($_GET['p']) &&
strlen(trim($_GET['p'])) > 0
){
$page = preg_replace("/[^a-zA-Z0-9 ]/", "", $_GET['p']);
$page = str_replace(" ", "-", $page);
$file_exists = file_exists('include/'.$page.'.php');
if ($file_exists) {
include ('include/'.$page.'.php');
} else {
$page = false;
echo 'Page you are requesting doesn´t exist<br><br>';
}
}
if (!$file_exists ||$page === false)
include ('include/login-form.php');
The first part of the code ensures that the query string value exists and has some content. Then it cleans out any non-alphanumeric characters (this helps prevent exploitation). Then, we check to see if it exists, storing that result in a variable so we can use it again.
If the page exists, the file is included. If not, a "page not found" message is output, and the login form file is included. If no page is specified in the query string, the login form file is included.
Documentation
$_GET - http://php.net/manual/en/reserved.variables.get.php
Query string on Wikipedia - http://en.wikipedia.org/wiki/Query_string
Exploiting PHP File Inclusion - an article about security when using include and $_GET - http://websec.wordpress.com/2010/02/22/exploiting-php-file-inclusion-overview/
preg_replace - http://php.net/manual/en/function.preg-replace.php
str_replace - http://php.net/manual/en/function.str-replace.php
?p=bid "redirects" to your default file, usually index.php. You want it to work in bid.php.
You can set the default file in apache with:
DirectoryIndex index.php bid.php
The other problem is you use multiple ? signs.
?p=bid&Sale_ID=$Sale_ID would work a lot better
Keep in mind that file_exists does not use the include path, so you should be doing this:
if (file_exists( get_include_path() . 'include/'.$p.'.php')) {
More info:
http://ca2.php.net/manual/en/function.file-exists.php
Related
The title is self-explanatory. Within PHP, I create a PHP file, add some PHP and HTML code to it, then close it. The problem is that PHP files take all PHP code found and converts it to emptiness. Here's the last thing I tried.
$phpfile=fopen('backupfile.php',"r");
$phptext=fgets($phpfile);
if(stristr($link, 'http://') === FALSE) {
fwrite($file2,$phptext."<meta http-equiv='refresh' content='0; URL=http://".$link." '/>");
}else{
fwrite($file2,$phptext."<meta http-equiv='refresh' content='0; URL=".$link." '/>");
}
phpfile includes the following:
<?php $file=fopen("/num","r"); $bar=fgets($file); $bar=$bar+1; $file=fopen("/num","w"); fwrite($file,$bar); ?>
As said before, it simply doesn't add that to the file.
I tried htmlentities but that made the PHP code visible to the page and not hardwired into the file.
Thanks for any help.
Rewrite your code using only (escaped) single quotes. Using double quotes will cause the embedded php to be interpreted.
Its not really about writing code inside a file, you can bridge this idea using a Database.
You could have a standard directory set-up, ie: help documents.
Inside that directory, have a file: you can simply query the Database for pages, integrate a permalink to each page using a get value and then show content from that value (maybe a page ID).
Of-course, you'll need to implement standards and security - ie, if anyone can create pages - ensure only certain html can be added or BBCode.
I hope this widens your idea; this is how most forums, posts, comments ect.. work.
Step 1:
Code clarification:
$link = "some like address";
if(mb_strpos($link, 'http://') === FALSE || mb_strpos($link, 'http://') > 0) {
$link = "http://".$link;
}
$phptext = PHP_EOL."<meta http-equiv='refresh' content='0; URL=".$link." '/>";
file_put_contents('backupfile.php', $phptext, FILE_APPEND);
Ok so what did I do here:
Checking with multibyte string checks if HTTP:// appears in the string, checking at the start is irrelivant because if it's not at the start it's an invalid HTTP request anyway, and you make no checks for this in the code provided.
Once checked, the $link value is updated.
Then use file_put_content to append what is in the string into the existing file. If the file does not exist then it will be created.
Edit:
It is not clear from your question but if you want $link saved in the string then write the link as follows with single quotes:
$phptext = PHP_EOL.'<meta http-equiv="refresh" content="0; URL=$link"/>';
Yesterday I asked a question about how to include files passed in via the URL, and someone give me this:
if (isset($_GET['file'])){
include($_GET['file'].'.php');
}
But one of the answers told me to do something with this to avoid possible attacks from hackers or something like that. The problem is that I don't understand how to do it myself.
He said I should do something like this:
$pages_array=('home','services','contact').
And then check the GET var:
if(!in_array($_GET['page'], $pages_array) { die(); }
What does this do, and how do I integrate it into my original code above?
Your original code is looking for a file parameter in the URL, and then including whatever file was passed in. So if somebody goes to your PHP page and adds ?file=something.txt to the URL, you'll include the contents of something.txt in your output.
The problem with this is that anybody can manually modify the URL to try to include whatever file they want - letting them see files on your system that should be private.
The solution is to have a list of allowed filenames, like this:
$pages = array('home', 'services', 'contact');
And then before you include the file, check that it's one of the allowed filenames first.
$pages = array('home', 'services', 'contact');
if (isset($_GET['file'])){
if (!in_array($_GET['file'], $pages_array)) {
exit('Not permitted to view this page');
}
include($_GET['file'].'.php');
}
We're using a PHP array to define the list of allowed pages, checking if our page is in the list with the in_array() function, and then stopping all script execution if it's not in the list with the exit() function.
The code checks the GET information passed from the browser to your PHP page by making sure that the page name is present in your $pages_array.
As long as you list all of the pages in your $pages_array, the code will execute. If the page is not in your array list, then it will die and not be executed.
When using GET it is always beneficial to validate the code sent in this way, as arbitrary statements can be sent and executed without validation.
The code, in this instance, is being validated - so you have taken the necessary steps; as long as there is nothing more to the code that you haven't submitted.
Correct code
$pages_array=array('home','services','contact');
You almost answered your own question...
Except this line becomes...
$pages_array=array('home','services','contact');
Instead of what you had...
$pages_array=('home','services','contact').
//change the variable array declaration
$newArray = array('home','services','contact');
Just do an else statement in your if like
else {
//include your file
include($_GET['page'].'.php');
}
Basically, Your syntax for an array definition is wrong, but also why die() if $_GET['file'] is not set? would it not be better if you reverted to a default so as to fail silently.
Using in_array()
<?php
$pages_array = array('home','services','contact');
if(isset($_GET['file']) && in_array($_GET['file'], $pages_array)){
include($_GET['file'].'.php');
}else{
include('home.php');
}
?>
Or even using switch() with hard coded values.
<?php
$page = isset($_GET['file']) ? $_GET['file'] : 'home';
switch($page){
case "home" : include($page.'.php'); break;
case "services" : include($page.'.php'); break;
case "contact" : include($page.'.php'); break;
default:
include('home.php');
break;
}
?>
$pages=array('home','services','contact');
if(isset($_GET['page']))
{
$page=$_GET['page'];
if(!in_array($page,$pages))
{
die ('');
}
else {
include($page.'.php');
}
}
So, your links will look like:
yoursite.com/index.php?page=home -> with this tool:
http://www.generateit.net/mod-rewrite/
you can make nicer URL's.
I want to show on my site an element depending on my site's url.
Currently i have the following code:
<?php
if(URL matches)
{
echo $something;
}
else
{
echo $otherthing;
}
?>
I wanted to know how do I get the URL on the if condition, because I need to have only one php archive to show on many diferent pages
EDIT: The solution provided by Rixhers Ajazi doesnt work for me, when i use ur code i get the same URI for both of my pages, so the if sentence always goes by the else side, is any way to get the exact string u can see on the browser to the PHP code
http://img339.imageshack.us/img339/5774/sinttulocbe.png
This is the place where it changes but, the URL i get on both sides is equal, im a little bit confused
To get the URL, use:
$url = http://$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
Use following syntax with URL
http://mysite.com/index.php?var1=val&var2=val
Now you can get the values of variables in your $_GET variable and use in if condition like
if($_GET['var1'])
You can do so by using the $_SERVER method like so :
$url = $_SERVER['PHP_SELF']; or $url = $_SERVER['SERVER_NAME'];
Read up on this more here
if($url == 'WHATEVER')
{
echo $something;
}
else
{
echo $otherthing;
}
?>
You can use different variables, e.g., $_SERVER["PHP_SELF"], or $_SERVER["REQUEST_URI"]. The first one contains the path after the server name and until a possible ? in the URL (the part with the GET parameters is excluded). The second one contains also the GET parameters. You can also retrieve the hostname used to connect to the server (in case you have a virtual host situation) using $_SERVER["HTTP_HOST"]. Therefore by concatenating all these you can reconstruct the full URL (if you really need it, maybe the script name is enough).
When I use the following PHP code:
$id = $_GET['page']; $page = include ($id.'.php'); echo $page;
The code within the $id.php file is returned, however there is a "1" appended to it, any idea why this is happening?
include() will return boolean TRUE if the file was successfully included. You then echo out that true value, which is printed as a 1.
Of note: never directly use user-provided data ($_GET['page']) in file system operations. It's a hideious security risk. You've at least got .php being appended so it's not quite as large a gaping hole, but still... don't do this.
You shouldn't echo a page like that.
include() is used to import the document onto your current working file.
By using $page = include ($id.'.php');, you are assigning boolean value to $page
This will hold the success status of the include() statement
If the page load successfully, it give true, whose numeric value is 1
If the load was unsuccessfully, it gives false, whose numeric value is 0
However, the way you are using is not entirely incorrect
For example: Create a page Test.php to return a value at the end
$t = "some text";
return $t;
Then you will able to use it to echo
echo include("test.php"); //outputs "some text"
I suggest you tead the documenation for complete guide
because the 1 is the return code of the include(), which you are saving in the $page variable.
The code within $id.php is returned when you do the include(), the only thing your 'echo' is printing is the 1
Yes! When you include, you're just telling PHP to parse the additional file as well. The variable you've set--$page-- just contains the return value of the include() function. Since it's 1, I'd say you included the other file successfully.
On a related note, it's generally (meaning, almost never) a good idea to include an arbitrary file based on un-parsed parameters from a user request. By manipulating the value of page passed to your script, a theoretical attacker could get your machine to execute any PHP file in the system--a dangerous proposition!
Most probably because include will return true or false (0 or 1). Actually you include the page content and then echo $page. This will print "1".
Hope you got it. Don't echo $page at the end. Just use include.
I'm trying to pass a URL as a url parameter in php but when I try to get this parameter I get nothing
I'm using the following url form:
http://localhost/dispatch.php?link=www.google.com
I'm trying to get it through:
$_GET['link'];
But nothing returned. What is the problem?
$_GET is not a function or language construct—it's just a variable (an array). Try:
<?php
echo $_GET['link'];
In particular, it's a superglobal: a built-in variable that's populated by PHP and is available in all scopes (you can use it from inside a function without the global keyword).
Since the variable might not exist, you could (and should) ensure your code does not trigger notices with:
<?php
if (isset($_GET['link'])) {
echo $_GET['link'];
} else {
// Fallback behaviour goes here
}
Alternatively, if you want to skip manual index checks and maybe add further validations you can use the filter extension:
<?php
echo filter_input(INPUT_GET, 'link', FILTER_SANITIZE_URL);
Last but not least, you can use the null coalescing operator (available since PHP/7.0) to handle missing parameters:
echo $_GET['link'] ?? 'Fallback value';
Please post your code,
<?php
echo $_GET['link'];
?>
or
<?php
echo $_REQUEST['link'];
?>
do work...
Use this:
$parameter = $_SERVER['QUERY_STRING'];
echo $parameter;
Or just use:
$parameter = $_GET['link'];
echo $parameter ;
To make sure you're always on the safe side, without getting all kinds of unwanted code insertion use FILTERS:
echo filter_input(INPUT_GET,"link",FILTER_SANITIZE_STRING);
More reading on php.net function filter_input, or check out the description of the different filters
The accepted answer is good. But if you have a scenario like this:
http://www.mydomain.me/index.php?state=California.php#Berkeley
You can treat the named anchor as a query string like this:
http://www.mydomain.me/index.php?state=California.php&city=Berkeley
Then, access it like this:
$Url = $_GET['state']."#".$_GET['city'];
I was getting nothing for any $_GET["..."] (e.g print_r($_GET) gave an empty array) yet $_SERVER['REQUEST_URI'] showed stuff should be there. In the end it turned out that I was only getting to the web page because my .htaccess was redirecting it there (my 404 handler was the same .php file, and I had made a typo in the browser when testing).
Simply changing the name meant the same php code worked once the 404 redirection wasn't kicking in!
So there are ways $_GET can return nothing even though the php code may be correct.
$Query_String = explode("&", explode("?", $_SERVER['REQUEST_URI'])[1] );
var_dump($Query_String)
Array
(
[ 0] => link=www.google.com
)