This is a discussion on File Handling in PHP within the PHP Programming forums, part of the Web Development category; Hi Guys, Lets discuss here about the file handling methods in PHP. I wanted to initiate this thread so as ...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| Hi Guys, Lets discuss here about the file handling methods in PHP. I wanted to initiate this thread so as we can discuss in detail on various:
Hope you all provide good support in this thread, so we dwell deeper into this issue. Thanks R.Rajan |
| Sponsored Links |
| |||
| Hi, 1. file() : Return a file data as an Array Eg: $lines = file('test.txt'); foreach ($lines as $line_num => $line) { echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n"; } 2. fopen() : Opens file or URL we can open a file Read / Write Mode. few file open modes describes below.. mode Description 'r' Open for reading only; place the file pointer at the beginning of the file. 'r+' Open for reading and writing; place the file pointer at the beginning of the file. 'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. 'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. 'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. 'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. 'x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. This option is supported in PHP 4.3.2 and later, and only works for local files. 'x+' Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. This option is supported in PHP 4.3.2 and later, and only works for local files. Eg: $handle = fopen("file.txt", "r"); $handle = fopen("file.txt", "w"); 3. file_get_contents() : Reads entire file into a string Eg: $vFileData = file_get_contents("read.txt"); |
| |||
| And one more question, I am working in flash action script. I wana do one flash uploader by using the server side script php. Can anyone give the code for that? I can send the file binary data to php by using File reference object. If u wants the flash code I can post that too. Thanks |
| |||
| I do not have code for this. So far in this discussion what i know is there are various ways we can handle File. 1. FTP 2. HTTP 3. CURL 4. Socket All those are used to handle file and communicate with other server but can anybody tell me what exactly they doing and which techinique we used and where? |
| |||
| Hi! I am a newbie to ActionScript, and as GEOBLOW asked, i need to do a flash uploader for one of my project. Before that i wanna know the step by step process or lifecycle of HTTP Uploading from Flash. Is there any Techies to help me? ![]()
__________________ Cheers!!!
Last edited by PixelNameVj : 08-03-2007 at 06:03 AM. |
| |||
| Reading a Remote File Using PHP To read a remote file from php you have to use any of these options : 1. Use fopen() 2. Use file_get_contents() 3. CURL 4. Make your own function using php's socket functions.
__________________ Thanks & Regards Sabari... |
| |||
| Quote:
Plz can you give the complete php code for flash uploader? |
| |||
| Here explained each of the file handling option little bit detailed.. 1 . Using fopen() If you use fopen() to read a remote file the process is as simple as reading from a local file. The only difference is that you will specify the URL instead of the file name. Take a look at the example below : // make sure the remote file is successfully opened before doing anything else if ($fp = fopen('http://www.google.co.in/', 'r')) { $content = ''; // keep reading until there's nothing left while ($line = fread($fp, 1024)) { $content .= $line; } echo $content; // do something with the content here // ... } else { echo "an error occured when trying to open the specified url"; } Now, the code above use fread() function in the while loop to read up to 1024 bytes of data in a single loop. That code can also be written like this : // make sure the remote file is successfully opened before doing anything else if ($fp = fopen('http://www.google.co.in/', 'r')) { $content = ''; // keep reading until there's nothing left while ($line = fgets($fp, 1024)) { $content .= $line; } echo $content; // do something with the content here // ... } else { echo "an error occured when trying to open the specified url"; } instead of fread() we use fgets() which reads one line of data up to 1024 bytes. The first code is much more preferable than the second though. Just imagine if the remote file's size is 50 kilobytes and consists of 300 lines. Using the first code will cause the loop to be executed about fifty times but using the second the loop will be executed three hundred times. If you consider the cost to call a function plus the time required to make 300 requests compared to just 5 then clearly the first one is the winner. 2. Using file_get_contents() This is my favorite way of reading a remote file because it is very simple. Just call this function and specify a url as the parameter. But make sure you remember to check the return value first to determine if it return an error before processing the result $content = file_get_contents('http://www.google.co.in/'); if ($content !== false) { // do something with the content } else { // an error happened } 3. CURL Unlike the two methods above using CURL cannot be said as straigthforward. Although this library is very useful to connect and communicate with may different protocols ( not just http ) it requires more effort to learn. And another problem is that not all web host have this library in their php installation. So we better make sure to check if the library is installed before trying to use it. Here is a basic example on fetching a remote file // make sure curl is installed if (function_exists('curl_init')) { // initialize a new curl resource $ch = curl_init(); // set the url to fetch curl_setopt($ch, CURLOPT_URL, 'http://www.google.co.in'); // don't give me the headers just the content curl_setopt($ch, CURLOPT_HEADER, 0); // return the value instead of printing the response to browser curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // use a user agent to mimic a browser curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0'); echo $content = curl_exec($ch); // remember to always close the session and free all resources curl_close($ch); } else { // curl library is not installed so we better use something else } In some cases using CURL is faster than using file_get_contents() or fopen(). This is because CURL handles compression protocols by default ( for example gzip ). Many sites, big and small, use gzip compression to compress their web pages in order to save bandwidth. This site, for example, also use gzip compression which cut the bandwidth used into half. So if you're the type who just can't wait CURL will fit you most. 4. Custom functions In the worst case your server will have fopen wrappers disabled and don't have CURL library installed. In this sad situation you just have to make your own way. Our function shall be named getRemoteFile() which takes only one parameter, the url for the remote file. The skeleton for this function is shown below function getRemoteFile($url) { // 1. get the host name and url path // 2. connect to the remote server // 3. send the necessary headers to get the file // 4. retrieve the response from the remote server // 5. strip the headers // 6. return the file content } To extract the host name and url path from the given url we'll use parse_url() function. When given a url this function will spit out the followings : 1. scheme 2. host 3. port 4. user 5. pass 6. path 7. query 8. fragment For example, if the url is “PHP - Google Search then parse_url() will return this: Array ( [scheme] => http [host] => Google [path] => /search [query] => hl=en&q=PHP&meta= ) For our new function we only care about the host, port, path and query. To establish a connection to a remote server we use fsockopen(). This function requires five arguments, the hostname, port number, a reference for error number, a reference for the error message and timeout $url = "http://www.google.co.in/search?hl=en&q=PHP&meta="; $vResult = getRemoteFile($url); echo $vResult; function getRemoteFile($url) { // get the host name and url path $parsedUrl = parse_url($url); $host = $parsedUrl['host']; if (isset($parsedUrl['path'])) { $path = $parsedUrl['path']; } else { // the url is pointing to the host like http://www.discussweb.com $path = '/'; } if (isset($parsedUrl['query'])) { $path .= '?' . $parsedUrl['query']; } if (isset($parsedUrl['port'])) { $port = $parsedUrl['port']; } else { // most sites use port 80 $port = '80'; } $timeout = 10; $response = ''; // connect to the remote server $fp = @fsockopen($host, '80', $errno, $errstr, $timeout ); if( !$fp ) { echo "Cannot retrieve $url"; } else { // send the necessary headers to get the file fputs($fp, "GET $path HTTP/1.0\r\n" . "Host: $host\r\n" . "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.3) Gecko/20060426 Firefox/1.5.0.3\r\n" . "Accept: */*\r\n" . "Accept-Language: en-us,en;q=0.5\r\n" . "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n" . "Keep-Alive: 300\r\n" . "Connection: keep-alive\r\n" . "Referer: http://$host\r\n\r\n"); // retrieve the response from the remote server while ( $line = fread( $fp, 4096 ) ) { $response .= $line; } fclose( $fp ); // strip the headers $pos = strpos($response, "\r\n\r\n"); $response = substr($response, $pos + 4); } // return the file content return $response; } The code above sends nine lines of headers but only the first two is mandatory. So even if you send only these fputs($fp, "GET $path HTTP/1.0\r\n" ."Host: $host\r\n\r\n"); the function will likely be working correctly. Not always though. Since the file is stored in a remote server It really up to that server to reply to your request or not. Some people code their page to block any request without the proper referer header. Some will only accept a specific user agent. Other will require cookies set in the header.
__________________ Thanks & Regards Sabari... |
| |||
| Quote:
Hey Geo... this is KBala, i am pretty good in flash action script and server side scripts. Actually u just need the php server side script to upload a file from flash, but here i try to explain about "File uploading from a flash client app to a web server". Eventhough you are well about flash part, i hope it will be useful for others. Lets first see the Flash part(Action Script 3.0). Create a new flash document and write the below script in frame 1. Code: var fileRef:FileReference = new FileReference(); Code: fileRef.addEventListener(Event.SELECT, selectHandler) Code: fileRef.addEventListener(Event.COMPLETE, completeHandler) Code: private function selectHandler(event:Event):void
{
var request:URLRequest = new URLRequest();
request.url = "http://somename.com/upload.php";
request.method = "POST";
fileRef.upload(request,"Filedata");
} [Note: Open a image file in a Notepad to see the binary data of the image. This binary data will be stored in the fileRef object as a stream of string] Create a URLRequest object as above and make sure the request method should be "POST". And call the upload function of the fileRef object. This function has two params. one is for where to post the binary data, another is post variable name. You can see how this variable name will be used in the server side script. Code: private function completeHandler(event:Event):void
{
Alert.show("One file uploaded");
} Place a button control on the stage and name as "btn" Code: btn.addEventListener(MouseEvent.CLICK, clickHandler);
//listener function
private function clickHandler(event:MouseEvent):void
{
fileRef.browse();
} So far, the flash part will come to the end, let us see the server side script(php) PHP Code: $_FILES['Filedata']['tmp_name'] will return the binary data of the image. $_FILES['Filedata']['name'] will return original name of the image file (with extension). $_FILES['Filedata']['size'] will return size of the image file in bytes. The image file is stored in the "UploadedFiles" folder. This will be created with full permission if it does not exsit. By using "Copy" method, the file will be stored in the "UploadedFiles" folder as same file name. Finally the status will be return back to Flash client app as xml. That's it Geo, i think you will get the exact one that you want. And if you have any doubt regarding this, dont hesitate, feel free to ask me. Thanks -kb |
| |||
| Yes Bala, This one is a good sample program for flash uploader in PHP. Ok, it will be very useful to discuss about how the php will be taking the HTTP uploaded files? Here is the simple tips to understand the flash uploading from any server side scripting. First of all we all should know about how the HTTP request will be proceeded for File uploading and how the data will be handled by the server side scripting. Flash fileReference Object This flash object is used to handle the local files. And you can use the upload method to call the server side script to be executed after the HTTP upload of that particular file. fileRef.upload("upload.php","Filedata");Server side scripting Once the file has been uploaded to the server, the server side php will be executed. In that server side file execution, the server side script will be having the binary data of the uploaded file. Now you can write the binary data of the uploaded file content to your server file path. This is to understand the basic concept of the HTTP uploading. Hope it will be useful for you. thanks ![]()
__________________ Karpagarajan. R Necessity is the mother of invention |
| |||
| hi sabari, Good explanation for the file handling techniques in PHP Here i have given here some more info on CURL functions in PHP to get a web page using CURL The CURL functions are a standard extension for PHP 4.0.2 and later. They are included in most PHP installations. You can check your installation by calling phpinfo() and looking for --with-curl in the Configure Command section at the start of its output. The CURL library manual has more installation information. The CURL functions are built atop libcurl, a cross-platform library also available for Perl, Python, Ruby, C/C++, Java, and other languages. The PHP documentation is an abbreviated form of that available at the libcurl web site. Getting a web page using CURL always includes these steps: 1. Create a CURL handle using curl_init(). 2. Set up the request using curl_setopt() or curl_setopt_array(). 3. Request the page using curl_exec(). 4. Check if an error occurred using curl_errno(). 5. Get the HTTP header using curl_getinfo(). 6. Close the CURL handle using curl_close(). curl_init() The curl_init() function creates a CURL handle to manage the web page request. The only function argument is a URL, which is saved until a later curl_exec() call executes the request. curl_setopt() or curl_setopt_array() The curl_setopt() and curl_setopt_array() functions configure the page request by setting options and their values. These two PHP functions are equivalent: curl_setopt() sets one option at a time, while curl_setopt_array() sets a list of options all at once. Here are the basics options for different uses of CURL for getting a web page: Essential options: * CURLOPT_RETURNTRANSFER. When true, CURL returns the web page content from curl_exec(). When false, CURL prints the page to the screen (which is hardly ever useful). * CURLOPT_HEADER. When true, CURL includes the web server’s HTTP response header in the page. When false, it is excluded, making the returned page easier to parse later. The header is still available by calling curl_getinfo(). Important options: * CURLOPT_FOLLOWLOCATION. When true, CURL follows web page redirects automatically. When false, it stops on the first redirect and returns an error. * CURLOPT_ENCODING. When empty, CURL handles uncompressed and compressed transfers. Compressed pages are automatically decompressed before they’re returned by curl_exec(). Web etiquette options: * CURLOPT_USERAGENT. The user agent is the name of the application making the request (such as a web browser). If left empty, some web servers will reject the request. * CURLOPT_AUTOREFERER. The referer is a URL for the web page that linked to the requested web page. When following redirects, set this to true and CURL automatically fills in the URL of the page being redirected away from. Error handling options: * CURLOPT_CONNECTTIMEOUT. Fail if a web server doesn’t respond to a connection within a time limit (seconds). * CURLOPT_TIMEOUT. Fail if a web server doesn’t return the web page within a time limit (seconds). * CURLOPT_MAXREDIRS. If a web page redirect leads to another redirect, and another, stop after a maximum number of redirects. curl_exec() The curl_exec() function issues the request and returns the web page (HTML, XHTML, XML, image, etc.). curl_errno() and curl_error() There are two kinds of errors: * System errors result from a bad URL, bad protocol, unknown host, connect timeout, response timeout, or redirect loop. On a system error, curl_errno() returns a non-zero error code (see the CURL error code list) and curl_error() returns a short error message suitable for debugging output. * Site errors result from an unknown web page, insufficient permissions, or a web server that is down for maintenance. On a site error or success, curl_errno() returns zero and the web server’s HTTP status code is available in the server header returned by curl_getinfo() (see below). curl_getinfo() The curl_getinfo() function returns values from the server header, such as web page’s content type and the HTTP status code. See the manual for a list of header fields returned. Highlights include: "url" the final web page URL after redirects "content_type" the content type (e.g. "text/html; charset=utf-8") "http_code" the web page status code (e.g. "200" on success) "filetime" the date stamp on the remote file The "http_code" entry has the HTTP status code (see Wikipedia’s List of HTTP status codes). On success, the status is 200. The code is 404 if the web page is not found, 401 if authentication is required, 503 if the web site is down, etc. curl_close() The curl_close() function destroys the CURL handle, freeing memory. Here sample code /** * Get a web file (HTML, XHTML, XML, image, etc.) from a URL. Return an * array containing the HTTP server response header fields and content. */ function get_web_page( $url ) { $options = array( CURLOPT_RETURNTRANSFER => true, // return web page CURLOPT_HEADER => false, // don't return headers CURLOPT_FOLLOWLOCATION => true, // follow redirects CURLOPT_ENCODING => "", // handle all encodings CURLOPT_USERAGENT => "spider", // who am i CURLOPT_AUTOREFERER => true, // set referer on redirect CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect CURLOPT_TIMEOUT => 120, // timeout on response CURLOPT_MAXREDIRS => 10, // stop after 10 redirects ); $ch = curl_init( $url ); curl_setopt_array( $ch, $options ); $content = curl_exec( $ch ); $err = curl_errno( $ch ); $errmsg = curl_error( $ch ); $header = curl_getinfo( $ch ); curl_close( $ch ); $header['errno'] = $err; $header['errmsg'] = $errmsg; $header['content'] = $content; return $header; }
__________________ With, J. Jeyaseelan Everything Possible |
| |||
| hi Pixel, Think this might given an idea about HTTP upload, Data from flash are send in a binary format to the server side script. Server side script reads that binary data and stores in the same format which had been send from flash. For example: if an JPEG file is send from flash, it will be send in binary format, server side script reads that data and stores it has in the format which has been send from flash. nssukumar |
| |||
| Quote:
Thanks a lot Bala. It’s really great. Thanks for your precious time. It’s working very fine. It’s really very useful to me and the whole actionscript programmers. And I have one more doubt. In my home I don’t have internet connection and server. I have little bit knowledge about IIS. I am using Windows XP operating system. How to install IIS there? How can I check the server side script in local machine? And one more think, here I can upload only one file at a time. My question is, how can I select multiple files at a time? Thanks in Advance!!! ![]() |