modify permissions for files created by php script - php

How (or can) I change the following php script so that when it creates a new file, it gives the file r/w permission?
<?php
if(isset($_GET['data'])) {
$data = $_GET['data'] . "\n";
$ip = $_GET['ip'];
$ret = file_put_contents('/opt/tomcat7/webapps/servlets/WEB-INF/logs/' . $ip, $data, LOCK_EX);
if($ret === false) {
die('There was an error writing the lab data file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no data to process');
}
?>

Try chmod function.
For example chmod("/somedir/somefile", 0755)

Related

PHP data processing not outputting

Hi I am trying to get this external text file to print inside my php document. The code looks fine to me however when I echo it does not output anything and I am not sure why this is. Can anybody help me out as I am new to this.
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
$fp = fopen($location, 'r');
if ($fp) {
$readin = fread($fp);
fclose($fp);
} else {
echo 'Can\'t open input.txt';
}
Not sure what you're trying to 'echo' but have you checked if the file exists in the first place?
Your code could be written as:
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
if (file_exists($location) && $data = file_get_content($location)){
echo $data;
} else {
echo 'File not found';
}
if (file_exists($location) && $file = fopen($location, 'r')){
$file_content = fread($file, filesize($location));
fclose($file);
} esle {
echo 'File not found';
}
See here for more: http://php.net/manual/en/function.file-get-contents.php, http://php.net/manual/en/function.filesize.php

Unzip a zip archive on a server with php

I've tryed some ways to automatically unzip files with php but all of them failed:
1st variant
<?php
function unzip($file){
$zip=zip_open(realpath(".")."/".$file);
if(!$zip) {return("Unable to proccess file '{$file}'");}
$e='';
while($zip_entry=zip_read($zip)) {
$zdir=dirname(zip_entry_name($zip_entry));
$zname=zip_entry_name($zip_entry);
if(!zip_entry_open($zip,$zip_entry,"r")) {$e.="Unable to proccess file '{$zname}'"; continue; }
if(!is_dir($zdir)) mkdirr($zdir,0777);
#print "{$zdir} | {$zname} \n";
$zip_fs=zip_entry_filesize($zip_entry);
if(empty($zip_fs)) continue;
$zz=zip_entry_read($zip_entry,$zip_fs);
$z=fopen($zname,"w");
fwrite($z,$zz);
fclose($z);
zip_entry_close($zip_entry);
}
zip_close($zip);
return $e;
}
$file = 'file_name.zip';
echo unzip($file);
2nd variant
<?php
$zip = zip_open("my_linkedin_groups_scrape_my_run_1_2015.zip");
if ($zip) {
while ($zip_entry = zip_read($zip)) {
$fp = fopen("./".zip_entry_name($zip_entry), "w");
if (zip_entry_open($zip, $zip_entry, "r")) {
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
fwrite($fp,"$buf");
zip_entry_close($zip_entry);
fclose($fp);
}
}
zip_close($zip);
}
?>
3rd variant
<?php
// assuming file.zip is in the same directory as the executing script.
$file = 'file.zip';
// get the absolute path to $file
$path = pathinfo(realpath($file), PATHINFO_DIRNAME);
$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
// extract it to the path we determined above
$zip->extractTo($path);
$zip->close();
echo "WOOT! $file extracted to $path";
} else {
echo "Doh! I couldn't open $file";
}
?>
for the 3rd case output is Doh! I couldn't open file.zip
What's wrong? Am I something missing?
I
Seems like a problem with write/read rights.
Change the rights for testing purposes on to 0777
I would go with 3rd variant. Try using absolute path to zip file and dump $res in the error message. It will say exactly whats wrong, just compare it with specific error codes http://php.net/manual/en/ziparchive.open.php.

PHP not writing to file from one source

I have an issue I can't seem to find the solution for. I am trying to write to a flat text file. I have echoed all variables out on the screen, verified permissions for the user (www-data) and just for grins set everything in the whole folder to 777 - all to no avail. Worst part is I can call on the same function from another file and it writes. I can't see to find the common thread here.....
function ReplaceAreaInFile($AreaStart, $AreaEnd, $File, $ReplaceWith){
$FileContents = GetFileAsString($File);
$Section = GetAreaFromFile($AreaStart, $AreaEnd, $FileContents, TRUE);
if(isset($Section)){
$SectionTop = $AreaStart."\n";
$SectionTop .= $ReplaceWith;
$NewContents = str_replace($Section, $SectionTop, $FileContents);
if (!$Handle = fopen($File, 'w')) {
return "Cannot open file ($File)";
exit;
}/*
if(!flock($Handle, LOCK_EX | LOCK_NB)) {
echo 'Unable to obtain file lock';
exit(-1);
}*/
if (fwrite($Handle, $NewContents) === FALSE) {
return "Cannot write to file ($File)";
exit;
}else{
return $NewContents;
}
}else{
return "<p align=\"center\">There was an issue saving your settings. Please try again. If the issue persists contact your provider.</p>";
}
}
Try with...
$Handle = fopen($File, 'w');
if ($Handle === false) {
die("Cannot open file ($File)");
}
$written = fwrite($Handle, $NewContents);
if ($written === false) {
die("Invalid arguments - could not write to file ($File)");
}
if ((strlen($NewContents) > 0) && ($written < strlen($NewContents))) {
die("There was a problem writing to $File - $written chars written");
}
fclose($Handle);
echo "Wrote $written bytes to $File\n"; // or log to a file
return $NewContents;
and also check for any problems in the error log. There should be something, assuming you've enabled error logging.
You need to check for number of characters written since in PHP fwrite behaves like this:
After having problems with fwrite() returning 0 in cases where one
would fully expect a return value of false, I took a look at the
source code for php's fwrite() itself. The function will only return
false if you pass in invalid arguments. Any other error, just as a
broken pipe or closed connection, will result in a return value of
less than strlen($string), in most cases 0.
Also, note that you might be writing to a file, but to a different file that you're expecting to write. Absolute paths might help with tracking this.
The final solution I ended up using for this:
function ReplaceAreaInFile($AreaStart, $AreaEnd, $File, $ReplaceWith){
$FileContents = GetFileAsString($File);
$Section = GetAreaFromFile($AreaStart, $AreaEnd, $FileContents, TRUE);
if(isset($Section)){
$SectionTop = $AreaStart."\n";
$SectionTop .= $ReplaceWith;
$NewContents = str_replace($Section, $SectionTop, $FileContents);
return $NewContents;
}else{
return "<p align=\"center\">There was an issue saving your settings.</p>";
}
}
function WriteNewConfigToFile($File2WriteName, $ContentsForFile){
file_put_contents($File2WriteName, $ContentsForFile, LOCK_EX);
}
I did end up using absolute file paths and had to check the permissions on the files. I had to make sure the www-data user in Apache was able to write to the files and was also the user running the script.

Stream ftp file to browser

I am trying to retrieve and stream a file to the browser from an ftp site.
The error is:
Warning: ftp_nb_get() expects parameter 2 to be string, resource given
I know that it is a resource but how do I get around this?
if(isset($_GET['filename'])){
$requestfilename = $_GET['filename'];
if($sockets = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP)){
stream_set_write_buffer($sockets[0], 0);
stream_set_timeout($sockets[1], 0);
if($ftp_connection = ftp_connect($ftp_server)){
if (#ftp_login($ftp_connection, $ftp_user, $ftp_pass)) {
if(#ftp_chdir($ftp_connection, $ftp_dir_new)){
if($ret = ftp_nb_get($ftp_connection, $sockets[0], $requestfilename, FTP_BINARY)){
while(ftp_nb_continue($ftp_connection)==FTP_MOREDATA){
$contents = stream_get_contents($sockets[1]);
if($contents !== false) {
echo $contents;
flush();
}
}
if ($ret != FTP_FINISHED) $error[] = 'There was an error downloading the file...';
}else{
$error[] = "Could not ftp_nb_get file from $ftp_server";
}
}else{
$error[] = "Couldn't cd to $ftp_dir_new";
}
} else {
$error[] = "Couldn't connect as $ftp_user";
}
}else{
$error[] = "Couldn't connect to $ftp_server";
}
}else{
$error[] = "Unable to create socket pair";
}
if($sockets){
fclose($sockets[0]);
fclose($sockets[1]);
}
if( ! empty($ftp_connection)) ftp_close($ftp_connection);
}
So you're looking for an alternative to ftp_nb_get() that allows you to write to STDOUT or an arbitrary stream, instead of a local file?
I've not used this module at all, but it looks like ftp_nb_fget does what you want.
I know it's an old topic, but I came across this code and found small bug. Maybe someone uses it and has problem making it work.
This code won't work for very small files because ftp_nb_continue won't return FTP_MOREDATA even once. To fix this you need to change while loop to:
while($ret == FTP_MOREDATA){
$contents = stream_get_contents($sockets[1]);
if($contents !== false) {
echo $contents;
flush();
}
$ret = ftp_nb_continue($ftp_connection);
}

File from SOAP, how to save?

I am working with a client on getting a gzip from their webservice. I am able to get a response with my following call:
$response = $client->call('branchzipdata', $param);
$filename = "test.gzip";
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $response) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
Now when I attempt to write that a file, such as 'test.gzip', I am unable to open it afterwards... most likely because I am doing something horrible wrong. Any insight would be appreciated.
EDIT:
For some reason I was saving the file as '.gzip' instead of '.gz'... So in order to have it work I now have:
$response = $client->call('call', $param);
$content = base64_decode($response);
$filename = "output_zip.gz";
if (!$handle = fopen($filename, 'w')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $content) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
fclose($handle);
echo system("gzip -d $filename");
(Edited based on the comments)
If the return value is base64-encoded, you need to base64-decode it before you write it to the file. Alternatively you could write it out to a file which you then base64-decode to another file before trying to open it, but that seems a bit pointless compared with just decoding it when you first get it.

Categories