Concept
How do you open and validate files in PHP?
ComputerScienceOne / Opening Files
"Files are represented in PHP as a “resource” (also referred to as a handle) that can be passed around to other functions to read and write to the file. For our purposes, a resource is simply a variable that can be stored and passed to other functions. To open a file, you use the fopen() function (short for file open) which requires two arguments and returns a file handle. The first argument is the file path/name that you want to open for processing. The second argument is a string representing the “mode” that you want to open the file in. There are several supported modes, but the two we will be interested in are reading, in which case you pass it \"r\" and writing in which case you pass it \"w\". The path can be an absolute path, relative path, or may be omitted if the file is in the current working directory.\n\n1 //open a file for reading (input):\n\n2 $input = fopen(\"/user/apps/data.txt\", \"r\");\n\n3 //open a file for writing (output):\n\n4 $output = fopen(\"./results.txt\", \"w\");\n\n5\n\n6 if(!$input) {\n\n7 printf(\"Unable to open input file\n\n\");\n\n8 exit(1);\n\n9 }\n\n10\n\n11 if(!$output) {\n\n12 printf(\"Unable to open output file\n\n\");\n\n13 exit(1);\n\n14 }"
Related Ideas
- What is 22?ComputerScienceOne · Opening Files
- How can you write values to a plaintext file in PHP?ComputerScienceOne · Using URLs
- How can PHP use URLs as file names?ComputerScienceOne · Closing Files
- How do file names, extensions, and working directories affect file paths?ComputerScienceOne · Paths
- What types of errors can occur when processing files?ComputerScienceOne · Error Handling
- How are files read, written, and properly managed?ComputerScienceOne · Paths
- How does PHP perform basic input and output?ComputerScienceOne · Basic I/O
- How do fprintf() and fscanf() read from and write to plaintext files?ComputerScienceOne · Plaintext Files