Jump to content

Featured Replies

Posted
comment_76

Bài viết này sẽ hướng dẫn các bạn tạo một trang upload file đơn giản bằng CURL.

Hướng dẫn

Tạo và dán lần lượt 3 file dưới:


index.php

<!DOCTYPE html>
<html>
    <head>
        <title>File Upload Using PHP and cURL - freetuts.net</title>
    </head>
    <body>
        <form action="b.php" method="post" enctype="multipart/form-data">
            <h3>Select File</h3>
            <input name="file" type="file" id="file" />
            <hr />
            <input name="btnUpload" type="submit" value="Upload" />
        </form>
    </body>
</html>

 curl.php

<?php
if (isset($_POST['btnUpload'])){
    $filename = $_FILES['file']['name'];
    $filedata = $_FILES['file']['tmp_name'];
    $filesize = $_FILES['file']['size'];
    if ($filedata != ''){
        $handle  = fopen($filedata, 'rb');
        $data    = fread($handle, $filesize);
        fclose($handle);
 
        $postfields = array('filedata' => $data, 'filename' => $filename);
        $ch = curl_init('http://test.pro/upload.php');
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_exec($ch);
        if(curl_errno($ch)){
            echo curl_error($ch);
        } else {
            $info = curl_getinfo($ch);
            if ($info['http_code'] == 200){
                echo 'Upload thành công';
            }
        }
        curl_close($ch);
    } else {
        echo 'Bạn chưa chọn file để upload';
    }
}

upload.php

<?php
$uploadpath = 'upload/';
$filedata = $_POST['filedata'];
$filename = $_POST['filename'];
if ($filedata != '' && $filename != ''){
    file_put_contents($uploadpath . $filename, $filedata);
}

Thay địa chỉ ở file curl.php và tạo thêm thư mục upload nữa là xong!

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...