How to echo a variable that's not a variable yet - php

I'm struggling with the following script:
$filename = '../lang.nl.php';
$string = '<?php // language = ' . $filename . '<br>';
foreach ($_POST as $param_name => $param_val) {
$string .= "$lang=['". $param_name ."'] = ". $param_val .";\n";
}
$string .= "?>";
file_put_contents($filename, $string);
As you can see I want to create a language file with all the $_POST variables but PHP sees the $lang in $string as a variable. You can imagine that this is not what I want, it should just print $lang not whatever $lang as a variable should be. I get the error that $lang doesn't exist but I just want to literally print $lang.

Escape the $: $string .= "\$lang=['". $param_name ."'] = ". $param_val .";\n";
What is different from the original code is the backslash before $lang, which makes the $ sign an ordinary $ sign and not a marker for a variable name.

It's easier (and safer) to use var_export here:
$filename = '../lang.nl.php';
$post = var_export($_POST, true);
$code = "<?php // language = $filename;
\$lang = $post;
?>";
file_put_contents($filename, $code);
"$lang=['". $param_name ."'] = ". $param_val; is going to fail if param_val contains a quote.

Related

Get Value from nested JSON File in PHP with Placeholder

I want to write my own little translation function.
My JSON File looks like:
{
"start": {
"body": {
"headline": "Hello, world!"
}
}
}
In my PHP Frontend, i want to write just Placeholders for translated Strings. So id do
<h1><?php trans('start.body.headline'); ?></h1>
My PHP Function is simple and looks like:
function trans($string) {
if (!isset($_GET['langID']))
$lang = 'de';
else
$lang = $_GET['langID'];
$str = file_get_contents('lang/'. $lang . '.json');
$json = json_decode($str);
$string = str_replace('.', '->', $string);
echo $json->$string;
}
But I don't get a Result.
The $string in My Function is correctly:
start->body->headline
And when I write:
echo $json->start->body->headline;
I get "Hello, world".
echo $json->$string;
is the same but doesn't work. why?
becouse you are using the some variable name $string for function parameter , use the other variable name here.
$keyword = str_replace('.', '->', $string);
echo $json->{$keyword};
also you can use return method
function trans($string) {
if (!isset($_GET['langID']))
$lang = 'de';
else
$lang = $_GET['langID'];
$str = file_get_contents('lang/'. $lang . '.json');
$json = json_decode($str);
$keyword = str_replace('.', '->', $string);
return $json->{$keyword};
}
and than use short way of echo in html
<h1><?= trans('start.body.headline'); ?></h1>

How to put new line in php file fwrite

I am writing a file that is plan.php. It is a php file that I am writing. I am using \n to put the new line in that file but it is giving me save output.
Here is code:
$datetime = 'Monthly';
$expiry = '2017-08-07';
$expiryin = str_replace('ly', '',$datetime);
if($expiryin == 'Month' || $expiryin == 'Year') {
$time = '+ 1'.$expiryin.'s';
} else {
$time = '+'.$expiryin.'s';
}
$expiry_date = date('Y-m-d', strtotime($time, strtotime($expiry)));
$string = createConfigString($expiry_date);
$file = 'plan.php';
$handle = fopen($file, 'w') or die('Cannot open file: '.$file);
fwrite($handle, $string);
And the function is:
function createConfigString($dates){
global $globalval;
$str = '<?php \n\n';
$configarray = array('cust_code','Auto_Renew','admin_name');
foreach($configarray as $val){
$str .= '$data["'.$val.'"] = "'.$globalval[$val].'"; \n';
}
$str .= '\n';
return $str;
}
But it is giving the output like:
<?php .......something....\n.....\n
So my question is how to put the new line in this file.
Note: There is no error in code. I have minimized the code to put here.
As everyone already mentioned '\n' is just a two symbols string \n.
You either need a "\n" or php core constant PHP_EOL:
function createConfigString($dates){
global $globalval;
// change here
$str = '<?php ' . PHP_EOL . PHP_EOL;
$configarray = array('cust_code','Auto_Renew','admin_name');
foreach($configarray as $val){
// change here
$str .= '$data["'.$val.'"] = "'.$globalval[$val].'";' . PHP_EOL;
}
// change here
$str .= PHP_EOL;
return $str;
}
More info about interpreting special characters in strings http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
Replace ' with " ;-)
You can learn more about strings in PHP's manual: http://docs.php.net/manual/en/language.types.string.php
If you use \n inside a single-quoted string ($var = '\n';), it will be just that - the litteral string \n, and not a newline. For PHP to interpret that it should in fact be a newline, you need to use doublequotes ($var = "\n";).
$var = '\n'; // The litteral string \n
$var = "\n"; // Newline
PHP.net on double quoted strings
Live demo
\n does not work inside single quotes such as '\n'. You need to use double quotes "\n". So for your purpose, the change you need to make is:
function createConfigString($dates){
global $globalval;
$str = '<?php \n\n';
$configarray = array('cust_code','Auto_Renew','admin_name');
foreach($configarray as $val){
$str .= "$data['".$val."'] = '".$globalval[$val]."'; \n"; // change places of double and single quotes
}
$str .= "\n"; // change places of double and single quotes
return $str;
}

PHP Array For Each not reading $_POST['item'] data

The following code is not
<?php
$deletinglist = addQuotes($_POST['delimglist']);
$deletelist = array($deletinglist);
foreach ($deletelist as $filename) {
unlink(dirname(__FILE__) . "/uploads/" . $filename);
}
function addQuotes($string) {
return '"'. implode('","', explode(',', $string)) .'"';
}
?>
Here $_POST['delimglist'] = "C0d49a7de7b635477125ffffa8df7b932.jpg,C0d49a7de7b635477125ffffa8df7b934.jpg,C0d49a7de7b635477125ffffa8df7b935.jpg";
If I use $deletelist = array("C0d49a7de7b635477125ffffa8df7b932.jpg","C0d49a7de7b635477125ffffa8df7b934.jpg","C0d49a7de7b635477125ffffa8df7b935.jpg");
Its working fine but if I use $deletelist = array($deletinglist); its not working.
I am getting the following Warning when trying to use like the above
Warning: unlink(/home/...somepath.../uploads/"C0d49a7de7b635477125ffffa8df7b932.jpg","C0d49a7de7b635477125ffffa8df7b934.jpg","C0d49a7de7b635477125ffffa8df7b935.jpg"): No such file or directory in /home/...somepath.../deletefile.php on line 9
I'm not sure why do you add quotes around filename?
The code should be as simple as this:
<?php
$deletelist = explode(',', $_POST['delimglist']);
foreach ($deletelist as $filename) {
unlink(dirname(__FILE__) . "/uploads/" . $filename);
}
?>
All you're doing is putting $deleteList into an array as a single element. You want to separate the values by ','. Use $deleteList = explode(',', $deleteList);
The following are not the same thing:
$arr1 = Array("a", "b", "c");
$str = "a,b,c";
$arr2 = Array($str);
The commas in the first example are a language construct: writing them inside a single variable does not mean they magically gain language construct abilities; inside the string they are just characters.
Similarly, this:
$str = "a,b,c";
foo($str);
is the same as this:
foo("a,b,c");
and not this:
foo("a", "b", "c");
You will have to use a function that explicitly splits up the string $_POST['delimglist']:
$deleteList = explode(',', $_POST['delimglist']);

str ireplace PHP parts of url

I have a html doc that has links in it.
Example :
http://mysite1.com/test/whatIwant/Idontwantthis
http://mysite1.com/test/whatIwant2/Istilldontwantthis
http://mysite1.com/test/whatIwant3/Idontwantthiseither
I want to replace these with:
http://myothersite.com/whatIwant
http://myothersite.com/whatIwant2
http://myothersite.com/whatIwant3
How can I do this? I feel like the only way is to use str_ireplace to get the value that I want and append it to the other link, I just can't seem to remove the part after the value that I want.
I use:
$var= str_ireplace("http://mysite1.com/test/", "http://myothersite.com/", $var);
But then I get the after value still on the link:
http://myothersite.com/whatIwant/Idontwantthis
I tried and now am turning to the community for help.
Thanks
Oh and they are enclosed in the tag with class and other attributes, all I need to change is the URL as explained above.
The links are not in an array they are being edited from a javascript file so they will be in a large variable as text.
$examples =
'http://mysite1.com/test/whatIwant/Idontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis
http://mysite1.com/test/whatIwant3/Idontwantthiseither'
;
Edit: using your updated example, you can split those URLs up by the whitespace between them:
$examples = 'http://mysite1.com/test/whatIwant/Idontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant3/Idontwantthiseither';
$examples = explode(' ', $examples);
Alternative example array:
$examples = array(
'http://mysite1.com/test/whatIwant/Idontwantthis',
'http://mysite1.com/test/whatIwant2/Istilldontwantthis',
'http://mysite1.com/test/whatIwant3/Idontwantthiseither'
);
Regex solution:
$pattern = '/^(?:http|https):\/\/.+\/.*\/(.+)\/.*$/Um';
$replace = 'http://myothersite.com/$1';
foreach($examples as $example) {
echo preg_replace($pattern, $replace, $example);
}
Non-regex solution:
foreach($examples as $example) {
// remove the original domain name
$first = str_ireplace('http://mysite1.com/test/', '', $example);
// prepend the new domain name with the first part of the remaining URL
// e.g. strip everything after the first slash
echo 'http://myothersite.com/' . explode('/', $first)[0];
}
Note: using explode(...)[0] is array dereferencing, and is supported in PHP >= 5.4.0. For previous versions of PHP, use a variable to store the array before referencing it:
$bits = explode('/', $first);
echo 'http://myothersite.com/' . $bits[0];
From the manual:
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
Example output:
http://myothersite.com/whatIwant
http://myothersite.com/whatIwant2
http://myothersite.com/whatIwant3
This function should do the job.
<?php
function EditLink($link)
{
$link = explode("/",$link);
return $link[4];
}
$new_link = "http://myothersite.com/".EditLink("http://mysite1.com/test/whatIwant/Idontwantthis")."";
echo $new_link;
?>
Try this no regex:
$urls = array(
'http://mysite1.com/test/whatIwant3/Idontwantthiseither',
'http://mysite1.com/test/whatIwant/Idontwantthis',
'http://mysite1.com/test/whatIwant2/Istilldontwantthis'
);
$new_site = "http://myothersite.com/";
foreach ($urls as $url) {
$pathinfo = pathinfo($url);
$base = basename($pathinfo['dirname']);
$var = str_ireplace($url, $new_site . $base, $url);
echo $var . '<br>';
}
As of PHP 5.3:
$new_urls = array_map(function($url) { // anonymous function
global $new_site;
$pathinfo = pathinfo($url);
$base = basename($pathinfo['dirname']);
$var = str_ireplace($url, $new_site . $base, $url);
return $var;
}, $urls);
echo implode('<br>', $new_urls);
Sorry by my last answer, you was right, the order was correct.
Try this one with pre_replace, I beleave could solve the problem:
$var = "http://mysite1.com/test/whatIwant/Idontwantthis";
$var = preg_replace("/http\:\/\/mysite1.com\/([^\/]+)\/?.*/", "http://myothersite.com/$1", $var);
echo $var;

is there a PHP library that handles URL parameters adding, removing, or replacing?

when we add a param to the URL
$redirectURL = $printPageURL . "?mode=1";
it works if $printPageURL is "http://www.somesite.com/print.php", but if $printPageURL is changed in the global file to "http://www.somesite.com/print.php?newUser=1", then the URL becomes badly formed. If the project has 300 files and there are 30 files that append param this way, we need to change all 30 files.
the same if we append using "&mode=1" and $printPageURL changes from "http://www.somesite.com/print.php?new=1" to "http://www.somesite.com/print.php", then the URL is also badly formed.
is there a library in PHP that will automatically handle the "?" and "&", and even checks that existing param exists already and removed that one because it will be replaced by the later one and it is not good if the URL keeps on growing longer?
Update: of the several helpful answers, there seems to be no pre-existing function addParam($url, $newParam) so that we don't need to write it?
Use a combination of parse_url() to explode the URL, parse_str() to explode the query string and http_build_query() to rebuild the querystring. After that you can rebuild the whole url from its original fragments you get from parse_url() and the new query string you built with http_build_query(). As the querystring gets exploded into an associative array (key-value-pairs) modifying the query is as easy as modifying an array in PHP.
EDIT
$query = parse_url('http://www.somesite.com/print.php?mode=1&newUser=1', PHP_URL_QUERY);
// $query = "mode=1&newUser=1"
$params = array();
parse_str($query, $params);
/*
* $params = array(
* 'mode' => '1'
* 'newUser' => '1'
* )
*/
unset($params['newUser']);
$params['mode'] = 2;
$params['done'] = 1;
$query = http_build_query($params);
// $query = "mode=2&done=1"
Use this:
http://hu.php.net/manual/en/function.http-build-query.php
http://www.addedbytes.com/php/querystring-functions/
is a good place to start
EDIT: There's also http://www.php.net/manual/en/class.httpquerystring.php
for example:
$http = new HttpQueryString();
$http->set(array('page' => 1, 'sort' => 'asc'));
$url = "yourfile.php" . $http->toString();
None of these solutions work when the url is of the form:
xyz.co.uk?param1=2&replace_this_param=2
param1 gets dropped all the time
.. which means it never works EVER!
If you look at the code given above:
function addParam($url, $s) {
return adjustParam($url, $s);
}
function delParam($url, $s) {
return adjustParam($url, $s);
}
These functions are IDENTICAL - so how can one add and one delete?!
using WishCow and sgehrig's suggestion, here is a test:
(assuming no anchor for the URL)
<?php
echo "<pre>\n";
function adjustParam($url, $s) {
if (preg_match('/(.*?)\?/', $url, $matches)) $urlWithoutParams = $matches[1];
else $urlWithoutParams = $url;
parse_str(parse_url($url, PHP_URL_QUERY), $params);
if (strpos($s, '=') !== false) {
list($var, $value) = split('=', $s);
$params[$var] = urldecode($value);
return $urlWithoutParams . '?' . http_build_query($params);
} else {
unset($params[$s]);
$newQueryString = http_build_query($params);
if ($newQueryString) return $urlWithoutParams . '?' . $newQueryString;
else return $urlWithoutParams;
}
}
function addParam($url, $s) {
return adjustParam($url, $s);
}
function delParam($url, $s) {
return adjustParam($url, $s);
}
echo "trying add:\n";
echo addParam("http://www.somesite.com/print.php", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?newUser=1", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?newUser=1&fee=0", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?newUser=1&fee=0&", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?mode=1", "mode=3"), "\n";
echo "\n", "now trying delete:\n";
echo delParam("http://www.somesite.com/print.php?mode=1", "mode"), "\n";
echo delParam("http://www.somesite.com/print.php?mode=1&newUser=1", "mode"), "\n";
echo delParam("http://www.somesite.com/print.php?mode=1&newUser=1", "newUser"), "\n";
?>
and the output is:
trying add:
http://www.somesite.com/print.php?mode=3
http://www.somesite.com/print.php?mode=3
http://www.somesite.com/print.php?newUser=1&mode=3
http://www.somesite.com/print.php?newUser=1&fee=0&mode=3
http://www.somesite.com/print.php?newUser=1&fee=0&mode=3
http://www.somesite.com/print.php?mode=3
now trying delete:
http://www.somesite.com/print.php
http://www.somesite.com/print.php?newUser=1
http://www.somesite.com/print.php?mode=1
You can try this:
function removeParamFromUrl($query, $paramToRemove)
{
$params = parse_url($query);
if(isset($params['query']))
{
$queryParams = array();
parse_str($params['query'], $queryParams);
if(isset($queryParams[$paramToRemove])) unset($queryParams[$paramToRemove]);
$params['query'] = http_build_query($queryParams);
}
$ret = $params['scheme'].'://'.$params['host'].$params['path'];
if(isset($params['query']) && $params['query'] != '' ) $ret .= '?'.$params['query'];
return $ret;
}

Categories