With this code I create new files with information from a database:
function getLocations() {
$query = mysql_query("SELECT DISTINCT `plaats` FROM `plaatsen` ORDER BY `plaats` ");
while ($row = mysql_fetch_assoc($query)){
$city = $row['plaats'];
$handle = fopen( "cities/$city.php",'w');
echo "<a href='cities/".$row['plaats'].".php' class='col-md-4'>"."<div class='steden'>".$row['plaats']."</div>"."</a>";
fwrite($handle, '<?php include("../stad.php") ?>');
fwrite($handle, $city);
}
}
The output are multiple links and files with different cities like: Amsterdam, Rotterdam, Den Haag. Now the content on these pages has to be different depending on the city it is. So basically the page should know which city it is and dan download content for this city from a database.
I tried to do this with writing a var to the pages which does write the city name to the page, but I cannot (as far as I know) do anything with this information.
Does someone know how to do this? Thanks!
$handle = fopen( "cities/$city.php",'w'); - ERK! This is really bad for security. Allowing your webserver uid write access to files which will then be processed by PHP is not in itself a vulnerability but provides a vector for escalation of an attack.
There may be a good reason why you want to cache content outside of your database - but use a caching reverse proxy or ESI or (as a last resort) implement caching of HTML fragments in your PHP code DO NOT USE PHP CODE AS A CACHE.
As to the question of identifying the name of a file PHP code is running in - PHP can get this from the __FILE__ constant. e.g.
<?php
print "I am in " . strtok(basename(__FILE__), '.');
To determine the filenames involved in a hierarchy of includes, have a look at debug_backtrace()
Related
I'm trying to download a full library of photos from my university housing system.
The system runs on nginx, file parsing for that particular directory is unavailable, 404 returns all the time.
Anyway, every single photo is stored in a /res/up/250x300 directory, with a number, gender indicator and a random(?) hash, example here;
114057-f-95830a765f22b71ad5691adfdec6bfzfc222bb1c7.jpg
There's catalog of users which when called with specific user id returns file in EXACT same format as provided above, and is always stored in:
<div class="uwb-imgcover-photo-wrapper"/>
So, summarizing, it looks like this.
Calling for a specific user;
/kontroler.php?_action=katalog2/osoby/pokazOsobe&os_id=114057
class uwb-imgcover-photo-wrapper gives me a link to the photo:
/res/up/250x300/114057-f-95830a765f22b71ad5691adfdec6bfzfc222bb1c7.jpg
Wget magic doesn't work.
I was thinking about a loop or something like this. This is actually very first time I'm doing anything related to web file catching.
Try this
for($i=114050;$i<=114057;$i++){
$result = file_get_contents('http://domain.com/kontroler.php?_action=katalog2/osoby/pokazOsobe&os_id='.$i);
if($result){
preg_match('/\/res\/up\/250x300\/(.*?)\.jpg/',$result,$match);
if($match){
$filename = $match[1].'.jpg';
$imageURL = 'http://domain.com/res/up/250x300/'.$filename;
$image = file_get_contents($url);
file_put_contents($filename, $image);
}
}
}
I am given a lot of video files on my server folder, so adding all of them is impossible, I need to develop a php script that will read the contents of a folder and populate my database table with details such as filename, size, path, etc.
Furthermore I need to use that data for displaying the video list to users so everything must be accurate.
Please tell me how to?
I suggest you to use Iterators from SPL (Standart PHP Library) for an OOP aproach, for recursive iterations you should use DirectoryRecursiveIterator;
$directoryIterator = new RecursiveDirectoryIterator("/path/");
$recursiveIterator = new RecursiveIteratorIterator($directoryIterator);
foreach ($recursiveIterator as $filename => $fileInfo) {
$filesize = $fileInfo->getSize();
$path = $fileInfo->getPath();
//insertDataIntoMysql($filename, $filesize, $filepath);
}
See here to see how to loop through a directory and get the filenames and file sizes. (Copied and edited here for simplicity)
$folder = '/my/path/to/dir';
foreach(glob($folder) as $file){
$size = filesize($file);
echo "Name=$file, size=$size<br />";
}
Instead of using echo to display the results you will simply use mysqli or PDO functions to run an INSERT query to insert into your table. Since this is not input coming from a user it is not so imperative to use prepare and bind but it is good practice to do so (and more efficient as well).
Then when you display the video list you will once again use mysqli or PDO functions to run a SELECT query and then echo these values onto your page in appropriate HTML syntax.
I'm guessing, based on your question, that some of these concepts might be new to you. If you do not know how to program in PHP or use SQL or create HTML pages then you are going to need to spend some serious time going through tutorials and watching youtube videos and reading books.
Good day everyone!
Well here's the thing;
One .htaccess file, mod rewrite, to redirect imagename.png (non existing file) to tracker.php (real file). So when a user is looking at site.com/hello.png the user is actuall looking at /hello.php which gather information and stores it.
tracker.php
<?php
$date = date('d-m-Y');
$time = date('H:i:s');
$ip = $_SERVER['REMOTE_ADDR'];
$ref = #$_SERVER["HTTP_REFERER"];
header('Content-type: image/png');
echo gzinflate(base64_decode('6wzwc+flkuJiYGDg9fRwCQLSjCDMwQQkJ5QH3wNSbCVBfsEMYJC3jH0ikOLxdHEMqZiTnJCQAOSxMDB+E7cIBcl7uvq5rHNKaAIA'));
$myFile = "tr.txt";
$fh = fopen($myFile, 'a');
fwrite($fh, $myFile = $time ." | ". $date . " | " .$ip. " | " .$ref. " | \r\n\r\n");
fclose($fh);
?>
I am using it on my site to track visitors. Everything works fine, I could gather information about ip, webbrowser, ref-link etc.
But my question is, what are the restriction when doing this? I have been experimenting a long time and it seems like I could only use plain php (not echo "some other language").
I can not redirect or echo text. Loops, if/else, variables etc is working.
If I tries to redirect I could see that the page is attempting to connect to e.g. google but just for a second so there are no actual redirects.
tl;dr
What are the restriction in code when using a php file as an image?
I don't think there are any restrictions.
Your php code is executed and runs.
What you display doesn't restrict php.
You mentioned a redirect there. You're loading an image in a html page (generated by php or not, doesn't matter). The html page received it's headers from the server, and your php generated image also received it's headers (content-type image). Here is where the redirect would be.
There's no reason why your html page will ever redirect using a php headers function on your image.
If you load the php generated image directly in your browser, I think you'll be able to redirect the user (directly, without displaying the image), but as an image in a html page, it's not possible to affect the rest of the page, unless you use javascript.
I'm writing a system for a browser application that will store some particular php scripts in a database and then pull them out and execute them when needed. At first I tried using exec() and piping to php the output of a script that got the scripts out of the database and printed them. This worked in one use case, but not all, and feels brittle anyway, so I'm looking for a better way.
I'm now attempting to accomplish this through use of a PHP file stream in memory. For instance:
$thing = <<<'TEST'
<?php
$thing = array();
print "Testing code in here.";
var_dump($thing);
?>
TEST;
$filename = "php://memory";
$fp = fopen($filename, "w+b");
fwrite($fp, $thing);
//rewind($fp);
fclose($fp);
include "php://memory";
However, nothing is printed when the script is executed. Is this even possible by this means, and if not, is there another way to do this? I'm trying to avoid having to write temporary files and read from them, as I'm sure accessing the filesystem would slow things down. Is there a URL I can provide to "include" so that it will read the memory stream as if it were a file?
I don't think eval() would do this, as, if I remember correctly, it's limited to a single line.
Also, please no "eval = include = hell" answers. Non-admin users do not have access to write the scripts stored in the database, I know that this needs special treatment over the life-cycle of my application.
You need to use stream_get_contents to read from the php://memory stream. You cannot include it directly.
eval() and include are actually pretty the same. So eval() works with multiple lines - just FYI. However, I would prefer include here, I always think it's faster. Maybe I'm wrong, no Idea.
However, I think you should debug your code, I don't see a reason per-se why it should not work. You might need to rewind the pointer (you have commented that), but what you should check first-hand is, that your PHP configuration allows to include URLs. I know that that setting prevents using of the data:// URIs, so you might have this enabled.
Also you can always try if PHP can open the memory by using file_get_contents and dumping out. This should give you the code. If not, you already made some mistake (e.g. no rewind or something similar).
Edit: I've not come that far (demo):
<?php
/**
* Include from “php://memory” stream
* #link https://stackoverflow.com/q/9944867/367456
*/
$thing = <<<TEST
<?php
\$thing = array();
print "Testing code in here.";
var_dump(\$thing);
TEST;
$filename = "php://memory";
$fp = fopen($filename, "w+b");
fwrite($fp, $thing);
rewind($fp);
var_dump(stream_get_contents($fp));
This is what I found out:
You should not close the "file". php://memory is a stream once closed it will disappear.
You need to access the $fp as stream than, which is not possible for include out of the box AFAIK.
You then would need to create a stream wrapper that maps a stream resource to a file name.
When you've done that, you can include a memory stream.
The PHP settings you need to check anyway. There are more than one, consult the PHP manual.
It might be easier to use the data URI (demo):
<?php
/**
* Include from “php://memory” stream
* #link https://stackoverflow.com/q/9944867/367456
*/
$thing = <<<TEST
<?php
\$thing = array();
print "Testing code in here.";
var_dump(\$thing);
TEST;
include 'data://text/plain;,'. urlencode($thing);
See as well: Include code from a PHP stream
If there is a way to include from php://memory then this is a serious vulnerability. While it has many uses, eval is used quite often with code obfuscation techniques to hide malicious code.
(Every tool is a weapon if you hold it right.)
With that said, there (thankfully) doesn't appear to be any obvious way to include from php://memory
http://static.ak.fbcdn.net/rsrc.php/117600/css/base.css
http://static.ak.fbcdn.net/rsrc.php/z4HBM/hash/3krgnmig.swf
http://b.static.ak.fbcdn.net/rsrc.php/z23ZQ/hash/3ls2fki5.xml
http://static.ak.fbcdn.net/rsrc.php/z7O0P/hash/4hw14aet.png
What does rsrc.php really does? I know that rsrc stands for resource and rsrc.php/z[random]/hash or css/file.extenstion loads a file from somehwere.
Assuming /hash/ or /css/ is a folder which keeps the files like .xml .png .swf but whats with z[random] thing and why they want to load a file from a php? Is it for something like version control for the file or what? If so how to do it (in a simpler way)?
rsrc.php is used by Facebook for version control of all static files, especially images, javascript, and stylesheets. This allows Facebook to apply changes to the main application stack including changes to static content files without breaking functionality for users who are running off an old cached version. It is built into the Facebook architecture as part of the Haste system.
Reference To Code Function Identification By Original Developer
Recommended Process For Managing Static Resources (phabricator.com)
I think that these files are stored in a database. Anything after the SELF (script name, in this case the script is rsrc.php) is passed to the script as a param for the database. I use myself on image files, you base64 the image, store it in the database and usually with a bit of mod_rewrite magic your can get the url of the image to be youtsite.com/images/fish-with-wings when it is really doing this: yoursite.com/some-script.php/fish-with-wings which is really telling the database to look look for get the image from the database where title is = fish-with-wings, and it spits out the base64 for that file.
The advantages of having everything in the database are that for content writers its easier to reference a file and you can delete or purge, or even modify with some cool AJAX and it's also useful to stop hotlinking, which facebook hasn't done here but you could say, if the url is the the full path the redirect to a hotlink warning.
There is a my version of rsrc.php
$request = basename($_SERVER[REQUEST_URI]);
$dotIndex = strrpos($request, ".");
$extension = substr($request, $dotIndex+1);
switch ($extension):
case 'js': $content_type="application/javascript"; break;
default: $content_type="text/css"; break;
endswitch;
$file = Gdecode($request);
$script_file = dirname(__FILE__)."/".$extension."/".$file.".".$extension;
$fp = #fopen($script_file, "r");
if($fp):
fclose($fp);
header('Content-type: '.$content_type);
echo file_get_contents($script_file);
endif;
Don't think it's related to CDN purposes, woulden't make sense running it through an "static" service to serve up dynamic generated content.
I do think however this might be used to hold an open connection, and push data through for facebook updates, ( that's where the xml would make sense for me ).
All of script/css files of Facebook are stored in database and Facebook uses rsrc.php to get them.
rsrc.php code may look like this:
$request = basename($_SERVER["REQUEST_URI"])
if($request != " ") {
$sql = "SELECT * FROM scripts";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
header('Content-type: '.$row["type"]);
echo $row["script"];
}
}
}