2016-04-25 102 views
0

我是新來的PHP,我試圖讓使用curl從網站的數據(刮)數據,無法發送使用CURLOPT_POST到其他PHP文件

無法從index.php來data.php獲取數據,使用CURLOPT_POST ..我做錯了什麼..?

的index.php

<?php 
$data = array("name"=>"john","age"=>31); 
$string = http_build_query($data); 

echo $string; 

$ch = curl_init("http://localhost/scrap_practise/data.php"); 
curl_setopt($ch, CURLOPT_POST,true); 
curl_setopt($ch, CURLOPT_POSTFIELDS,$string); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_exec($ch); 
curl_close($ch); 

?> 

data.php

<?php 
echo 'finlly in'; // this never echos 
if(isset($_POST['name'],$_POST['age'])){ 
    $db = new Mysqli("localhost","root","","mydb"); 
    $name = $db->real_escape_string($_POST['name']); 
     $age = (int) $_POST['age']; 
     $query = "INSERT INTO data SET data='$name,$age'"; 
     $db->query($query); 

} 

?> 
+0

分配在捲曲變量'$ result = curl_exec($ ch);'和打印結果'print_r($ result);'來檢查錯誤,但是你的代碼工作正常我認爲問題在於你的主機名是'localhost 'not'loclhost' –

+0

使用'curl_setopt($ ch,CURLOPT_URL,Your Url);' –

+0

@manjeet barnala- no,但它甚至沒有回顯data.php中的代碼,data.php中的第一行是'echo' finlly in',它沒有顯示 – Bawa

回答

1

只要你需要更新你index.php腳本與這些代碼行。

的index.php

<?php 
$data = array("name"=>"john","age"=>31); 
$string = http_build_query($data); 

echo $string; 

$ch = curl_init("http://localhost/scrap_practise/data.php"); 
curl_setopt($ch, CURLOPT_POST,true); 
curl_setopt($ch, CURLOPT_POSTFIELDS,$string); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
if(! $result = curl_exec($ch)) 
{ 
    trigger_error(curl_error($ch)); 
} 
curl_close($ch); 

// to see the return result uncomment the below line code. 
//print_r($result); 
?> 

更多選項或函數引用看到這個鏈接 - http://php.net/manual/en/function.curl-exec.php

希望這將有助於解決您的問題!

+0

兄弟,這工作,我現在可以看到data.php裏面的回聲,但它沒有任何意義給我。怎麼樣..?如何聲明有所作爲..加上我仍然無法看到數據庫中的數據(雖然我會解決它,幫助在這種情況下,將不勝感激) – Bawa

+0

我認爲這是因爲print_r($結果); – Bawa

+1

@Bawa,函數'curl_exec()'在成功時返回'TRUE'或者在失敗時返回'FALSE'。但是,如果設置了'CURLOPT_RETURNTRANSFER'選項,它將在成功時返回結果,失敗時返回'FALSE'。 –

1

試試這個代碼,我希望它會爲你工作...

<?php 
$url = 'http://localhost/scrap_practise/data.php'; 

$data = array("name"=>"john","age"=>31); 

$string = http_build_query($data); 

echo $string; 

$ch = curl_init(); 
curl_setopt($ch,CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_POST,true); 
curl_setopt($ch, CURLOPT_POSTFIELDS,$string); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

$result = curl_exec($ch); 
print_r($result) ; 

curl_close($ch); 

?> 

在data.php文件

<?php 
echo 'finlly in'; // this never echos 
if(isset($_POST['name'],$_POST['age'])) 
{ 
    echo "<pre>"; print_r($_POST); 
} 
?> 

這將輸出:

finlly in 
Array 
(
    [name] => john 
    [age] => 31 
) 
+0

這工作太bro了,但我只能標記一個答案的權利。 :)感謝您的幫助。 – Bawa

+1

歡迎bro ... @Bawa,我一直在這裏幫助... –

相關問題