PHP include dynamically generated filename? - php

while($x<=$num_of_cpkgs){
$cpkg_navtray = '\'' . $cpkg_array[$x] . '.html\'';
include $cpkg_navtray;
$x++;
}
I'm getting an error when I try this ... it works when I manually include the same value however ... for example, if $cpkg_navtray = 'test.html', I'm getting an error; however, when I directly include 'test.html' like include 'test.html';, it works. Why?

You dont need quotes in filename variable -
$cpkg_navtray = $cpkg_array[$x] . '.html';

Looking same Question but tag and desire different: Jut do these, just a simple concatenate.
while($x<=$num_of_cpkgs){
$cpkg_navtray = $cpkg_array[$x].'.html';
include $cpkg_navtray;
$x++;
}

Related

PHP include statement containing echoed PHP variable

I have the required ID variable from this, (there are 1-6 possible values):
$new_product['ID'] =$row[2];
What I need is to echo a separate 'php-include' depending on this variable, so something like:
<?php include 'includes/size/prod/echo $row[2].php'; ?>
which would display, includes/size/prod/1.php, includes/size/prod/2.php etc
I don't understand how to phrase the 'echo' within the php.
There are a few ways:
//Concatenate array value in double quotes:
<?php include "includes/size/prod/{$row[2]}.php"; ?>
//Concatenate array value outside of quotes:
<?php include "includes/size/prod/".$row[2].".php"; ?>
//or, using single quotes:
<?php include 'includes/size/prod/'.$row[2].'.php'; ?>
//Concatenate variable (not array value) in double quotes:
<?php $page = $row[2]; include "includes/size/prod/$page.php"; ?>
See:
http://php.net/manual/en/language.operators.string.php
PHP - concatenate or directly insert variables in string
PHP include with a variable in the path
It's very dangerous to include your PHP files with this technic !!
You must prevent this by doing at least a control of included files are PHP
Now to respond to your question:
<?php
// ? $row2 contains more than 1 php file to include ?
// they are seperated by comma ?
$phpToInclude = NULL;
define(TEMPLATE_INCLUDE, 'includes/size/prod/');
if (isset($row[2])) {
$phpToInclude = explode($row[2], ',');
}
if (!is_null($phpToInclude)) {
foreach($phpToInclude as $f) {
$include = sprintf(TEMPLATE_INCLUDE . '%s', $f);
if (is_file($include)) {
// add validator here !!
include ($include);
}
else {
// file not exist, log your error
}
}
}
?>
dear use following working code
$row[2] = '';
$file_name = !empty($row[2])?$row[2]:'default';
$include_file = "includes/size/prod/".$file_name.".php";
include($include_file);
Things get evaluated in double quotes but not in single:
$var = "rajveer gangwar";
echo '$var is musician'; // $s is musician.
echo "$var is musician."; //rajveer gangwar is musician.
So better to use double quotes
Example:
// Get your dynamic file name in a single variable.
$file_name = !empty($row[0]) ? $row[0] : "default_file";
$include_file = "includes/size/prod/$file_name.php";
include($include_file);
You can use the dots for separating a string:
So for instance:
$path = 'includes/size/prod/'.$row[2].'.php';
include '$path';
Or you can put it in a variable:
$path = $row[2];
include 'includes/size/prod/$path.php';
Php is able to evaluate a variable within a string.

How To Base PHP Include Off of Current Pagename?

I'm currently hardcoding an include into my pages and its a lot of work everytime I want to create a new page. Currently, my url is like this:
http://example.com/folder/one-z-pagename.php?var1=one&var2=two
and in one-z-pagename.php I have an include that looks like this:
include("lander-a-pagename.php");
So what I want to do is instead of hardcoding the file into the page like above, I want to grab one-z-pagename.php without the ?var1=one&var2=two from the url, erase the first 6 characters which is one-z- and replace it with lander-a-.
How do I do something like this?
use parse_url and basename to get filename then str_replace
$url= parse_url('http://example.com/folder/one-z-pagename.php?var1=one&var2=two');
$file = basename($url['path']);
$newfile = str_replace('one-z-','lander-a-',$file);
echo $newfile;
output : lander-a-pagename.php
It can be achive by many method, have a look on below two methods:
Method 1:
$current_script_name = basename(__FILE__);
$include_script_name = 'lander-a-'.substr($current_script_name, 6);
Method 2:
$current_script_name = $_SERVER['SCRIPT_NAME'];
$current_script_name = end(explode('/', $current_script_name));
$include_script_name = 'lander-a-'.substr($current_script_name, 6);
//OR
$include_script_name = str_replace('one-z', 'lander-a', $current_script_name);
variable $include_script_name contains required filename which you want to include.
Hope this will help.

PHP save form data to file

I am trying to save form data to a file, this is what I have so far:
if(isset($_POST['connect'])) {
$host = "$dbuser=" . $_POST["host"];
$root = $_POST["root"];
$pass = $_POST["pass"];
}
I'm trying to write the form data to a file with the variable $dbhost="Formdata";
and I get this error:
Parse error: syntax error, unexpected 'echo' (T_ECHO) in C:\xampp\htdocs\dev\admin2.0\install\index.php on line 55`
$host = '$dbhost="' . $_POST["host"] . '"';
echo $host;
Try this. You don't need to echo unless you are attempting to print to the page.
I'm not really sure what you trying to accomplish, but if you want to write some data to a file (for example), you could try something like this:
<?php
if (isset($_POST['connect'])) {
file_put_contents("file.txt", "$dbuser={$_POST["host"]}");
}
Also keep in mind that notation:
"$dbuser="
will expand variable in place (1), if a variable $dbuser exists, because you are using double quotes.
With single quotes you will need string concatenation operator . like this:
<?php
if (isset($_POST['connect'])) {
file_put_contents("file.txt", '$dbuser=' . $_POST["host"]);
}
But, if this all about plain debug, maybe print_r($_POST); will be sufficient?
Hope this helps!
PHP Reference: Strings (please read section "Variable parsing").

Is it secure to use "require" with GET/POST data?

Is it secure to use the following code:
require($_SERVER['DOCUMENT_ROOT'] . "/pages/" . $_GET['page'] . ".php")
No, it is not secure. Why?
Because sequence of two dots /../ means one directory back and the attacker could potentially include anything on your system, even above $_SERVER['DOCUMENT_ROOT']. (In an unfortunate configuration that means secret/sensitive OS config files.)
You have to IF or SWITCH for the allowed values to prevent malicious input. Example:
switch($_GET['page']) {
case 'welcome': $page='welcome';
case 'shop': $page='shop';
default: $page='index';
}
require($_SERVER['DOCUMENT_ROOT'] . "/pages/" . $page . ".php")
Also check out in_array() for a little easier filtration.
StackOverflow has a useful Q&A for how to sanitize user input with PHP. It's a few years old, but the principles haven't changed at all.
The quick answer is: if you can avoid the problem in the first place, you're better off.
Show us how you're trying to use this, and we may be able to offer suggestions for improvement.
It's not secure. You can use array with allowed values.
For example
$allowed_pages = array('index', 'test', 'my_page')
if (!in_array($_GET['page'], $allowed_pages)){
echo 'good bye';
die();
} else {
//
}
If you trust all the files in the pages dir try:
if (in_array($_GET['page'],glob("/pages/*.php"))) {
require($_SERVER['DOCUMENT_ROOT'] . "/pages/" . $_GET['page'] . ".php");
} else echo "Nice try hacker!";
Here's another solution using parts of a function I use to clean uploaded filenames:
OPTION #2 thanks Daniel, Rok!
$page = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_GET['page']);
$filename = $_SERVER['DOCUMENT_ROOT'] . "/pages/" . str_replace("/",'',$page) . ".php";
if (file_exists($filename)) {
require($filename);
} else echo "Nice try hacker!";
Note that this will only work if there are no special characters in your file names
use regExp to check your $_GET['page']!

Cannot call PHP function even though it is "included"

I've started using PHP lately... all is good except one thing.
I am trying to call a function from another php file... but it's not working.
It's probably really simple, but I haven't found anything useful to solve it.
I've used "required_once " but it still does not work.
Does anyone know where I'm going wrong?
<?php
require_once "/Applications/MAMP/htdocs/me/database_functions.php";
require_once "/Applications/MAMP/htdocs/me/encode_decode.php";
if (isset($_POST['url']) && $_POST['url'] != "http://")
{
//Get the url posted
$long_url = $_POST['url'];
//Create record in long_url table and return it's id
$long_id = create_long_url($long_url);
Everything works so far.. But
the problem is this next function call.. it doesn't even go into the function.
$short_url = $encode($long_id);
}...............etc...
encode_decode.php looks a bit like this...
<?php //encode_decode.php
function encode($number)
{
echo "<br />in encode";
//Encode numer to 6 char
$s = strtr(rtrim(base64_encode(pack('i', $number)), '='), '+/', '-_');
echo $s;
return $s;
}
Any help is greatly appreciated...
You don't need the $ before your function call
$short_url = $encode($long_id);
should be
$short_url = encode($long_id);
The dollar sign would only be needed if the function is stored in a variable (which it isn't).
$short_url = encode($long_id);
remove the dollar sign from in front of the function. a dollar sign in PHP indicates a variable
As all others have said:
$short_url = encode($long_id);
But also you could clean up your require_once statements:
define('DS', DIRECTORY_SEPARATOR);
require_once(dirname(__FILE__) . DS . 'database_functions.php');
require_once(dirname(__FILE__) . DS . 'encode_decode.php');
Instead of the define() and reference to DS you could of course just prefix your file names with '/'. This also assumes your files are relative (but if not just prefix the folder to the filename) - this would make sure you don't get any problems if you move your site from different servers (i.e., testing, production).

Categories