Delete File Even A Fatal Error - php

I am trying to create an online php editor .Alternative to eval , i am doing it as
Get the codes by form post (having an iframe as target) request and save it in a temp file
including that temp file ,so codes gets executed
deleting that temp file
CODE
<?php
session_start();
if(isset($_POST['winCode']))
{
$data=$_POST['winCode'];
$_SESSION['data']=$data;
// creating a $_SESSION['data'] ,so that
// user can maximize the resultant iframe
}
file_put_contents(session_id()."_runphp.php",$_SESSION['data']);
include(session_id()."_runphp.php");//generate output
unlink(session_id()."_runphp.php");//delete temp file
?>
This is working well , but when a user generates error by his codes ..unlink doesn't work .. How can i set unlink to run even a fatal error occurs.

Use register_shutdown_function.
Follow the link http://php.net/manual/en/function.register-shutdown-function.php
register_shutdown_function( "shutdown_handler" );
function shutdown_handler() {
// delete file here
}
Note: This is not a good practice to execute the user entered code as it is. This system to open to Cross Site Scripting Attacks.

Related

PHP file stops working with no changes made to it

I am trying to get a website to work, but cannot figure out how to edit the server PHP file without the website crashing. I am not getting many hits on google looking for this issue.
I am attempting to build a "stripe checkout" page, where you can put a hold on a card. I did not write any of this code, but got it on github.
https://github.com/stripe-samples/placing-a-hold
The index.php file is what I am trying to edit, but this is where I am having trouble:
https://github.com/stripe-samples/placing-a-hold/tree/master/using-webhooks/server/php
If I download the github link and open the php file through my browser, I get a checkout page as expected. However, if I copy and paste the file on my desktop, open it, save it (no edits), close it, and re-upload it to the server, it gives me a white screen. If I re-upload the original php file it works again. I dont see how two identical php files can give me this result. I was thinking that saving the php file changes the permissions associated with the file? but I did a chmod 777 to the entire directory, and it still doesn't work.
I don't have much coding experience. I checked the server error it says:
PHP Fatal error: Uncaught RuntimeException: Unexpected data in output buffer. Maybe you have characters before an opening <?php tag? in /var/www/html/server/php/vendor/slim/slim/Slim/App.php:625Stack trace:#0 /var/www/html/server/php/vendor/slim/slim/Slim/App.php(333): Slim\App->finalize(Object(Slim\Http\Response))#1 /var/www/html/server/php/index.php(112): Slim\App->run()#2 {main}\n thrown in /var/www/html/server/php/vendor/slim/slim/Slim/App.php on line 625,
going into the App.php file around line 625 it has this:
protected function finalize(ResponseInterface $response)
{
// stop PHP sending a Content-Type automatically
ini_set('default_mimetype', '');
$request = $this->container->get('request');
if ($this->isEmptyResponse($response) && !$this->isHeadRequest($request)) {
return $response->withoutHeader('Content-Type')->withoutHeader('Content-Length');
}
// Add Content-Length header if `addContentLengthHeader` setting is set
if (isset($this->container->get('settings')['addContentLengthHeader']) &&
$this->container->get('settings')['addContentLengthHeader'] == true) {
if (ob_get_length() > 0) {
throw new \RuntimeException("Unexpected data in output buffer. " .
"Maybe you have characters before an opening <?php tag?");
}
$size = $response->getBody()->getSize();
if ($size !== null && !$response->hasHeader('Content-Length')) {
$response = $response->withHeader('Content-Length', (string) $size);
}
}
// clear the body if this is a HEAD request
if ($this->isHeadRequest($request)) {
return $response->withBody(new Body(fopen('php://temp', 'r+')));
}
return $response;
}

The filemtime () isn't working for my script, but is working fine for the script where I copied the example code

I have a .txt file located under some folder of my data files. Now I have created a long polling system (actually copied the code ) which is run by ajax.
Now the problem is that my php script is unable to fetch file modification time of the text file (it totally disregards the file).
Below I have both the original code of the author and my twerked code. The one of the author worked fine, but not mine.
Plz help.
The apache server is hosted on windows server
THe file path is absolutly correct and file exist.
Here's the section of my code which has error
while (true) {
//**The error occurs here**
$fileModifyTime = filectime($file);
if ($fileModifyTime === false) {
throw new Exception('Could not read last modification time');
}
// if the last modification time of the file is greater than the last update sent to the browser...
if ($fileModifyTime > $lastUpdate) {
setcookie('lastUpdate', $fileModifyTime);
require 'msgread.php';
// get file contents from last lines...
$fileRead = tailCustom($file, 8);
exit(json_encode([
'status' => true,
'time' => $fileModifyTime,
'content' => $fileRead
]));
}
// to clear cache
clearstatcache();
// to sleep
sleep(1);
}
here's the original code from where i copied
the author's original polling code
and here's my full code, just in case needed
My script which has error
I suspect that your problem is that file.txt does not exist. have you created it and ensured that it's in the current working directory of the script?
It's impossible to say more without seeing your actual code. If you select it and press Ctrl + K that will indent it all.

Generating unique download link to download once only

I wanna create a few unique download link for my users. The reason is that I wanted to let them download once only, so that they can use back the same link to download again.
I've generate a few of the keys (example, qwertyasdfghzxcbn. As in the download link will be like www.xxxxx.com/download.php?qwertyasdfghzxcbn) in the database and flag field where when the user downloaded, it will update 1 to the flag field.
I did a search on the net and found this.
http://www.webvamp.co.uk/blog/coding/creating-one-time-download-links/
But that only works when you go to the page first then only the page will generate the unique link. I've already pre-generate the link inside my database, I don't need to regenerate again, if fact if I generate the key when user go the page, they will able to download multiple times by refreshing the page.
The solution would be to make the link target itself a PHP script.
You'd hide the actual file somewhere inaccessible from the browser (i.e., somewhere where you can reach the file via fopen(), but isn't within the document root), and put a download.php file to download files.
The download script itself would look something like this:
$fileid = $_REQUEST['file'];
$file = file_location($fileid); // you'd write this function somehow
if ($file === null) die("The file doesn't exist");
$allowed = check_permissions_for($file, $fileid) // again, write this
// the previous line would allow you to implement arbitrary checks on the file
if ($allowed) {
mark_downloaded($fileid, $file); // so you mark it as downloaded if it's single-use
header("Content-Type: application/octet-stream"); // downloadable file
echo file_get_contents($file);
return 0; // running a return 0; from outside any function ends the script
} else
die("You're not allowed to download this file");
Any link you point would simply point to download.php?fileid=712984 (whatever the fileid actually is). That would be the actual download link, since that script does transfer the file; but only if the user is allowed to retrieve it. You'd have to write the file_location(), check_permissions_for() and mark_downloaded() functions yourself though.
I would suggest using uniqid() function, and store unique ids with the expiration date in a database, while returning to the user url with something like this: ...?file_id=$id
When the link is being opened, you may delete it from the database or mark it to be deleted 'soon' (just in case user wants to refresh the page.)

How to display a message if file already exists

I have a javascript function in one page and in another page I have a php script which concentrates on file uploading. At the moment my files are uploading successfully which is great news. My question though is that I want to use the php to check if a file already exists in the folder but I want to use the javascript function to display an message to state file already exists if this is true. How can this be done?
Below is the php code which checks if file exists:
if (file_exists("upload/" . $_FILES["fileImage"]["name"]))
{
}
Below is the Javascript function when file stops uploading. at moment if file doesn't upload it displays a message stating there is an error while uploading file and it displays a message if file is successfully uploaded, but I want an extra message where if file doesn't upload but this is because the file already exists, then I want it to display a message stating file already exists.
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
}
P.S Please no one put in their answer why don't I just put an echo in the php code, I don't want to do it like that because the user never actually navigates to the php script.
In yours PHP code that checks if file exists do
else{
echo 2;
}
In yours JS code in else clausule do
if(success == 2){
result = '<span class="emsg">File already exist!</span><br/><br/>';
}
That is a quick solution, but it gives You a way to do more complex file handling via JS/PHP. For example. When PHP returns a data 1, then everything is ok, when 2 then file exists, when 3 then file is too large, when 4 then file with bad extension, when 5 then something else, and so on.
This method I have encountered when learning C/C++(in C this way is like a standard thing). This way You can give info how some parts of code went.
Still, I would generete a a random name for file, if the name is irrelevant, and if name of file is important then wold use AJAX to check it, and display info about it, or maybe append a number after file name (file(1).xyz, file(2).xyz, file(3).xyz). That depends on what You are trying to achieve.
You say.
P.S Please no one put in their answer why don't I just put an echo in
the php code, I don't want to do it like that because the user never
actually navigates to the php script.
you need to execute some php code anyway. so you will have to do this one way or another. then , display the information to the user using whatever way you want.
since we dont have all the code i assume you have a input[type=file] in the html code , so you need to use ajax with the value of the input. send it to your server , check if the filename already exists , then respond with true or false with ajax from php and execute the code in javascript that will tell the user if the file exists or not. you can use jQuery to do that :
$("#myInput").on("change",function(event){
$.getJSON("checkFileService.php",{filename:$(event.currentTarget).val()},
function(datas){
if(datas.exists === true){
doSomething();
else{
doSomethingElse();
}
}
}
Check the jQuery ajax api for more infos
you'll have to write a php script that outputs some json string like {"exists":true} in order for the client script to work.
#safarov Can you show me an example of a function to see if file already exists, then write different name for new uploaded file?
Save/upload a simple text file named "filenamecounter.txt",
containing only text 1 in it.
<?php
//Get the original name of file
$tmp_name = $_FILES["filename"]["tmp_name"];
//Get/Read File Name Counter
$filenamecounter = file_get_contents('filenamecounter.txt');
//If it is less than 10, add a "0"/Zero to make it like 01,02,03
if (strlen($filenamecounter) <= 1){
$filenamecounter = str_pad($filenamecounter, 2, '0', STR_PAD_LEFT);
}
//Assign Filename + Variable
$name = "filename".$filenamecounter.".txt";
//Save file with new name
move_uploaded_file($tmp_name, $name);
//write quotecounter to file.
$filenamecounter++;
file_put_contents("filenamecounter.txt", $filenamecounter);
?>

Create Thumbnail with SWFUpload

I am attempting a CMS photo gallery and need to create thumbnails at the end of my upload.php file. I have a function called create_square_image that works fine when run on the 'showphotos.php' page. However I don't want it to be run every time someone views the page. I have tried adding the following to SWFUpload...
// Process the file
/*
At this point we are ready to process the valid file. This sample code shows how to save the file. Other tasks
could be done such as creating an entry in a database or generating a thumbnail.
Depending on your server OS and needs you may need to set the Security Permissions on the file after it has
been saved.
*/
$thumb_save = "uploads/thumbs/thumb_" . $_FILES[$upload_name]["tmp_name"];
create_square_image($_FILES[$upload_name]["tmp_name"],$thumb_save,100);
if (!#move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
HandleError("File could not be saved.");
exit(0);
}
exit(0);
The create_square_image function uses this format:
create_square_image ( string $filename , string $destination, size )
I have tried it a few times and it will save the image but not the thumbnail.
Set the permissions on /uploads/thumbs/ to 777. You could also try specifying the absolute path to that location. To see your absolute path use this code: echo getcwd();

Categories