"ifelse" command in the "include" - php

where in error?
<?
if($_GET['data'])
{
print 'atmam';
include ('http://downloads.website.com/download/3725f5eea93437e9de52f9b15854f5c1');
}
else {
print 'fail to download'; }
?>
Written on the screen error:
Warning: Unexpected character in input: '' (ASCII=1) state=1 in http://downloads.website.com/download/3725f5eea93437e9de52f9b15854f5c1 on line 515
Parse error: syntax error, unexpected T_STRING in http://downloads.website.com/download/3725f5eea93437e9de52f9b15854f5c1 on line 515
PS: http://downloads.website.com/download/3725f5eea93437e9de52f9b15854f5c1 = direct file download link
Can you help?
Best regards

See if this does something like what you want:
<?php
if ($_GET['data']) {
// Some headers that indicate a generic download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment');
// Try and read the file directly to the client
if (!#readfile('http://downloads.website.com/download/3725f5eea93437e9de52f9b15854f5c1')) {
// Try and clear the header and print a message. This may not work depending on the result of the readfile() attempt.
#header('Content-Disposition:');
print 'fail to download';
}
exit;
}
?>
An alternative (and many would argue better) approach is this:
<?php
if ($_GET['data']) {
// Redirect the client to the actual location
header('HTTP/1.1 302 Found');
header('Location: http://downloads.website.com/download/3725f5eea93437e9de52f9b15854f5c1');
exit;
}
?>

PHP provides a function called file_exists for this purpose. $_GET['data'] is for getting information out of the html element with name="data" attached to it. If you do not have this in your document the script will NEVER run as its looking for something that doesn't exist. Even if the element does exist, this is not a necessary nor recommended use of $_GET.
To find out more about what you're trying to do check this link, and look at my examples.
http://php.net/manual/en/function.file-exists.php
To use it you simply do this:
$filename = 'http://downloads.website.com/download/3725f5eea93437e9de52f9b15854f5c1';
if (file_exists($filename)) {
echo 'atmam';
include ('$filename');
}
else
echo 'Failed to download file';
I'm assuming you are going to use this for any files your site has to access, to save you time you can use it in a function.
function testfile(filename) {
if (file_exists(filename)) {
echo 'atmam';
include ('filename');
}
else
echo 'Failed to download file';
}
Call the function like this:
$filename1 = 'http://downloads.website.com/download/3725f5eea93437e9de52f9b15854f5c1';
$filename2 = 'something.txt';
function testfile($filename1);
Using the function you can check as many file names as you want using variables for each file name.
Edit: To solve the syntax error that is coming up, you must make sure the file being included has no errors. Please post it here for us to look at. Removing echos and prints will change nothing, in fact you want those in there in order to debug. First try using the small bit of code I've put here, this is the correct method to check if a file exists, and if it does, do something. Once you are using the correct code to check the file and include it, then you will be sure that once you fix any issues in the include file you are going to have the functionality you want.
Hope this helps you out!
-Sean

Related

How to echo error message if include can't find the file

I use a php script to include another php file. When someone goes to the index.php with the wrong string, I want it to show on the screen an error message.
How do I make it show a custom error message like "You have used the wrong link. Please try again."?
Here is what I am doing now...
Someone comes to the URL like this...
http://example.com/?p=14
That would take them to the index.php file and it would pick up p. In the index.php script it then uses include ('p'.$p.'/index.php'); which finds the directory p14 and includes the index.php file in that directory.
I am finding people, for what ever reason, are changing the p= and making it something that is not a directory. I want to fight against that and just show an error if they put anything else in there. I have too many directories and will be adding more so I can't just us a simple if ($p != '14'){echo "error";} I would have to make about 45 of those.
So what is a simple way for me to say.... "If include does not work then echo "error";"?
$filename = 'p'.$p.'/index.php';
Solution1:
if(!#include($filename)) throw new Exception("Failed to include ".$filename);
Solution2: Use file_exists - this checks whether a file or directory exists, so u can just check for directory as well
if (!file_exists($filename)) {
echo "The file $filename does not exist";
}
You should never use this include solution, because it can be vulnerable to code injection.
Even using file_exists is not a good solution, because the attacker can try some files in your server that was not properly secured and gain access to them.
You should use a white list: a dictionary containing the files that the user can include referenced by an alias, like this:
$whiteList = array(
"page1" => "/dir1/file1.php",
"page2" => "/dirabc/filexyz.php"
)
if (array_key_exists($p, $whiteList)) {
include_once($whiteList[$p]);
} else {
die("wrong file");
}
In this way you do no expose the server files structure to the web and guarantee that only a file allowed by you can be included.
You must sanitize the $p before using it:
$p = filter_input(INPUT_GET, "p", FILTER_SANITIZE_STRING);
But depending on the keys that you use in the dictionary, other filters should be used... look at the reference.
if(!file_exists('p'.$p.'/index.php')) die('error');
require_once('p'.$p.'/index.php');

Best way to see if a view file (.ctp) exists in Cake PHP?

I am using CakePHP 3, and would like to change the behaviour of the handy PagesController which comes with the installation.
The current solution they use when trying to find and render a view file (.ctp) is using a try{} block, which is working well.
Actual code:
try {
$this->render(implode('/', $path));
} catch (MissingTemplateException $e) {
But in my case the most common situation will be that the .ctp file does not exist. (If it does not exist, it will go on with a default view and try fetch content from database, but it is not my problem here.)
In my modified version the most normal case will be that the MissingTemplaceException is thrown, which seem a bit overkill.
Why can I not simply check if the file exists?
Am I thinking right here? And if I am, how do I check for the file's existence?
After some fiddling around, I found the APP constant. This works:
$path = func_get_args();
$file = APP.'Template'.DS.'Pages'.DS.implode('/', $path).'.ctp';
if (file_exists($file))
{
// Render the file.
}
else
{
// Render some default file.
}
Why can I not simply check if the file exists?
I don't know why you can't. Just use file_exists()?
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}

Php problem eval/html/php

I've been writing a php/html page encoder/decoder... I know it already exists but it's a university project so go on XDDD
I encode the pages that I want to protect let's say hypothetically with base64_encode and when I receive a request of any pages I have a loader that reads the coded page, decrypts it and with eval executes it. The real problems arise when I try to decrypt and execute a mixed php/html page. Obviously eval can't execute html code so my question is do I really become crazy about splitting the page executing the php code and print the html? And also if I include an encoded php or php/html page do I really have to reuse the method up here?
I hope someone can really help me because i have a week left before the deadline and I can't change the project at this point.
chris here the function and the fisrt calling in $param[0] i've got the filename called
function MyInclude($filename)
{
// create the temp file
$temp_filename = "tmp.php";
$handle = fopen($temp_filename , 'w+');
if (!$handle)
die('Error creating temp file');
// write the decrypted data, close the handle
$tmp=file_get_contents($filename);
$data=MCrypt_Decode($tmp,'PFL_EPU_V100_mia');
fwrite($handle,$data );
fclose($handle);
// start output buffering to contain any output the script creates
ob_start();
try {
include($temp_filename);
} catch (Exception $e) {
die('There was an error in the encrypted file, cannot process');
}
// get the output, clear the buffer
$output = ob_get_contents();
ob_end_clean();
//destroy the temp file
unlink($temp_filename);
// now you can output the buffer, if desired:
echo $output;
}
MyInclude($param[0]);
the $param[0] file here
<?php
session_start();
$_SESSION['title']='Home';
MyInclude("header.php");
?>
<body>
sono il body <?php echo APP_PATH; ?>
</body>
<?
echo "boss";
MyInclude("footer.php");
?>
any idea about it??? or you need some other code??? let me know T_T
Mike
You can eval() a string that contains mixed html and php, just so long as the tags are included.
http://php.net/manual/en/function.eval.php
When eval() encounters a php close tag (?>), it will stop trying to treat it as php code and just echo everything out until it comes to a php open tag.
The typical solution to your problem is something like this:
$file = ... //Your decoded php/html code here
$file = '?>' . $file; //Add a close tag to the beginning;
ob_start();
eval($file);
$output = ob_get_clean();
echo $output; //Or do something else with it... really, if you're
//just going to be echoing it you can skip the output buffering
Is it possible to decrypt the page, write it to a file, then include it? That would let the PHP interpreter do what it does best - interpret PHP documents. That will include HTML/PHP combinations without relying on eval.
The outline of that would be:
// create the temp file
$temp_filename = "tmp.php";
$handle = fopen($filename , 'w');
if (!$handle)
die('Error creating temp file');
// write the decrypted data, close the handle
fwrite($handle, $decrypted_data);
fclose($handle);
// start output buffering to contain any output the script creates
ob_start();
try {
include_once($temp_filename);
} catch (Exception $e) {
die('There was an error in the encrypted file, cannot process');
}
// get the output, clear the buffer
$output = ob_get_contents();
ob_end_clean();
//destroy the temp file
unlink($temp_filename);
// now you can output the buffer, if desired:
echo $output;
Function references
fopen: http://us2.php.net/manual/en/function.fopen.php
fwrite: http://us2.php.net/manual/en/function.fwrite.php
fclose: http://us2.php.net/manual/en/function.fclose.php
ob_start: http://us2.php.net/manual/en/function.ob-start.php
ob_get_contents: http://us2.php.net/manual/en/function.ob-get-contents.php
ob_end_clean: http://us2.php.net/manual/en/function.ob-end-clean.php
unlink: http://www.php.net/manual/en/function.unlink.php
You will need dump the decoded file to another file and include(); it. The eval approach will not work because it will exit with a parse error if the first item in the file is not either an opening <?php tag, or a valid bit of PHP code.
More than this, you will need to find/replace any occurences of include(), require(), include_once(), and require_once() within the encrypted file with a different function, to ensure you don't try to execute another encrypted file before it has been decrypted. You could do this at execution (ie decryption) time, but it would be much better to it a encryption time, to minimise the time required to pre-fetch the code before it is executed.
You can define these customised functions to decrypt a file and include/require it in your loader script.
Your problem description is a bit vague however your problem seems to be solvable with output buffering.
Have you tried decrypting the page, then parsing the text to split out anything between and then only executing that code?

file_get_contents not working on production server, fine on local

I have a PHP script that fetches an image from a remote server so that I can manipulate it using HTML5 canvas API.
<?php
if ((isset($_GET['url']))) {
$url = $_GET['url'];
$file_format = pathinfo($url, PATHINFO_EXTENSION);
try
{
header("Content-Type: image/$file_format");
header("Content-disposition: filename=image.$file_format");
$img = file_get_contents($url);
echo $img;
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
else die('Unknown request');
?>
A typical request would look like this:
fetch_image.php?url=http://example.com/images/image.png
Everything works fine on my local server but the production server gives me this error:
NetworkError: 500 Internal Server Error.
The error log registers this message:
PHP Warning: Cannot modify header information - headers already sent.
I have tried some of the suggestions but its not working:
allow_url_fopen = 1
Check that the server allows you to open remote URLs with the file functions (the php.ini "allow_url_fopen" setting must be "true").
Try
ob_start()
in the beginning and
ob_end_flush()
at the end of the script. Also make sure that the script contains no characters before the <?php.
You should make sure that your hosting provider has not disabled remote URL fetching for security reasons. The setting is allow_url_fopen and you can inspect current configuration with phpinfo(). In such case, file_get_contents() should return FALSE so you must test $img against false with the === operator.
Try this way
<?php
if ((isset($_GET['url']))) {
$url = $_GET['url'];
$file_format = pathinfo($url, PATHINFO_EXTENSION);
try
{
ob_clean();
ob_start();
header("Content-Type: image/$file_format");
header("Content-disposition: filename=image.$file_format");
$img = file_get_contents(urlencode($url));
// as per manual "If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode(). "
echo $img;
echo ob_get_clean();
exit();
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
else die('Unknown request');
?>
one more solution from manual
Sometimes you might get an error opening an http URL.
even though you have set "allow_url_fopen = On" in php.ini
For me the the solution was to also set "user_agent" to something.
The headers gets sent when you start outputting content. So somewhere before the code you've supplied above, content gets echoed out (from PHP or in plain HTML or javascript). You need to hunt down where that happens.
you should check for encoding of the file as utf8 will break the headers
check if your file does not print any other data before it runs the script.

The whole index.php?=<filename>.exe

I've never really understood on how to do it. I want to where where I can type my address, followed by /index.php?=<a file that is on the FTP>.exe. From there, I would be direct to a page that has a download now button and maybe something like a ad.
Anyone have any tutorials or guides that I may look at?
Im gonna bite ...
The PHP script ensures the file is not accessible from the outside, and only on a per-request basis with possible authentication. When you see:
download.php?file=sdjasdk.exe
The download script looks a bit like:
<?php
if( $_SESSION['auth'] == TRUE){
$file = fileopen($whatever);
echo "mimetype crap"
//spit out file
}else{
echo "not authorized bozo"
}
?>
DOne.
I think he is on about simple $_GET requests >.<
<?php
$file = $_GET['file'];
if (file_exists($file)) {
header('Content-Type: application/octet-stream');
echo file_get_contents($file);
}
?>
Ofcourse this is a very basic example with no security at all. Its not reccomended for you to use this in production without upping security on it.

Categories