IT Community - Software Programming, Web Development and Technical Support

File Handling in PHP

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 ...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Web Development > PHP Programming

Register FAQ Members List Calendar Mark Forums Read
  #1 (permalink)  
Old 08-03-2007, 04:11 AM
ragavraj ragavraj is offline
D-Web Programmer
 
Join Date: Feb 2007
Posts: 92
ragavraj is on a distinguished road
Default File Handling in PHP

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:
  1. Basic Techniques of File Handling
  2. Various File Handling Methods
  3. Handling File Uploads
  4. Integrating Flash in File Uploads
  5. Reading Files from Remote Servers
  6. Common Testing Methodologies in File Handling Functionalities

Hope you all provide good support in this thread, so we dwell deeper into this issue.

Thanks
R.Rajan
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 08-03-2007, 04:22 AM
sivaramakrishnan sivaramakrishnan is offline
D-Web Programmer
 
Join Date: Feb 2007
Posts: 74
sivaramakrishnan is on a distinguished road
Exclamation Re: File Handling in PHP

Hi,

I give below the three types PHP File Handling methods

* file()
* fopen()
* file_get_contents().
What is difference Between three?
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 08-03-2007, 05:20 AM
raj raj is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 89
raj is on a distinguished road
Default Re: File Handling in PHP

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");
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 08-03-2007, 05:33 AM
geoblow geoblow is offline
D-Web Trainee
 
Join Date: Jul 2007
Posts: 19
geoblow is on a distinguished road
Default Re: File Handling in PHP

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
__________________
Geo
Actionscript Villain
geoblow.com
Atleast an inch move every day!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 08-03-2007, 05:43 AM
venkat_charya venkat_charya is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Posts: 118
venkat_charya is on a distinguished road
Thumbs up Re: File Handling in PHP

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?
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 08-03-2007, 05:57 AM
PixelNameVj PixelNameVj is offline
D-Web Trainee
 
Join Date: Jul 2007
Posts: 28
PixelNameVj is on a distinguished road
Exclamation Re: File Handling in PHP

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.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 08-03-2007, 06:03 AM
Anand Anand is offline
D-Web Programmer
 
Join Date: Mar 2007
Posts: 52
Anand is on a distinguished road
Default Re: File Handling in PHP

Yes, we can. Once the file is uploaded via http from flash, we can access the file using $_FILES['Filedata']['tmp_name'] in php.
__________________
None of us is As Strong as All of us.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 08-03-2007, 06:21 AM
Sabari Sabari is offline
D-Web Genius
 
Join Date: Jul 2007
Posts: 1,008
Sabari is on a distinguished road
Default Re: File Handling in PHP

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...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 08-03-2007, 07:30 AM
geoblow geoblow is offline
D-Web Trainee
 
Join Date: Jul 2007
Posts: 19
geoblow is on a distinguished road
Default Re: File Handling in PHP

Quote:
Originally Posted by Anand View Post
Yes, we can. Once the file is uploaded via http from flash, we can access the file using $_FILES['Filedata']['tmp_name'] in php.
Thanks Anand!
Plz can you give the complete php code for flash uploader?
__________________
Geo
Actionscript Villain
geoblow.com
Atleast an inch move every day!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 08-03-2007, 07:54 AM
Sabari Sabari is offline
D-Web Genius
 
Join Date: Jul 2007
Posts: 1,008
Sabari is on a distinguished road
Default Re: File Handling in PHP

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...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #11 (permalink)  
Old 08-03-2007, 08:55 AM
kbala kbala is offline
D-Web Trainee
 
Join Date: Mar 2007
Posts: 5
kbala is on a distinguished road
Default Re: File Handling in PHP

Quote:
Originally Posted by geoblow View Post
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

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();
here, we have created a new instance of FileReference Class, fileRef is the instance(object) name.

Code:
fileRef.addEventListener(Event.SELECT, selectHandler)
we have to add a event and a listener to the fileRef object. Here the event is "SELECT", listener is "selectHandler". The meaning of the above code is, when the SELECT event fires, call the selectHandler function

Code:
fileRef.addEventListener(Event.COMPLETE, completeHandler)
we can add another event to notify the upload complition
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");
}
consider, we have to upload a image file to the server. Here, the core functionality used to upload the selected file. As soon as SELECT event of the fileRef object fires, the above listener function will execute. Now the fileRef object contains the selected image file in the form of binary data.

[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");
}
This function will be executed when the binary data transfered over http from fileRef object to server.

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();
}
When you click the button, Browse dialog window will open to select the image file. The SELECT event will fire when the user click the "Open" button of the Browse window.

So far, the flash part will come to the end, let us see the server side script(php)

PHP Code:
<?php
if ($_FILES['Filedata']['tmp_name'] && $_FILES['Filedata']['name'])
{
    
$vSourceFile $_FILES['Filedata']['tmp_name'];
    
$vImageName stripslashes($_FILES['Filedata']['name']);
    
$vFoldername 'UploadedFiles/';
    if(!
is_dir($vFoldername))
    {
        
mkdir($vFoldername0777); //#-- Create a new session directory        chmod($vFoldername, 0777); //#-- Set all the access permissions to the folder
    
}
    if(
copy($vSourceFile,$vFoldername.$vImageName))
        
$vStatus 1;
    else
        
$vStatus 0;
    }        
    else
    {
        
$vStatus 0;
    }
    echo 
'<?xml version="1.0" encoding="UTF-8"?>';
    if(
$vStatus)
        echo 
'<status>1</status>';
    else
        echo 
'<status>0</status>';
?>
See, how the "Filedata" variable is used.
$_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
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #12 (permalink)  
Old 08-03-2007, 09:38 AM
Karpagarajan Karpagarajan is offline
D-Web Analyst
 
Join Date: Mar 2007
Posts: 299
Karpagarajan is on a distinguished road
Post Re: File Handling in PHP

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
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #13 (permalink)  
Old 08-04-2007, 12:59 AM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: File Handling in PHP

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
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #14 (permalink)  
Old 08-06-2007, 03:23 AM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: File Handling in PHP

Hi guys,
Is there any way to get web page from https url through CURL?
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #15 (permalink)  
Old 08-07-2007, 12:07 AM
nssukumar nssukumar is offline
D-Web Sr.Programmer
 
Join Date: Feb 2007
Posts: 155
nssukumar is on a distinguished road
Default Re: File Handling in PHP

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
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #16 (permalink)  
Old 08-08-2007, 08:15 AM
geoblow geoblow is offline
D-Web Trainee
 
Join Date: Jul 2007
Posts: 19
geoblow is on a distinguished road
Thumbs up Re: File Handling in PHP

Quote:
Originally Posted by kbala View Post
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();
here, we have created a new instance of FileReference Class, fileRef is the instance(object) name.

Code:
fileRef.addEventListener(Event.SELECT, selectHandler)
we have to add a event and a listener to the fileRef object. Here the event is "SELECT", listener is "selectHandler". The meaning of the above code is, when the SELECT event fires, call the selectHandler function

Code:
fileRef.addEventListener(Event.COMPLETE, completeHandler)
we can add another event to notify the upload complition
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");
}
consider, we have to upload a image file to the server. Here, the core functionality used to upload the selected file. As soon as SELECT event of the fileRef object fires, the above listener function will execute. Now the fileRef object contains the selected image file in the form of binary data.

[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");
}
This function will be executed when the binary data transfered over http from fileRef object to server.

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();
}
When you click the button, Browse dialog window will open to select the image file. The SELECT event will fire when the user click the "Open" button of the Browse window.

So far, the flash part will come to the end, let us see the server side script(php)

PHP Code:
<?php
if ($_FILES['Filedata']['tmp_name'] && $_FILES['Filedata']['name'])
{
    
$vSourceFile $_FILES['Filedata']['tmp_name'];
    
$vImageName stripslashes($_FILES['Filedata']['name']);
    
$vFoldername 'UploadedFiles/';
    if(!
is_dir($vFoldername))
    {
        
mkdir($vFoldername0777); //#-- Create a new session directory        chmod($vFoldername, 0777); //#-- Set all the access permissions to the folder
    
}
    if(
copy($vSourceFile,$vFoldername.$vImageName))
        
$vStatus 1;
    else
        
$vStatus 0;
    }        
    else
    {
        
$vStatus 0;
    }
    echo 
'<?xml version="1.0" encoding="UTF-8"?>';
    if(
$vStatus)
        echo 
'<status>1</status>';
    else
        echo 
'<status>0</status>';
?>
See, how the "Filedata" variable is used.
$_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

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!!!
__________________
Geo
Actionscript Villain
geoblow.com
Atleast an inch move every day!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!