file_get_contents with query string - php

i am trying to send email from php
i have one php file with all values & other php template file.
(both files are on same server)
i am using file_get_contents to get contents of php template file for example
$url="emil_form.php";
$a="uname";
if(($Content = file_get_contents($url. "?uname=".$a)) === false) {
$Content = "";
}
...... EMAIL Sending Code ..........
and here is code for emil_form.php (email template file)
Your Name is : <?php $_GET['uname']; ?>
so once i got data in $Content i can send it by email.
but i am getting error unable to open file....
what i want is pass data from original php file to template php file and what will be output of template stored in variable so i can send it by email.
how can do this ?
Thanks

The real problem would be that you try to read a local file with a http query string behind it. The file system don't understand this and looks for a file called "emil_form.php?uname=uname".
$_GET / $_POST / etc only works over a http connection.
Try to put a placeholder like "%%NAME%%" in your template and replace this after reading the template.
<?php
$url = "emil_form.php";
$a = "uname";
if(($Content = file_get_contents($url)) === false) {
$Content = "";
}
$Content = str_replace('%%NAME%%', $a, $Content);
// sending mail....
Template will look like this:
Your Name is: %%NAME%%

Here's an alternative solution...
Use the relative path or absolute path as suggested by "cballou" to read file.
But insted of wirting a php file use a simple text file put you message template in it replace <?php $_GET['uname']; ?> with something unique like %uname% (replacement keys).
Read the file content into a variable and replace the replacement keys with your variable like so,
$url = "/usr/local/path/to/email_form.txt";
$a = "uname";
if(($Content = file_get_contents($url)) === false) {
$Content = "";
}else{
$content = str_replace('%uname%', $a, $content);
}

$url = sprintf("%s://%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME']);
$content = file_get_contents($url."/file.php?test=".$test);
echo $content;

Please note that you had a filename error in $url which wss trying to load emil_form.php.
A secondary issue seems to be the path you are using for your call to $url. Try making it an full URL in order to properly parse the file, avoiding any templating you may otherwise have to do. The RTT would be slower but you wouldnt have to change any code. This would look like:
$url = 'http://www.mysite.com/email_form.php';
$a = "uname";
if(($Content = file_get_contents($url. "?uname=".$a)) === false) {
$Content = "";
}

Related

How to assign SplFileObject::fpassthru output to variable

I'm currently writing some data to an SplFileObject like this:
$fileObj = new SplFileObject('php://text/plain,', "w+");
foreach($data as $row) {
$fileObj->fputcsv($row);
}
Now, I want to dump the whole output (string) to a variable.
I know that SplFileObject::fgets gets the output line by line (which requires a loop) but I want to get it in one go, ideally something like this:
$fileObj->rewind();
$output = $fileObj->fpassthru();
However, this does not work as it simply prints to standard output.
There's a solution for what I'm trying to achieve using stream_get_contents():
pass fpassthru contents to variable
However, that method requires you to have direct access to the file handle.
SplFileObject hides the file handle in a private property and therefore not accessible.
Is there anything else I can try?
After writing, do a rewind() then you can read everything. The example is for understanding:
$fileObj = new SplFileObject('php://memory', "w+");
$row = [1,2,'test']; //Test Data
$fileObj->fputcsv($row);
$fileObj->rewind();
//now Read
$rowCopy = $fileObj->fgetcsv();
var_dump($row == $rowCopy);//bool(true)
$fileObj->rewind();
$strLine = $fileObj->fgets(); //read as string
$expected = "1,2,test\n";
var_dump($strLine === $expected); //bool(true)
//several lines
$fileObj->rewind();
$fileObj->fputcsv(['test2',3,4]);
$fileObj->fputcsv(['test3',5,6]);
$fileObj->rewind();
for($content = ""; $row = $fileObj->fgets(); $content .= $row);
var_dump($content === "test2,3,4\ntest3,5,6\n"); //bool(true)
If you absolutely have to fetch your content with only one command then you can do this too
// :
$length = $fileObj->ftell();
$fileObj->rewind();
$content = $fileObj->fread($length);
getSize() doesn't work here.
In the absence of an inbuilt function I've decided to do php output buffering as #CBroe had suggested.
...
$fileObj->rewind();
ob_start();
$fileObj->fpassthru();
$buffer = ob_get_clean();
See #jsplit's answer for a better method using SplFileObjects inbuilt functions

How to get the content of the file in variable in Laravel 5.5

I am uploading files that I need to attach to email via office365 API.
What I need is the content of the file in a variable WITHOUT storing/saving the file, how can I do that?
foreach ($request->filesToUpload as $file) {
$originalName = $file->getClientOriginalName();//working
$content = $file->getContent();//<- I need this, but not working
//$this->addAttachment($content, $originalName) //logic for later
}
Access the contents of the file like so:
$content = file_get_contents(Input::file('nameAttribute')->getRealPath());
or in other words inside that loop
$contents = file_get_contents($file->getRealPath());
Get the real path with object methods, and you may interact with it like any other file.
Waqas Bukhary,
You get that result, beucause, getContent is not a method of uploadedFiles, check the documentation.
But you have the path, so you can always read the content, like:
$path = $file->path();
$handle = fopen($path, 'r');
$content = fread($handle, filesize($path);
fclose($handle);
You can also use the Request File method if you know the name of the file field, check it here.

php - one time access by looking up serial in a .dat file

i've now written this short script.
It records a serial or token number, checks to see if its in a .dat file, and allows access if its present. Otherwise it denies access to the site.
It also removes the token from the file once it has been redeemed as it were.
However, when i add multiple tokes in the dat file, the code doesn work properly. It only works with a single entry. How would i make it work for multiple entries.
im thinking of maybe implementing some sort of array somewhere? or explode?
index.php
require_once "married.php";
session_start();
$url_request = (isset($_SERVER['HTTPS']) ? "https" : "http") .
"://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$ip = $_SERVER['REMOTE_ADDR'];
$token = substr($url_request,45);
$_SESSION["cookie"] = $token;
$tk = $_SESSION["cookie"];
$ips = array();
$page = file("urls.dat");
foreach($page as $line)
{
array_push($ips, $line);
}
if(in_array($tk, $ips))
{
//header("Location: mysite.co.uk");
echo "<title>My Site</title>Here is my site";
$file = fopen("ip_match.dat","a");
fwrite($file,$tk . " " . $ip . "\r\n");
fclose($file);
$oldMessage = $_SESSION["cookie"];
$deletedFormat = "";
$str=file_get_contents('urls.dat');
$str=str_replace("$oldMessage", "$deletedFormat",$str);
file_put_contents('urls.dat', $str);
exit;
} else {
echo ("<title>404 Not Found</title>
<h1>Not Found</h1>The requested URL was not found on this server.
<br>
<br>
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. test");
exit;
}
urls.dat
1089yht
url: http://mmmmmmmmmmmmm.co.uk/url/index.php?key=1089yht
ps. Happy Holidays all!
Look at JSON. You could do something like this:
$tokens = ['foo', 'bar'];
file_put_contents('urls.json', json_encode($tokens));
// and then you can decode it back
// returns ['foo', 'bar']
$decodedTokens = json_decode(file_get_contents('urls.json'));
If you still want to use simple text file, you could save every record at new line and then load line by line.
$tokens = [];
while(! feof($file)) {
$line = fgets($file);
// or save to array
$tokens[] = $line;
}
fclose($file);
try
$str = preg_replace("/{$oldMessage}/", $deletedFormat, $str, 1);
Instead of
$str=str_replace("$oldMessage", "$deletedFormat",$str);
Because: str_replace replaces everything.
preg_replace lets you limit how many replacements.

Get generated html content of php script on same server

I have a php page that outputs html to the browser based on a query string that is parsed. The issue I am having is that I need to retrieve this html source code dynamically via php.
The following code will not work because it tries to resolve an absolute path as it's on the same server:
$url = 'http://example.com/myScript.php';
$html = file_get_contents($url);
If I manually set the absolute path it just returns the php contents as text (not executed like a browser would do):
$url = '/dir1/dir2/dir3/dir4/myScript.php';
$html = file_get_contents($url);
I then researched it and found that using ob_get_contents could work. The code below works as expected, executing the script and returning the html output.
$url = '/dir1/dir2/dir3/dir4/myScript.php';
ob_start();
include($url);
$html = ob_get_contents();
ob_end_clean();
The problem with the above solution is that as soon as I put the query string on the end it fails. I think this is because it's treating the query string as part of the file name.
Use PHPs ob_get_contents
<?php
ob_start();
$original_get = $_GET;
$_GET = ["query" => "tags", "you" => "need", "in" => "file.php"];
$file = "file.php";
include($file);
$_GET = $original_get;
$content = ob_get_contents();
ob_clean();
echo $content;

How to read a csv file with php code inside?

i searched Google but found nothing what fits for my problem, or i search with the wrong words.
In many threads i read, the smarty Template was the solution, but i dont wont use smarty because its to big for this little project.
My problem:
I got a CSV file, this file contents only HTML and PHP code, its a simple html template document the phpcode i use for generating dynamic imagelinks for example.
I want to read in this file (that works) but how can i handle the phpcode inside this file, because the phpcode shown up as they are. All variables i use in the CSV file still works and right.
Short Version
how to handle, print or echo phpcode in a CSV file.
thanks a lot,
and sorry for my Bad english
Formatting your comment above you have the following code:
$userdatei = fopen("selltemplate/template.txt","r");
while(!feof($userdatei)) {
$zeile = fgets($userdatei);
echo $zeile;
}
fclose($userdatei);
// so i read in the csv file and the content of csv file one line:
// src="<?php echo $bild1; ?>" ></a>
This is assuming $bild1 is defined somewhere else, but try using these functions in your while loop to parse and output your html/php:
$userdatei = fopen("selltemplate/template.txt","r");
while(!feof($userdatei)) {
$zeile = fgets($userdatei);
outputResults($zeile);
}
fclose($userdatei);
//-- $delims contains the delimiters for your $string. For example, you could use <?php and ?> instead of <?php and ?>
function parseString($string, $delims) {
$result = array();
//-- init delimiter vars
if (empty($delims)) {
$delims = array('<?php', '?>');
}
$start = $delims[0];
$end = $delims[1];
//-- where our delimiters start/end
$php_start = strpos($string, $start);
$php_end = strpos($string, $end) + strlen($end);
//-- where our php CODE starts/ends
$php_code_start = $php_start + strlen($start);
$php_code_end = strpos($string, $end);
//-- the non-php content before/after the php delimiters
$pre = substr($string, 0, $php_start);
$post = substr($string, $php_end);
$code_end = $php_code_end - $php_code_start;
$code = substr($string, $php_code_start, $code_end);
$result['pre'] = $pre;
$result['post'] = $post;
$result['code'] = $code;
return $result;
}
function outputResults($string) {
$result = parseString($string);
print $result['pre'];
eval($result['code']);
print $result['post'];
}
Having PHP code inside a CSV file that should be parsed and probably executed using eval sounds pretty dangerous to me.
If I get you right you just want to have dynamic parameters in your CSV file right? If thats the case and you don't want to implement an entire templating language ( like Mustache, Twig or Smarty ) into your application you could do a simple search and replace thing.
$string = "<img alt='{{myImageAlt}}' src='{{myImage}}' />";
$parameters = [
'myImageAlt' => 'company logo',
'myImage' => 'assets/images/logo.png'
];
foreach( $parameters as $key => $value )
{
$string = str_replace( '{{'.$key.'}}', $value, $string );
}

Categories