PHP file stops working with no changes made to it - php

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;
}

Related

PHP rename() function not working properly. Alternative access is denied (code: 5)

I am facing a strange situation with php rename() function. I download a file using API and then moved that file to destination folder.
$download_path =
C:\Users\JOHN\AppData\Local\Temp/downloaded_folder/downloaded_file.png
$moving_path = C:\xampp\htdocs\project-1/images/downloaded_file.png
Every time downloading is working perfectly and file downloaded
The rename() function is working alternatively. ie on first time it works second time fails. 3rd time ITS works 4th time fails etc.
ie first time file moved . and second time i am getting warning
Warning:
rename(C:\Users\JOHN\AppData\Local\Temp/downloaded_folder/downloaded_file.png,C:\xampp\htdocs\project-1/images/downloaded_file.png):
Access is denied (code: 5)
Warning: copy(C:\xampp\htdocs\project-1/images/downloaded_file.png):
Failed to open stream: Permission denied
Please see my code below.
if (file_exists($moving_path)) {
#unlink($moving_path);
}
if (file_exists($download_path) && !file_exists($moving_path)) {
if (!rename($download_path, $moving_path)) {
if (copy ($download_path, $moving_path)) {
echo 'no rename but copied';
} else {
echo 'not moved';
}
} else {
echo 'moved';
}
#rmdir(dirname($download_path))
}
Here what happen is first time it's moved and downloaded_file.png coming inside project-1/images folder & echo moved and second time there is no file coming and echo not moved .
Third time downloaded_file.png coming inside project-1/images folder & echo moved and 4th time there is no file coming and echo not moved.
How to solve this issue. Please help. I seen a similar question but that answer also not working for me
It seems that you do not have the correct folder permissions for:
C:\xampp\htdocs\project-1/images/
As you have this directory showing up in your error for the rename and the copy functions. Set this directory's permissions to 750, for your basic needs.
Since you're using windows:
Right Click>Properties>Security Tab
Change the permissions for your user the script is running under to "Read & execute" and "Write".

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.

Resolve relative urls of youtube using PHP

This question is asked before but non of the answers worked for me.
I use the following code to directly copy a file from a remote server to my server,
<?php
set_time_limit(0); //Unlimited max execution time
$remote_file_url = $_GET['url'];
$ext = pathinfo($remote_file_url, PATHINFO_EXTENSION);
$name = basename($remote_file_url);
if(isset($ext)){
$local_file = 'download/'.$name.'.'.$ext;
}
else
$local_file = 'download/'.$name;
$copy = copy( $remote_file_url, "1.mp4" );
if( !$copy ) {
echo "Doh! failed to copy $file...\n";
}
else{
echo "WOOT! success to copy $file...\n";
}
?>
It works well but it doesn't copy the files I get from Youtube. I use 1-Click Youtube Video Downloader extension for Firefox which gives me direct link to youtube videos. I can use these direct links in browser and Internet Download Manager as well.
For example the direct url of
https://www.youtube.com/watch?v=xPXrJwQ5lqQ
is
https://r6---sn-ab5l6nzy.googlevideo.com/videoplayback?ipbits=0&requiressl=yes&sparams=dur,ei,expire,id,initcwndbps,ip,ipbits,ipbypass,itag,lmt,mime,mip,mm,mn,ms,mv,pl,ratebypass,requiressl,source&ei=3DNOWfq4CImGc9rxvcgO&signature=3D188D073D872381433A45462E84928383D10D02.4E0AF7D777E76AA19A576D42983A81F4E62EF84D&lmt=1472135086539955&mime=video%2Fmp4&ratebypass=yes&id=o-ABaoUEn3pBt5SLXdWXlrzCdteMLfLPizrRTPoakDoLSX&expire=1498318908&source=youtube&dur=119.211&itag=22&pl=20&ip=162.217.31.128&key=cms1&redirect_counter=1&req_id=ce038b9993a9a3ee&cms_redirect=yes&ipbypass=yes&mip=159.203.89.210&mm=31&mn=sn-ab5l6nzy&ms=au&mt=1498297234&mv=m
The problem is my code can't copy this file to my server. I would like to know of there is any way to resolve such urls?
The error is
failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in /home/...
thanks in advance.
Well, I have no idea why that happened. (Would it be expired?I hope not) I just managed to try another link for the above video (copy the link using right click) in your code as the $remote_file_url and it worked as expected
How did I get that link?
I've used the underlined library : YouTube-Downloader to the 1-Click Youtube Video Downloader extension (it is inherently used by that extension ) this way you will have more control over the process. Then after hosting the files in your web server. Simply run the index.php and when you use it, you'll get something like :
Then you can automate this last part to suit your needs.
That doesn't mean that all videos could be smoothly downloaded with this method. Because of the used videos that have signatures issue or that are recently uploaded issue and here's the list of issues of Youtube-Downloader
For that There is a fix that is somewhat involved: youtube-dl-php, it is based on a sound principle : there is a very good command line utility to download YouTube videos called youtube-dl : here is the download page
Basically, you'll just call it using php. Then, notice that you'll need its path installed in order for the following to work
After you install Composer, go to your web project folder
and run composer require norkunas/youtube-dl-php as explained in the Github page
When running its example, I've get an error
proc_open() 267 CreateProcess failed
I've never dealt with Symphony before and I've found it particularly interesting to play with YoutubeDl.php and redefine the $arguments passed to createProcess and commenting out much of the less useful configuration options to get rid of that error, give it more time to run with
ini_set('max_execution_time', 300);
And yikes it was downloaded.
You don't have to follow this unless you couldn't figure out a better way. It is just supposed to give you an idea of where lies the problem if you havn'et figure it out. And if you have that problem in the first place.
private function createProcess(array $arguments = [])
{
array_unshift($arguments, $this->binPath ?: 'youtube-dl');
$process = new Process("youtube-dl https://www.youtube.com/watch?v=nDMwW41AlSI");
/*$process->setEnv(['LANG' => 'en_US.UTF-8']);
$process->setTimeout($this->timeout);
$process->setOptions($this->processOptions);
if ($this->moveWithPhp) {
$cwd = sys_get_temp_dir();
} else {
$cwd = $this->downloadPath ?: sys_get_temp_dir();
}
$process->setWorkingDirectory($cwd);*/
return $process;
}
Or you can just write your own code that calls youtube-dl, good luck!

Laravel Storage facade with S3 - cannot download pdf files, get 'Incorrectly nested style tag found' exception

I am running Laravel 5.3. When I try to download one of our csv files from S3:
Storage::disk('s3')->get('files/contract.csv');
...it works fine. But any time I try to get a pdf file from the same S3 location:
Storage::disk('s3')->get('files/contract.pdf');
I get this exception:
InvalidArgumentException with message 'Incorrectly nested style tag found.'
This happens for ALL pdf files, even pdf files that I grab from the net and put on S3 strictly for testing purposes. Is this a bug or am I doing something incorrectly?
By the way, this exception comes from the vendor/symfony/console/Formatter/OutputFormatterStyleStack class:
public function pop(OutputFormatterStyleInterface $style = null)
{
if (empty($this->styles)) {
return $this->emptyStyle;
}
if (null === $style) {
return array_pop($this->styles);
}
foreach (array_reverse($this->styles, true) as $index => $stackedStyle) {
if ($style->apply('') === $stackedStyle->apply('')) {
$this->styles = array_slice($this->styles, 0, $index);
return $stackedStyle;
}
}
throw new InvalidArgumentException('Incorrectly nested style tag found.');
}
Update:
Just to clarify the issue. When I run the test directly on the web app server like so:
Route::get('test', function() {
return Storage::disk('s3')->get('files/document.pdf');
});
It works. It also works if it is inside a command that I execute from the shell.
The way my site actually works is this: the web server makes a request to a worker box which is running a laravel work daemon and it appears that the error I described above is due to it running in a daemon. Both the console command and the web route work fine. Weird.
So the issue all along was that the csv is text data and pdf is binary, which for some reason, prevented my app from returning the pdf data. My solution was to base64 encode the pdf data, after which I was able to return it without issues.

Delete File Even A Fatal Error

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.

Categories