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.
Related
I have four files named comma separated in one field in database like this file1,file2,file3,file4. It may change depending on files uploading. User can upload maximum 4 files, minimum one file. But I was not able to get it. I used explode but it's taking too long.
I am using this code:
$imagefiles = $row["imagefiles"];
$cutjobs = explode(",", $imagefiles);
$cutjobs1 = count($cutjobs);
$image1 = $cutjobs[0];
$image2 = $cutjobs[1];
$image3 = $cutjobs[2];
$image4 = $cutjobs[3];
if (empty($image1)) {
$imagefiles1 = "";
} else {
$imagefiles1 = 'http://projects.santabantathegreat.com/glassicam/uploads/'.$registerid.
"/".$viewjobsid.
"/".$image1;
}
if (empty($image2)) {
$imagefiles2 = "";
} else {
$imagefiles2 = 'http://projects.santabantathegreat.com/glassicam/uploads/'.$registerid.
"/".$viewjobsid.
"/".$image2;
}
if (empty($image3)) {
$imagefiles3 = "";
} else {
$imagefiles3 = 'http://projects.santabantathegreat.com/glassicam/uploads/'.$registerid.
"/".$viewjobsid.
"/".$image3;
}
if (empty($image4)) {
$imagefiles4 = "";
} else {
$imagefiles4 = 'http://projects.santabantathegreat.com/glassicam/uploads/'.$registerid.
"/".$viewjobsid.
"/".$image4;
}
}
$data[] = array( 'imagearray' => array($imagefiles, $imagefiles1, $imagefiles2, $imagefiles3));
}
echo json_encode($data);
}
I am getting output like this :
[{"imagearray":["http:\/\/projects.santabantathegreat.com\/glassicam\/uploads\/60\/30\/file1.jpg","http:\/\/projects.santabantathegreat.com\/glassicam\/uploads\/60\/30\/file2.jpg",""]}]
If you see this imageArray last one is getting "" that means some in file1, file2, file3, file4 one name is missing so I want to show if any filename is not there means I don't want to show null values with ""
i have a field with file1,file2,file3,file4 so times we will have file1,file3 then remaining will not there so i want to count file name separated with commas and if file1 is there is should print that if file3 is there not then it shouldn't show with ""
You could have used split(), but its deprecated in PHP 5.3.0. So, instead you are left with:
explode() which is substantially faster because it doesn't split based on a regular expression, so the string doesn't have to be analyzed by the regex parser.
or
preg_split() which is faster and uses PCRE regular expressions for regex splits.
With preg_split() you could do:
<?php
$encoded_data = json_encode($data);
$images = preg_split('/,/', $encoded_data->imagearray);
?>
I would say that explode() is more appropriate for this.
<?php
$encoded_data = json_encode($data);
$images = explode(',', $encoded_data->imagearray);
print_r($images);
?>
Resources: What is the difference between split() and explode()?
You shouldn't have empty values in your array in the first place. But if you still have any empty values you could use preg_split() something like this one here.
Similarly you can use array_filter() to handle removal of values (null, false,'',0):
print_r(array_filter($images));
There are so many answers here in this forum that do exactly what you are asking: Remove empty array elements, Delete empty value element in array.
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").
i have this list on name.txt file :
"name1":"Robert"
"name2":"George"
"name3":"Flophin"
"name4":"Fred"
in a web page i need a php code that takes only the name of the person by the name 1 2 3 4 id.
I've use this in test.php?id=name2
$Text=file_get_contents("./name.txt");
if(isset($_GET["id"])){
$id = $_GET["id"];
$regex = "/".$id."=\'([^\']+)\'/";
preg_match_all($regex,$Text,$Match);
$fid=$Match[1][0];
echo $fid;
} else {
echo "";
}
The result should be George ,
how do i change this to work??
Mabe is another way to do this more simply?
$file=file('name.txt');
$id = $_GET["id"];
$result=explode(':',$file[$id-1]);
echo $result[1];
Edit: $result[1] if you want just name.
Heres an ugly solution to your problem, which you can loop trough.
And Here's a reference to the explode function.
<?php
$text = '"name1":"Robert"
"name2":"George"
"name3":"Flophin"
"name4":"Fred"';
$x = explode("\n", $text);
$x = explode(':', $x[1]);
echo $x[1];
Load the text file into an array; see Text Files and Arrays in PHP as an example.
Once the array is loaded you can reference the array value directly, e.g. $fid = $myArray['name' . $id]. Please refer to PHP how to get value from array if key is in a variable as an example.
I am trying to read a file as a string and return it to the client to be executed as javascript code in order to save it as a variable. Like so
<?php
$fileName = 'target.js';
$codeAsString = file_get_contents($fileName);
$script = 'var code=\'' . $codeAsString . '\'';
echo $script;
?>
Once returned, I want the variable code to have a string representation of the contents of target.js. However, it isn't working. I suspect it has to do with new line characters and single/double quotes... In Python they have a multi line quote
"""This
is
a "multi"
line
'quote'
"""
Is there anything like this in Javascript/php? I can't even wrap my head around whether I need the single quotes around $codeAsString when appending it to $script. Do I have to manually go in and prepend backslashes before all quotes, double quotes, back slashes...Surely they have helper functions for this
thanks.
json_encode is your friend...
<?php
$fileName = 'target.js';
$codeAsString = file_get_contents($fileName);
$script = 'var code= '.json_encode($codeAsString) .';';
echo $script;
?>
Use PHP function json_encode.
I was wondering what you'd do if you wanted to link to a directory index file if it existed?
So far what I have is this
$filename = './../season/6/index.php';
if (file_exists($filename)) {
echo '<div id="lesson">
season 6
</div>';
} else {
echo "";
}
However, what I want now is something like this
$lesson="5";
$lesson++; // (or someway to increase it)
$filename = './../season/$lesson/index.php';
if (file_exists($filename)) {
echo '
season $lesson
';
} else {
echo "";
}
however, I know that php won't allow ALL Those backslashes in that echo or apostrophe. How can I compensate? Should I use String concatenation?
As an example:
<?php
foreach(range(1,10) as $lesson){
$filename = "./../season/$lesson/index.php";
echo $filename;
}
?>
A live demo:
http://www.ideone.com/pemRv
Essentially two things here:
1) Use double quotes to have variable interpolation.
2) Just have $lesson be an integer, so you can increment the value.
Variable interpolation only occurs in double quoted strings, you are using single quoted.
Also, your else { ... } is unnecessary.
However, it sounds like this method could be improved. What upper bound will you go to before you stop checking? This will be a lot of unnecessary overhead.