PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label fopen. Show all posts
Showing posts with label fopen. Show all posts

Monday, November 21, 2022

[FIXED] What is unsafe about fopen?

 November 21, 2022     c, c11, fopen, tr24731, visual-studio     No comments   

Issue

When using fopen(), Microsoft Visual Studio prints

warning C4996: 'fopen' was declared deprecated`

As reason is given:

This function or variable may be unsafe. Consider using fopen_s instead.

What is unsafe with fopen() that's more safe with fopen_s()?

How can fopen() be used in a safe way (if possible)?

I don't want to know how to suppress the warning - there are enough Stack Overflow articles that answer that question.


Solution

The Microsoft CRT implements the secure library enhancements described in C11 Annex K. Which is normative but not mandatory. fopen_s() is described in section K.3.5.2.1. Also covered by rule FIO06-C of the CERT institute.

At issue is that fopen() dates from simpler times when programmers could still assume that their program was the only one manipulating files. An assumption that has never really been true. It does not have a way to describe how access to the file by other processes is limited, CRT implementations traditionally opened the file without denying any access. Non-standard alternatives have been used to fix this problem, like _fsopen().

This has consequences if the file is opened for writing, another process can also open the file for writing and the file content will be hopelessly corrupted. If the file is opened for reading while another process is writing to it then the view of the file content is unpredictable.

fopen_s() solves these problems by denying all access if the file is opened for writing and only allowing read access when the file is opened for reading.



Answered By - Hans Passant
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, November 2, 2022

[FIXED] Why filestream.close not available

 November 02, 2022     fclose, file, filestream, fopen, vala     No comments   

Issue

I see following code example on this Vala documentation page:

public static int main (string[] args) {
    // Opens "foo.txt" for reading ("r")
    FileStream stream = FileStream.open ("foo.txt", "r");
    assert (stream != null);

    // buffered:
    char buf[100];
    while (stream.gets (buf) != null) {
        print ((string) buf);
    }

    return 0;
}

However, I cannot find a close() function. I want to open file once for reading and later again for writing. Is it safe to do so without a close in between?

(I do not want to use a+ etc mode which permit both reading and writing as both may not be needed while running the application.)


Solution

There are two key items at play:

  1. The FileStream class is a binding to standard C library functions (e.g. open for fopen, read for fread, etc.). (See: this Stack Overflow answer for a good overview of various file APIs)
  2. Vala does automatic reference counting and will free objects for you (See: Vala's Memory Management Explained).

Now if we look at the definition for the FileStream Vala binding, we see:

[ CCode ( cname = "FILE" , free_function = "fclose" ) ]
public class FileStream

Notice the free_function = "fclose" part. This means that when it comes time for Vala to free a FileStream object, it will implicitly call fclose. So no need to attempt this manually. (Also see: Writing VAPI files under the Defining Classes section for details on free_function)

What this means for you is that once your stream object goes out of scope, reference count hits 0, etc. it will get cleaned up for you as you would expect with any other object. You can safely open the file for reading again later by using FileStream.open and getting a new FileStream object.



Answered By - avojak
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to open make hyperlink for txt files

 November 02, 2022     file, fopen, html, php, txt     No comments   

Issue

I created 3 text files and I want to create a bullet form list with hyperlinks that will direct the user to each file created. How can I code this?

echo "<ul>";
echo "<li>" . <a fopen("test.txt", "r") or die("Unable to open file!");>Test 1</a>  "</li>";
echo "<li>"  . $filename = 'test2.txt' . "</li>";
echo "/<ul>";

Solution

Please note that /<ul> is not the correct closing tag, it should be </ul>

On the other hand, you may use the Nowdoc string quoting syntax (or similar):

<?php
echo <<<'EOD'

<ul>
<li><a href='test.txt'>Test1</a></li>
<li><a href='test2.txt'>Test2</a></li>
</ul>

EOD;

?>

For further reference on the above , please view the official documentation:

http://docs.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc



Answered By - Ken Lee
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, August 30, 2022

[FIXED] How do I seperate CSV headers and columns in PHP

 August 30, 2022     csv, fopen, php     No comments   

Issue

I am trying to create a csv with PHP, that separate the the headers and columns.

Currently I am able to create the csv and dump the data, but each row in dumped into one cell.

The result is: enter image description here

I expected this:

enter image description here

Here is my code

<?php
// Load the database configuration file 
require_once('db/connect_db.php');

//$time = date('Y-m-d:').preg_replace("/^.*\./i","", microtime(true));
    $time = date('Y-m-d');
    $dteTimetamp = date('Y-m-d');
// Fetch records from database 
    $find = $conn->prepare("SELECT School, SchoolAddress, School_Email, Principle_Name,  Reception_Number,  QuantityFingerPrintScanner, InvoiceNumber from School");
    $find->execute();
    $udonr = "$dteTimetamp" . "Request";
    //$filename = "$udonr.csv";
// Create a file pointer 
    $f = fopen(dirname(__FILE__).'/testfolder/'.$udonr.'.csv', 'w'); 
 
// Set column headers 
    $header = array('School Name', 'Contact Person', 'Contact Number', 'School Address', 'Number of scanners to deliver', 'Invoice Nuber'); 
    fputcsv($f, $header); 

// Output each row of the data, format line as csv and write to file pointer 
    while($row = $find->fetch(PDO::FETCH_ASSOC)){ 
    $lineData = array($row['School'], $row['Principle_Name'], $row['Reception_Number'], $row['SchoolAddress'], $row['QuantityFingerPrintScanner'], $row['InvoiceNumber']); 
    fputcsv($f, $lineData); 

 
// Set headers to download file rather than displayed 
//header('Content-Type: text/csv'); 
// header('Content-Disposition: attachment; filename="' . $filename . '";'); 
 
//output all remaining data on a file pointer 
fpassthru($f); 
} 
//exit; 

Solution

@FROSIT is right. Excel is kinda dumb about opening CSV files, especially ones with comma separator (ironically). Your file looks good but if you need to have it automatically open in Excel (e.i. someone else will need to open it), you might want to find which one is the default separator for Excel and set that in your script.



Answered By - phoenix
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 21, 2022

[FIXED] How can i write text on a file in c?

 July 21, 2022     append, c, file, fopen, stdio     No comments   

Issue

I am programming a simple text editor in c and I defined a structure named node and created a linked list named textbuffer. I am trying to create an insert function for the text editor. Here is the code so far:

#include <stdio.h>
#include <string.h>

struct node
{
    char statement[40];
    int next;
};
struct node textbuffer[25];

int free_head;
int inuse_head;

void insert(int line, char* stat)
{
    FILE *file;
    file=fopen("texteditor.txt","w");
    
    if(file!=NULL)
    {
        int i;
        int k;
        
        strcpy(textbuffer[line].statement,stat);
        textbuffer[line].next=line+1;
        fprintf(file,textbuffer[line].statement);
        
        for(i=0;i<=25;i++)
        {
            if(textbuffer[i].statement==NULL)
            {
                free_head=i;
                break;
            }
        }
        
        for(k=0;k<=25;k++)
        {
            if(textbuffer[k].statement!=NULL)
            {
                inuse_head=k;
                break;
            }
        }
    }
    else
    {
        printf("File couldn't found.");
    }
    fclose(file);
}


int main()
{
    insert(1,"Hello World");
    return 0;   
}


The problem is when texteditor.txt file is empty and when i run the code it writes "Hello World" in the file, that's fine but when i run it for the second the, i am expecting it to write "HelloWorldHelloWorld" but it doesn't do anything.it's still staying as "Hello World". How can i solve this?


Solution

You can simply open the file in append mode:

file=fopen("texteditor.txt","a");

More info: https://en.cppreference.com/w/c/io/fopen



Answered By - HARSH MITTAL
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, March 24, 2022

[FIXED] Create a stream from a resource

 March 24, 2022     fopen, php, php-stream-wrappers, psr-7, stream     No comments   

Issue

I know that I can create a PHP stream from a filename (a real one, or an URL), by using the <a

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, February 18, 2022

[FIXED] fopen("php://input", "r") returns 0

 February 18, 2022     fopen, mamp, php     No comments   

Issue

I have the line

$input = fopen( "php://input", "r" );

in a php script and I can't figure out why it is returning 0. It is only doing so on my local MAMP set up. I think it is a permission issue but I am not sure what permissions I need to modify.


Solution

in some server for security reason allow_url_fopen set 0 in php.ini . search for this string allow_url_fopen and set it to 1 and restart apache service



Answered By - Yuseferi
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 15, 2022

[FIXED] Localhost and fopen

 January 15, 2022     codeigniter, fopen, mamp     No comments   

Issue

We are now working in a local environment, rather than working live, which is a good thing. However, I've run into a hiccup I don't know how to fix. My code (CodeIgniter) looks like this:

if (!is_dir(base_url() . 'channel-partners/html/camera-registration/' . $name_url)) {
        mkdir(base_url() . 'channel-partners/html/camera-registration/' . $name_url);
}

$handle = fopen('/path/to/file/channel-partners/html/camera-registration/' . $name_url . '/index.html', 'w') or die('Can\'t open file');
fwrite($handle, $html);
fclose($handle);

But since I'm running MAMP, $_SERVER['DOCUMENT_ROOT'] equals Applications/MAMP/htdocs, so that won't work. So what can I do to write a file in PHP that would work in both a production environment and a local environment?


Solution

Use the FCPATH or APPPATH constants.

FCPATH will give you the path to the directory where the front controller is located (index.php).

APPPATH will give you the path to the application directory.

Usage:

fopen(FCPATH . 'path/relative/to/frontcontroller/etc/' . $name_url . '/index.html', 'w') ... 


Answered By - Brendan
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, January 14, 2022

[FIXED] fopen permission denied

 January 14, 2022     fopen, lamp, php, ubuntu-10.04     No comments   

Issue

I am getting the following error when I try loading one of my php pages:

[Fri Apr 08 22:59:50 2011] [error] [client ::1] PHP Warning: fopen(tracking_id.txt): failed to open stream: Permission denied in /var/www/basic.php on line 61

Line 61 is the second line from the script below:

$ourFileName = "tracking_id.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fwrite($ourFileHandle, $trackingId);
fclose($ourFileHandle);

Anyone know how this can be resolved?

I am using Ubuntu as the OS, and apache as the webserver.

I used tasksel to install LAMP-server


Solution

Create a file called tracking_id.txt and execute the following command on it:

chmod a+w tracking_id.txt


Answered By - dionyziz
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing