PHP: Using a variable inside a double quotes with backshlashes - php

I have a variable with Windows path and backslahes. And in this i need two antoher variables. Looks like this:
$file_name_with_full_path = 'C:\inetpub\wwwroot\upload\files\$filnr\$file';
At the end i need the variable $filnr and $file, but it is not possible to do it with " "
$file_name_with_full_path = "C:\inetpub\wwwroot\upload\files\$filnr\$file";
With " " i got an error, because in my script i do a curl-request.
How can i insert the variables with backslash in a single ' ?
my full script looks like this:
if ($result->num_rows > 0) {
//schleife ausführen
while($row = $result->fetch_assoc()) {
//ip und filnr aus datenbank in var
$ip = $row["ip"];
$filnr = $row["filnr"];
echo "$filnr $ip<br>";
//filnr und dateiname momentan noch hart codiert
$target_url = "http://10.74.20.94:6001/upload";
$file_name_with_full_path = 'C:\inetpub\wwwroot\upload\files\$filnr\$file';
if (function_exists('curl_file_create')) {
$cFile = curl_file_create($file_name_with_full_path);
} else {
$cFile = '#' . realpath($file_name_with_full_path);
}
$post = array('targetpath'=>'C:\bizstorecard\hossi','uploadfile'=> $cFile);
$go = curl($target_url,$post);
}
} else {
echo "Fehler bei Abfrage";
}
function curl($target_url,$post) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_exec($ch);
curl_close($ch);
}

Just use string concatenation instead:
$file_name_with_full_path = 'C:\inetpub\wwwroot\upload\files\\' . $filnr . '\\' . $file;
Note you need to use \\ for the \ before the ' otherwise PHP treats it as an escaped '.
If you want to use double quotes, you just need to escape all the backslashes that occur before something that can be interpreted as a variable (or a special character e.g. \f = Formfeed):
$file_name_with_full_path = "C:\inetpub\wwwroot\upload\\files\\$filnr\\$file";
Demo on 3v4l.org

You cannot use variables directly in a single quoted string, if you want to use this you need to either concatenate manually or use sprintf.
The reason the double quotes aren't working is because the backslash escapes the $ character and so it just prints the string literally. You need to escape the backslash characters to print them correctly.
$file_name_with_full_path = "C:\\inetpub\\wwwroot\\upload\\files\\$filnr\\$file";

Alternatively, and with added readability, you can use curly braces inside double-quoted strings.
$path = "C:\inetpub\wwwroot\upload\files\{$filnr}\{$file}";
Additionally, this works with array values addressed using single quotes:
$path = "C:\inetpub\wwwroot\upload\files\{$file['directory']}\{$file['name']}";

Related

curl post Json with addslashes

I need:
$content = "{\"data1\":90,\"data2\":\"SUKAORU\",\"data3\":7483478334}";
curl_setopt_array($curl, array(CURLOPT_POSTFIELDS => $content);
I did:
$_REQUEST = array("data1"=>90,"data2"=>"SUKAORU,"data3"=>7483478334);
$content1 = '"' . addslashes(json_encode($_REQUEST)) . '"';
curl_setopt_array($curl, array(CURLOPT_POSTFIELDS => $content1);
//or
$content1 = addslashes(json_encode($_REQUEST));
curl_setopt_array($curl, array(CURLOPT_POSTFIELDS => $content1);
//or
$content1 = json_encode($_REQUEST);
curl_setopt_array($curl, array(CURLOPT_POSTFIELDS => $content1);
$content and $content1 looks identically:
But second version returns error from server "unable to decode request".
How can I ecranate array into JSON like in I need example?
Don't use addslashes. Just don't use it.
The slashes here:
$content = "{\"data1\":90,\"data2\":\"SUKAORU\",\"data3\":7483478334}";
… are only part of the PHP source code. They are not part of the data.
If you're generating the JSON using json_encode then you don't need to manually write \" to get quotes into the " delimited string literal. You don't have a string literal and json_encode is generating the quotes.
This should be fine.
$data = array("data1"=>90,"data2"=>"SUKAORU","data3"=>7483478334);
$json = json_encode($data);
curl_setopt_array($curl, array(CURLOPT_POSTFIELDS => $json);
Note addition of missing " after "SUKAORU.

How can assign preg_match_all variable to a vaiable

Forgive me as I am a newbie programmer. How can I assign the resulting $matches (preg_match) value, with the first character stripped, to another variable ($funded) in php? You can see what I have below:
<?php
$content = file_get_contents("https://join.app.net");
//echo $content;
preg_match_all ("/<div class=\"stat-number\">([^`]*?)<\/div>/", $content, $matches);
//testing the array $matches
//echo sprintf('<pre>%s</pre>', print_r($matches, true));
$funded = $matches[0][1];
echo substr($funded, 1);
?>
Don't parse HTML with RegEx.
The best way is to use PHP DOM:
<?php
$handle = curl_init('https://join.app.net');
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$raw = curl_exec($handle);
curl_close($handle);
$doc = new DOMDocument();
$doc->loadHTML($raw);
$elems = $doc->getElementsByTagName('div');
foreach($elems as $item) {
if($item->getAttribute('class') == 'stat-number')
if(strpos($item->textContent, '$') !== false) $funded = $item->textContent;
}
// Remove $ sign and ,
$funded = preg_replace('/[^0-9]/', '', $funded);
echo $funded;
?>
This returned 380950 at the time of posting.
I am not 100% sure but it seems like you are trying to get the dollar amount that the funding is currently ?
And the character is a dollar sign that you want to strip out ?
If that is the case why not just add the dollar sign to the regex outside the group so it isn't captured.
/<div class=\"stat-number\">\$([^`]*?)<\/div>/
Because $ means end of line in regex you must first escape it with a slash.

How do i echo php for json string?

i need to echo $account into $url so that the url/path is whatever i get from $account plus the extension json. I can't figure it out with the quotes. i tried single and double quotes but no luck. any ideas?
<?php
$account = $_POST['account'];
$url = 'echo $account.json'; //
$content = file_get_contents($url);
$json = json_decode($content, true);
?>
Like this?
<?php
$account = $_POST['account'];
$url = $account. '.json'; //
$content = file_get_contents($url);
$json = json_decode($content, true);
?>
the . operator is used for string concatenation in php. This means take the value of $account and append the string .json to the end, and store that in the variable $url. The rest of the code looks all right from there. There are a few other ways to do this as well with strings in php, but I find this one simplest.
You can do this as this
$account = $_POST['account'];
$content = file_get_contents($account.'.json');
$json = json_decode($content, true);
Need I remind you how, vulnerable your codes are to injection?
The documentation on strings goes into detail on how to format strings. You might want to try using curly braces ({}) around your variable as well to delineate where the identifier ends.
$url = "{$account}.json"

sprintf warning - encoding issue

I'm using the following code to find all properties for a user and in turn delete them. My problem is that I'm getting a warning: Warning: sprintf(): Too few arguments for each of the properties.
However, when I manually enter the $user_id for the delete string as first_last%%40ourwiki.com it works!
Seems like sprintf requires double '%' but not sure why. Is there a way to get around this? Also, I'm using the same variable for file_get_contents and this works fine.
The Code:
$user="first_last#ourwiki.com";
$user_id=str_replace(array('#', '#'), array('%40', '%23'), $user);
print $user_id;
$url=("http://admin:password#172.16.214.133/#api/users/=$user_id/properties");
$xmlString=file_get_contents($url);
$delete = "http://admin:password#172.16.214.133/#api/users/=$user_id/properties/%s";
$xml = new SimpleXMLElement($xmlString);
function curl_fetch($url,$username,$password,$method='DELETE')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password");
return curl_exec($ch);
}
foreach($xml->property as $property) {
$name = $property['name'];
$name2=str_replace(array('#', '#'), array('%40', '%23'), $name);
print $name2;
curl_fetch(sprintf($delete, $name2),'admin','password');
}
Thanks in advance!
% is a special character in sprintf(). So you have to escape all % before processing it, %% is a literal %s.
$delete = str_replace("http://admin:password#172.16.214.133/#api/users/=$user_id/properties/", '%', '%%').'%s';
You do not have to use sprintf here, you can use the concatenation operator too, like:
$delete = "http://admin:password#172.16.214.133/#api/users/=$user_id/properties/";
curl_fetch( $delete . $name2, 'admin', 'password' );

PHP - Failed to open stream with URL containing variable

I'm trying to use file_get_contents but it tells me failed to open stream.
My code:
$user="first_last#ourwiki.com";
$user_id=str_replace(array('#', '#'), array('%40', '%23'), $user);
print $user_id;
$url=('http://admin:password#172.16.214.133/#api/users/=$user_id/properties');
$xmlString=file_get_contents($url);
This is what I get when I try to run it:
Warning:
file_get_contents(http://...#172.16.214.133/#api/deki/users/=$user_id/properties):
failed to open stream: HTTP request
failed! HTTP/1.1 500 Internal Server
Error
However, if I manually type in the $user_id first_last%40ourwiki.com then it works! What am I doing wrong? Shouldn't I be able to just use the variable name?
Remaining code:
$delete = "http://admin:password#172.16.214.133/#api/users/=$user_id/properties/%s";
$xml = new SimpleXMLElement($xmlString);
function curl_fetch($url,$username,$password,$method='DELETE')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password");
return curl_exec($ch);
}
foreach($xml->property as $property) {
$name = $property['name'];
$name2 =str_replace(array('#', '#'), array('%40', '%23'), $name);
print $name2;
curl_fetch(sprintf($delete, $name2),'admin','password');
}
Variables contained in single-quoted strings are not interpreted.
You could do this:
"http://admin:password#172.16.214.133/#api/users/=$user_id/properties"
But a better habit is to do this:
'http://admin:password#172.16.214.133/#api/users/=' . $user_id . '/properties'
or this:
"http://admin:password#172.16.214.133/#api/users/=" . $user_id . "/properties"
or this:
sprintf("http://admin:password#172.16.214.133/#api/users/=%s/properties", $user_id)
The faster is with single-quoted strings, because php doesn't try to find variables in them.
This is because you have used single quotes. The content within single quotes is not parsed, so:
echo '$test';
won't display the value of the $test variable, but just the "$test" string. You can use double quotes instead, but anyway this is the best way to do it:
$url=('http://admin:password#172.16.214.133/#api/users/='.$user_id.'/properties');
Special characters such as \n, \t or \r also won't be parsed in single quotes.

Categories