I am trying to execute a url and getting its response. Following is the code that executes the curl. I want the curl execution to return me a string in $result.
<?php
$fields = array
(
'username'=>urlencode($username),
'pwrd'=>urlencode($pwrd),
'customer_num'=>urlencode($customer_num)
);
$url = 'http://localhost/test200.php';
//open connection
set_time_limit(20);
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
echo $result; //I want $result to be "Successful"
?>
This is my test200.php on localhost:
<?php
$usernam = $_POST['username'];
$pass = $_POST['pwrd'];
$customer_num = $_POST['customer_num'];
echo "Successful!";
?>
What changes do I make in test200.php? Please help.
You should use the httpcode returned by the curl execution and not rely on a string that is returned
$res = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
Here - http://www.webmasterworld.com/forum88/12492.htm
Once the data is sent to test200.php do the appropriate manipulation like insert the posted values into a table and on success
echo "Successful!";
or print the same in your test200.php.. assuming you are doing an insert code in test200.php code would be like
<?php
$qry = "INSERT INTO `your_table` (`field_customer_name`, `field_username`, `field_password`) VALUES ($fields['customer_num'], $fields['username'], some_encrypt_fxn($fields['pwrd']))";
mysql_query($qry);
$err_flag = mysql_error($your_conn_link);
if($err_flag == '') {
echo "Successful!";
}
else {
echo "Failed, Error " . $err_flag;
}
?>
If the purpose of getting "Successful!" is to check if the cURL returns success then i suggest using Prateik's answer of using the returned status code
Somehow a simple print("Successful"); statement in test200.php worked well. The response i get now is as follows: HTTP Code: 0 Array ( [0] => [1] => Successful )
Related
I'm new to JSON Code. I want to learn about the update function. Currently, I successfully can update data to the database. Below is the code.
<?php
require_once "../config/configPDO.php";
$photo_after = 'kk haha';
$report_id = 1;
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_maintainReport?taskname=&reportStatus=&photoBefore=&photoAfter=". urlencode($photo_after) . "&reportID=$report_id";
$data = file_get_contents($url);
$json = json_decode($data);
$query = $json->otReportList;
if($query){
echo "Data Save!";
}else{
echo "Error!! Not Saved";
}
?>
the problem is, if the value of $photo_after is base64 string, which is too large string, it will give the error:
1) PHP Warning: file_get_contents.....
2) PHP Notice: Trying to get property 'otReportList' of non-object in C:
BUT
when I change the code to this,
<?php
require_once "../config/configPDO.php";
$photo_after = 'mama kk';
$report_id = 1;
$sql = "UPDATE ot_report SET photo_after ='$photo_after', time_photo_after = GETDATE(), ot_end = '20:30:00' WHERE report_id = '$report_id'";
$query = $conn->prepare($sql);
$query->execute();
if($query){
echo "Data Save!";
}else{
echo "Error!! Not Saved";
}
?>
The data will updated including when the value of $photo_after is in base 64 string.
Can I know what is the problem? Any solution to allow the base64 string update thru json link?
Thanks
// ...
// It's likely that the following line failed
$data = file_get_contents($url);
// ...
If the length of $url is more than 2048 bytes, that could cause file_get_contents($url) to fail. See What is the maximum length of a URL in different browsers?.
Consequent to such failure, you end up with a value of $json which is not an object. Ultimately, the property otReportList would not exist in $json hence the error: ...trying to get property 'otReportList' of non-object in C....
To surmount the URL length limitation, it would be best to embed the value of $photo_after in the request body. As requests made with GET method should not have a body, using POST method would be appropriate.
Below is a conceptual adjustment of your code to send the data with a POST method:
<?php
require_once "../config/configPDO.php";
# You must adapt backend behind this URL to be able to service the
# POST request
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_maintainReport";
$report_id = 1;
$photo_after = 'very-long-base64-encoding-of-an-image';
$request_content = <<<CONTENT
{
"taskname": $taskname,
"report_id": $report_id,
"photoBefore": $photoBefore,
"photo_after": $photo_after,
"reportStatus": $reportStatus
}
CONTENT;
$request_content_length = strlen($request_content);
# Depending on your server configuration, you may need to set
# $request_headers as an associative array instead of a string.
$request_headers = <<<HEADERS
Content-type: application/json
Content-Length: $request_content_length
HEADERS;
$request_options = array(
'http' => array(
'method' => "POST",
'header' => $request_headers,
'content' => $request_content
)
);
$request_context = stream_context_create($request_options);
$data = file_get_contents($url, false, $request_context);
# The request may fail for whatever reason, you should handle that case.
if (!$data) {
throw new Exception('Request failed, data is invalid');
}
$json = json_decode($data);
$query = $json->otReportList;
if ($query) {
echo "Data Save!";
} else {
echo "Error!! Not Saved";
}
?>
sending a long GET URL is not a good practice. You need to use POST method with cURL. And your webservice should receive the data using post method.
Here's example sending post using PHP:
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") { ... } else { ... }
Sample code from: PHP + curl, HTTP POST sample code?
And all output from the webservice will put in the curl_exec() method and from there you can decode the replied json string.
I am trying to add the following data to my database using curl. It insert's the data but the data inserted is blank
Employee Name = Test
Employee Salary = 100
Employee Age = 28
This is my code in inserting the data:
// set post fields
$data["employee_name"] = "test";
$data["employee_salary"] = 1;
$data["employee_age"] = 1;
$ch = curl_init('http://localhost/cloud/v1/employees');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump($response);
This is my Function in getting the data :
function insert_employee()
{
global $connection;
$data = json_decode(file_get_contents('php://input'), true);
$employee_name=$data["employee_name"];
$employee_salary=$data["employee_salary"];
$employee_age=$data["employee_age"];
echo $query="INSERT INTO employee SET employee_name='".$employee_name."', employee_salary='".$employee_salary."', employee_age='".$employee_age."'";
if(mysqli_query($connection, $query))
{
$response=array(
'status' => 1,
'status_message' =>'Employee Added Successfully.'
);
}
else
{
$response=array(
'status' => 0,
'status_message' =>'Employee Addition Failed.'
);
}
header('Content-Type: application/json');
echo json_encode($response);
}
Thank you
Replace this line:
$data = json_decode(file_get_contents('php://input'), true);
with:
$data = $_POST;
PHP will take your POSTed data and push it straight into a global $_POST array. No need to play with json_decode (unless you have posted a JSON string) or php://input.
Be aware, however, that blindly trusting posted data, and concatenating posted variables into a SQL statement is a huge security hole! Please look in to prepared statements and input validation.
$text="text.";
//fetch from DB
$sql=mysql_query("SELECT * FROM `employee`");
while($query=mysql_fetch_array($sql))
{
echo $employee_mobile=$query['employee_mobile'];
echo $url="http://mobile.ssexpertcompu.com/vendorsms/pushsms.aspx?user=MYUSERNAME&password=MYPASSWORD&msisdn=".$employee_salary."&sid=78NSL&msg=".$text."&fl=0&gwid=2";
$url = str_replace(" ","%20",$url); // to properly format the url
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
echo $data = curl_exec($ch);
curl_close($ch);
}
First employee record are fetched from DB,then using curl I'm sending message to their respective mobile numbers.The code for sending messages works fine without loop. I've seen some post how to use curl in a loop, but couldn't modify to my needs.
Looks like you have not defined $employee_salary and should exchange it with $employee_mobile:
echo $employee_mobile = $query['employee_mobile'];
echo $url = "http://mobile.ssexpertcompu.com/vendorsms/pushsms.aspx?user=MYUSERNAME&password=MYPASSWORD&msisdn=" . $employee_mobile . "&sid=78NSL&msg=" . $text . "&fl=0&gwid=2";
I wrote this php code to fetch data from an url with json format and It seemed like it worked but I dont get anything in the database
<?php
session_start();
$con= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($con,"facebook_data") or die ("no database");
$url = "https://graph.facebook.com/209024949216061/feed?fields=created_time,from,type,message&access_token=XXXXXXXX";
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_HEADER, false);
$curlResponse = curl_exec($ch);
$data = json_decode($curlResponse,TRUE);
if (is_array($data) || is_object($data)) {
foreach($data as $row){
$id=$row["id"];
$created_time=$row["created_time"];
$type=$row["type"];
$message=$row["message"];
$user_id=$row["from"]["id"];
$username=$row["from"]["name"];
$sql="INSERT INTO group_feed(id, username, created_time, user_id, type, message) VALUES('$id','$username','$created_time','$user_id', '$type', '$message')";
if(!mysql_query($sql,$con))
{
die('Error : ');
}
}
}
?>
I put the $url with the appropriate access_token when I open the link in my browser it displays me the JSON format DATA where the problem could be?
$url = "http://graph.facebook.com/".$group_id."/feed/?access_token=".$token;
$ch = curl_init($url);
curl_setopt(CURLOPT_HEADER, false);
$curlResponse = curl_exec($ch);
Check http://php.net/manual/en/book.curl.php for more information on curl()
Then you have to parse you curl response using $data = json_decode($curlResponse). You will get an associative array which can be iterated (foreach, for, while).
Only you know how to write your SQL queries.
Note: If this doesn't work, take a look at the curl_setopt() function.
I'm using CURL to post to a script hosted on a remote server.
I'm sending a multidimensional array using this:
$urlserver = "myserver";
$arraytag = array('tags'=>$taggenerici,'tagesplosi'=>$tagesplosi,'matrice'=>$matricefin,'id' =>$identificativo);
$postfields = http_build_query($arraytag);
//open connection
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$urlserver);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_POST,sizeof($postfields));
curl_setopt($ch, CURLOPT_POSTFIELDS,$postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1); // RETURN THE CONTENTS OF THE CALL
//execute request sending post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
The problem is about the result: infact if i try to execute my script i get a randomic result. I'd like to view an array of 20rows X 43columns but it stops at row10 and column28. But if i refresh my page after some try i get my full array.
I'd like to say that i have tried to get the array before sending it to the remote server and it works fine cos i get my array entirely without any kind of cutting.
script being called (minus unused mysql connection):
<?php
$taggenerici = $_POST['tags'];
$matrice = $_POST['matrice'];
$identificativo = $_POST['id'];
$tagesplosi = $_POST['tagesplosi'];
//Here i create the array with "a" and "?"
for($dom=0;$dom<sizeof($identificativo);$dom++) {
for ($tag=0;$tag<sizeof($taggenerici);$tag++) {
$matrice[$dom][$tag] = "a, ";
}
$tagAdd=sizeof($taggenerici)+1;
$matrice[$dom][$tagAdd] ="?";
}
//Here i set "p".
for($dom=0;$dom<sizeof($identificativo);$dom++) {
for ($tag=0;$tag<sizeof($taggenerici);$tag++) {
for ($tagarray=0;$tagarray<sizeof($tagesplosi[$dom]);$tagarray++) {
if ($taggenerici[$tag] == $tagesplosi[$dom][$tagarray]) {
$matrice[$dom][$tag] = "p, ";
}
}
}
}
//this is the $result which I call on the client. (echo $valore);
foreach ($matrice as $kappa => $vu) {
echo "<br>";
foreach ($vu as $kii => $valore)
echo $valore;
}
}