define a variable in a query (?) - php

I have to define two variables:
<?php
$path = 'http://' . $_SERVER['SERVER_NAME'] . '/root/images/folderX/';
$files = scandir('images/folderX/');
?>
In the place of 'folderX' I should use a dynamic value, which comes from a query, like
<?php echo $row_rsQuery["item_name"];?>
How can it be done?
I'm not too familiar with php, and I will perhaps never learn it (..too old..), but I solve most of my problems with Dreamweaver, however the above problem is beyond its (and my) capabilities...

String concatenation (appending one string to another) is done via the . operator:
$files = scandir('images/'.$row_rsQuery["item_name"]);

$path = 'http://' . $_SERVER['SERVER_NAME'] . '/root/images/'.$row_rsQuery["item_name"].'/';
$files = scandir('images/'.$row_rsQuery["item_name"].'/');

Related

Storing values to a variable php

I have this php code in which i attempted to store a value from three select input into a one variable. it is not working. what is the right way? or is that possible?
$REGDATE = mysql_real_escape_string ($_POST["month"]) "/" ($_POST["day"]) "/" ($_POST["year"]);
What you're looking for is to concatenate the strings
mysql_real_escape_string(
$_POST["month"] . "/" .
$_POST["day"] . "/" .
$_POST["year"] )
As mentioned there are better ways of doing this, but for what you're doing you need to join the strings together.

Clean way to write urls instead of concatenation

I have been finding myself doing URLs like this:
$link = base_url('post') . '/' . $post_id . '/' . $slug . '/page/' . $page_num;
To form http://example.com/post/10/some-post-name/page/1
Needless to say, it's pretty messy, but I can't think of an alternative? Is there a better way write links with variables in it?
I am using Codeigniter as a framework if there is a solution involving it.
You have a few ways:
First, via sprintf:
sprintf('%s/%s/%s/page/%s', base_url('post'), $post_id, $slug, $page_num);
Or via an array implode:
implode('/', array(base_url('post'), $post_id, $slug, 'page', $page_num));
Or if you put all your values into variables, you can take advantage of string interpolation.
$url = ...;
...
"$url/$post_id/$slug/page/$page_num";
The last one is longer when you take into account the variable assignment block, but it combines succintness with readability.
Use sprintf:
$link = sprintf('%s/%d/%s/page/%d', base_url('post'), $post_id, $slug, $page_num);
You could do something like this:
$link = site_url("post/{$post_id}/{$slug}/page/{$page_num}");
You really should be using site_url() instead of base_url() for CI links. base_url() is meant for non-CI assets, like images and css.
site_url() will point to the correct front controller path, so you can update your configuration at will, and everything using that to build paths will update accordingly.
I revised my answer. Use the curly brace notation and avoid using extra functions. You can pass an array of arguments to the function, like so:
$link = site_url(array('post', $post_id, $slug, 'page', $page_num));
But working with arrays is slower. This can be useful if you need to dynamically build the url, though.
You could do it the old fashioned way with a function!
function buildlink($base_url,$post_id,$slug,$page_num)
{
return $base_url . '/' . $post_id . '/' . $slug . '/page/' . $page_num;
}
call it like this
$link = buildlink(base_url('post') ,$post_id, $slug ,$page_num);
but maybe i'm missing something

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).

How do I use a variable as an index to an array in PHP?

I have a config file which has variables based on the domain of the page (HTTP_HOST)
$c is an array.
eg $c['example.com-user'] is an entry in the config file.
I need to pass the value of $c['example.com-user'] to a function building the variable name on the fly.
I have "example.com" in $host variable
Thanks for any help!
<?php
$c['example.com-user'] = "someval";
$host = "example.com";
echo $c[ $host . '-user'];
?>
Tested, working.
$c[$host.'-user']
Assuming you only ever need the config data for the current domain, might it be easier to have a config file per domain, rather than one monster array with all of them? Then you can just load up the relevant file at the start.
If, for example your domain stored in variable $host and username in variable $user. Then, all you have to do is, use this variables as array's key:
echo $c[ $host . "-" . $user];
if $host = 'inform.com' and $user = 'simple_user', the code above will translate into:
echo $c['inform.com-simple_user'];
You see, to concatenate string, you use '.' (dot).

Categories