I have a POST function contained in my page. I am trying to call it directly for my CURL Function, notice in the following code the url variable is set to http://dirtrif.loc/installs.php
//extract data from the post
//set POST variables
$cookie_name = "drcuserid";
if(isset($_COOKIE[$cookie_name]))
{
$cookie = $_COOKIE[$cookie_name];
}
$url = 'http://dirtrif.loc/installs.php';
$fields['username'] = $vbulletin->userinfo[username];
$fields['webmasteremail'] = $vbulletin->options[webmasteremail];
$fields['cookie'] = $_COOKIE[$cookie_name];
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$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);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
echo $fields_string;
This is causing an issue when the CURL script is executed, by navigating to the actual page and not running the portion that it's supposed to.
I currently have the post portion set up as follows in my installs.php:
if (isset($_POST['username'])) {
$vbulletin->db->query_write("
INSERT INTO " . TABLE_PREFIX . "installs (
username,
webmasteremail,
cookie
) VALUES (" .
$_POST['username'] .", '" .
$_POST['webmasteremail'] . ", '" .
$_POST['cookie'] . "'
)");
}
Is there a way I can change the URL in my CURL code to point directly to that part of the installs.php page?
the full contents of installs.php (note* I have made a few changes since posting this question)
<?php
// ####################### SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE);
// #################### DEFINE IMPORTANT CONSTANTS #######################
define('THIS_SCRIPT', 'installs');
define('CSRF_PROTECTION', true);
define('CSRF_SKIP_LIST', '');
// ################### PRE-CACHE TEMPLATES AND DATA ######################
// pre-cache templates used by all actions
$globaltemplates = array(
'installs'
);
// pre-cache templates used by specific actions
$actiontemplates = array();
// ######################### REQUIRE BACK-END ############################
require_once('./global.php');
// ######################### VARIABLES ############################
$username = $_POST['username'];
$userid = $_POST['userid'];
$email = $_POST['email'];
$addontitle = $_POST['addontitle'];
$addonversion = $_POST['addonversion'];
$bburl = $_POST['bburl'];
$bbtitle = $_POST['bbtitle'];
$webmasteremail = $_POST['webmasteremail'];
$cookie = $_POST['cookie'];
if (isset($_POST['username'])) {
$db->query_write("
INSERT INTO " . TABLE_PREFIX . "installs (
username,userid,email,addontitle,addonversion,bburl,bbtitle,webmasteremail,cookie,dateline
) VALUES (
'$username',
'$userid',
'$email',
'$addontitle',
'$addonversion',
'$bburl',
'$bbtitle',
'$webmasteremail',
'$cookie',
NOW()
)");
}
// #######################################################################
// ######################## START MAIN SCRIPT ############################
// #######################################################################
$navbits = array();
$navbits[$parent] = 'Installs Page';
$navbits = construct_navbits($navbits);
eval('$navbar = "' . fetch_template('navbar') . '";');
eval('print_output("' . fetch_template('installs') . '");');
?>
Is there a way I can change the URL in my CURL code to point directly to that part of the installs.php page?
As for standard HTTP features: no, there is no explicit way of calling parts of a script.
Let's start from the beginning. What we would usually do in this situation is that we set the path in the URL to the file, that contains parts we want to execute. Then, it is up us to decide, how we design our program to know, which part should be executed. We can use POST parameters for that like you were trying. So far, so good.
Now, how do we divide our script, installs.php in your case, into pieces?
One good way is the one RamRaider already mentioned: use a POST parameter action and in installs.php, put code into a big switch. Example:
// installs.php
<?php
switch ($_POST['action']) {
case 'myfirstaction':
if (isset($_POST['username'])) {
$vbulletin->db->query_write("...");
}
break;
case 'myotheraction':
// code here
break;
}
?>
To call specific actions, just extend you $fields array:
<?php
// script that "can be executed from anywhere":
$fields['action'] = 'myfirstaction';
?>
I would say this is the cleanest way to do it in your situation. However, if installs.php is a larger script you are adjusting, this might be way too much work. In that case you may want to exit the script after running your code (thus, running only the code you want). You can simply write exit; and no further code will be executed. See: https://www.php.net/exit.
Related
Hey guys I'm working with PHP, cURL and JSON data.
Architecture:
FRONT <-> MIDDLE <-> BACK
Problem location:
MIDDLE <-> BACK
Description:
In my MIDDLE file (PHP server) I call a function which make a cURL to my BACK file (PHP server).
The issue I'm having is that it will execute one of the calls (HTTP cURL requests) but not the other, overthought the one not executing is the call first.
Can you guys guide me on the issue, how can I solve this?
What I've try:
I research (articles, videos) info on curl thinking that maybe I had to handle it mysql-like, in which I had to create multiple cURL connection if I needed to request different items from the same server (BACK).
I've implemented dummy print outs to see whats executed and came about the conclusion I describe in the description part.
Note:
Following you will find the code for MIDDLE, BACK and two images:
Image 1 is the code with dummy print out showing how one cURL executes and the other does not. Please noticed the text "what back gets".
Image 2 is how cURL is not executed.
MIDDLE FILE:
Note:
Look how under case "EXAMSOLVED" I call two functions. That is related to Image 1.
If I comment the second function that is related to Image 2.
<?php
/*------------------------------------------------------------------*/
include "exam_grading_system.php";
/*------------------------------------------------------------------*/
function http_post_back_server($url, $data)
{
$obj = curl_init();
curl_setopt($obj, CURLOPT_URL, $url);
curl_setopt($obj, CURLOPT_POST, strlen($data));
curl_setopt($obj, CURLOPT_POSTFIELDS, $data);
curl_setopt($obj, CURLOPT_RETURNTRANSFER, true);
$ans = curl_exec($obj);
curl_close($obj);
return $ans;
}
//--------------------------------------------------------------------
function get_question_info($ulr, $id_question)
{
//Set UP Request Packet
$askDB->case = "GradingInfo";
$askDB->id_question = $id_question;
//Convert Packet to JSON format
$askDB = json_encode($askDB);
//echo $askDB;
//Ask Back Server
$BK_Srv_Ans = http_post_back_server($url,$askDB);
return $BK_Srv_Ans;
}
//--------------------------------------------------------------------
/*URL TO BACK SERVER*/
$url_myserver = "https: MY URL ";
/*GLOBAL VARS*/
$back_ans ="";
/*RECEIVE DATA FROM POST REQUEST*/
$indata = file_get_contents("php://input");
$data = json_decode($indata,true);
/*MAKE REQUEST TO SERVERS*/
switch($data["case"]){
case "_EXAMSOLVED_":
$questions_Info = get_question_info($url_myserver, $data["id_question"]);
//$indata = Grading($data, $questions_Info);
//$back_ans = http_post_back_server($url_myserver,$indata);
break;
default:
$back_ans = http_post_back_server($url_myserver,$indata);
break;
}
/*ANSWER BACK TO FRON END*/
echo $back_ans;
?>
BACK FILE:
Note: Look the dummy echo statement I have at the begging of the file
<?php
/*------------------------------------------------------------------*/
include "Prof_backend_tools.php";
include "Student_backend_tools.php";
/*------------------------------------------------------------------*/
echo "what back gets: ";
/*RECEIVING DATA FROM POST REQUEST */
$indata = file_get_contents("php://input");
/*DATA TO JSON OBJ*/
$indata = json_decode($indata, true);
/*CHECKING DATABASE CONNECTIVITY */
if(mysqli_connect_error())
{ echo "Connection Error: ".mysqli_connect_error; }
switch($indata["case"])
{
case "_EXAMSOLVED_":
echo store_exam_slutions($indata,DB_s());
break;
case "GradingInfo":
echo "--IN BACK--";
//echo Needed_data_for_grading($indata);
break;
default:
echo "NADA";
break;
}
?>
Image 1:
Image 2:
Any guide would be great guys.
Thank you.
OK,I've found what was happening!!!
Debugging:
Check MIDDLE file.
Check the parameters in function definition get_question_info
Now check arguments given to function call http_post_back_server
There lies the problem.
The code I am using is:
$url = "example.com";
$code = file_get_contents("http://www.".$url);
if (!$code) {
$code = file_get_contents("https://www.".$url);
}
I don't know whether each URL starts with http or https. I have 1,000 URLs saved in my database. Any suggestions?
This answer is somewhat relevant. Given that your database is rather incomplete in that the URLs aren't fully qualified, I would be inclined to write a short routine to update the database for future use.
<?php
$url = 'example.com';
$variations[] = 'http://'.$url;
$variations[] = 'https://'.$url;
$variations[] = 'http://www.'.$url;
$variations[] = 'https://www'.$url;
foreach($variations as $v){
// Check variation with function from answer linked above
if(urlOK($v)){
// code to update database row
// or if you don't want to do that
$code = file_get_contents($v);
}
}
I would like to find out how a PHP page calls another PHP page, which will return JSON data.
I am working with PHP (UsersView.php) files to display my contents of a website. However, I have separated the MySQL Queries in another PHP (Get_Users.php) file.
In the Get_Users.php, I will have a MySQL statement to query the database for data. It will then encode in JSON and be echo-ed out.
In the UsersView.php, I will call the Get_Users.php in order to retrieve the Users JSON data. The data will then be used to populate a "Users Table".
The thing is, I do not know how to call the "Get_Users.php" from the "UsersView.php" in order to get the data.
Part of UserView.php
$url = "get_user.php?id=" . $id;
$json = file_get_contents($url);
$result = json_decode($json, true);
I am trying to call the file which is in the same directory, but this does not seem to work.
Whole of Get_Users.php
<?php
$connection = mysqli_connect("localhost", "root", "", "bluesky");
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") " .
"<br>Please retry your last action. Please retry your last action. " .
"<br>If problem persist, please follow strictly to the instruction manual and restart the system.");
}
$valid = true;
if (!isset($_GET['id'])) {
$valid = false;
$arr=array('success'=>0,'message'=>"No User ID!");
echo json_encode($arr);
}
$id = $_GET['id'];
if($valid == true){
$query = "SELECT * FROM user WHERE id = '$id'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_assoc($result);
$arr=array('success'=>1,'type'=>$row['type'],'user_id'=>$row['id'],'email'=>$row['email'],'name'=>$row['name'],'phone'=>$row['phone'],'notification'=>$row['notification']);
echo json_encode($arr);
}else{
$arr=array('success'=>0,'message'=>"Invalid User ID!");
echo json_encode($arr);
}
}
mysqli_close($connection);
?>
You have a couple of different ways to accomplish this:
You should be able to first set the actual id and then include the Get_Users.php file like this. Notice that you should not echo out the output from Get_Users.php, instead only return the encoded json data using return json_encode($arr);:
// set the id in $_GET super global
$_GET['id'] = 1;
// include the file and catch the response
$result = include_once('Get_Users.php');
You can also create a function that can be called from UserView.php:
// Get_Users.php
<?php
function get_user($id) {
// connect to and query database here
// then return the result as json
return json_encode($arr);
}
?>
// In UserView.php you first include the above file and call the function
include_once('Get_Users.php');
$result = get_user(1);
You could also use file_get_contents(). Notice that you need to make sure so that allow_url_fopen is enabled in your php.ini file for this to work:
$result = file_get_contents('http://example.com/Get_Users.php?id=1');
To enable allow_url_fopen you need to open up your loaded configuration file and set allow_url_fopen=1 and finally restart your webserver.
You could also use curl to achieve the same result:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://example.com/Get_Users.php?id=1');
$result = curl_exec($ch);
curl_close($ch);
An ajax request could also be made to get the result. This example uses jQuery:
$(document).ready(function() {
$.get({
url: 'Get_Users.php',
data: 'id=1',
success: function(response) {
// response contains your json encoded data
// in this case you **must** use echo to transfer the data from `Get_Users.php`
}
});
});
Change UsersView.php to like this
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['CONTEXT_PREFIX'];
$url = "get_users.php?id=" . $id;
$url = $actual_link.$url;
$json = file_get_contents($url);
$result = json_decode($json, true);
This will work fine.
I have the the following code however the data only goes into the applicant table and not the applicant_edit table, and apparently I am having this error around the program, I may think it has something to do with the $_post but im not sure, also I have the same exact application running on another computer and it works fine, here is what i did, on this new machine, whiche seems to not be working well, I installed apache, then copied over my entire server folder with all the setting from my other machine, most things seem to be working however when it comes to $_post, thats where errors occur. Please Id love some help and suggestions.
<?php
include("config.php"); // put the *FULL* path to the file.
$url = 'index.php';
header('Location: ' . $url);
//header('Location: ' . $url);
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sq1="INSERT INTO applicant (app_trn,app_file_id, app_fname, app_lname,app_mid_name, app_strt_add_1, app_strt_add_2,app_city, app_parish, app_postal,
app_hme_cntct, app_cell1_cntct, app_cell2_cntct, app_email, app_gov_agncy, app_gov_agncy_strt,app_gov_agncy_city, app_gov_agncy_parish, app_post,
app_grade,app_appointment_date,app_salary,app_gov_last_agncy1,app_gov_last_agncy1_street,app_gov_last_agncy1_city,app_gov_last_agncy1_parish,
app_gov_last_agncy1_contact, app_gov_last_agncy2, app_gov_last_agncy2_street,app_gov_last_agncy2_city,app_gov_last_agncy2_parish,app_gov_last_agncy2_contact,
app_gov_last_agncy3,app_gov_last_agncy3_street,app_gov_last_agncy3_city,app_gov_last_agncy3_parish,app_gov_last_agncy3_contact)
VALUES
('$values[app_trn]','$values[app_file_id]', '$values[app_fname]','$values[app_lname]', '$values[app_mid_name]','$values[app_strt_add_1]', '$values[app_strt_add_2]',
'$values[app_city]', '$values[app_parish]', '$values[app_postal]', '$values[app_hme_cntct]', '$values[app_cell1_cntct]', '$values[app_cell2_cntct]',
'$values[app_email]', '$values[app_gov_agncy]', '$values[app_gov_agncy_strt]', '$values[app_gov_agncy_city]', '$values[app_gov_agncy_parish]','$values[app_post]',
'$values[app_grade]','$values[app_appointment_date]','$values[app_salary]','$values[app_gov_last_agncy1]','$values[app_gov_last_agncy1_street]',
'$values[app_gov_last_agncy1_city]','$values[app_gov_last_agncy1_parish]','$values[app_gov_last_agncy1_contact]', '$values[app_gov_last_agncy2]',
'$values[app_gov_last_agncy2_street]','$values[app_gov_last_agncy2_city]','$values[app_gov_last_agncy2_parish]','$values[app_gov_last_agncy2_contact]',
'$values[app_gov_last_agncy3]','$values[app_gov_last_agncy3_street]','$values[app_gov_last_agncy3_city]','$values[app_gov_last_agncy3_parish]',
'$values[app_gov_last_agncy3_contact]')";
$result = mysql_query($sq1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
mysql_query("INSERT INTO applicant_edit (applicant_edit_id,edit_app_trn)
VALUES ('','$values[app_trn]')");
?>
You're redirecting all traffic to index.php before anything happens
$url = 'index.php';
header('Location: ' . $url);
Remove that and see what happens
1- Remove header redirect code as mentioned by Paul
2- Try to print out one value
echo $values[app_trn];
echo "'$values[app_trn]'"; //test same case (double quota and single quota)
if it works, then, it will be sql error, try to print
echo mysql_error();
3-
I also suggest to use:
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
after this add:
foreach ($values as $kc => $vc){
$$kc = $vc;
}
now all values can be accessed by using key names:
VALUES
('$app_trn','$app_file_id', '$valuesapp_fname', ...
So I've started working on this twitter script that targets users who tweet about my website, and I want to set up this up with cron job to thank them for doing so. This is how it works:
Parses usernames from search page (15 in total)
Loops through all 15 user names and if its found in the twitter.txt file
it will stop the script
If the user name is not found in the twitter.txt file it will write
the user name to the twitter.txt file and then send a tweet to that user. (twitter.txt file helps to prevent sending of duplicate tweets to the same user)
So my issue is that this script currently sends out 15 tweets in one sitting and this would be considered spam. So I need help to be able to consolidate the user names in to 3 tweets. So each tweet will contain 5 user names. You will seet at the bottom of the script where i have the variables to store the usernames for the tweets.
//cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://search.twitter.com/search.atom?q=MYWEBSITE");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$twitter = curl_exec($curl);
curl_close($curl);
//search html source page for user names
preg_match_all('/\<uri\>http\:\/\/twitter\.com\/(.*?)\<\/uri\>/', $twitter, $usernames);
//open the twitter text file and prepare for writing
$twitter = fopen("twitter.txt", "a");
//contents of the twitter text file (holds the twitter user names)
$contents = file_get_contents("twitter.txt");
//loop through each user name
foreach($usernames[1] as $username) {
//if user name is found in the twitter text file it states "Found" and script stops
if (strpos($contents, $username) !== FALSE) {
echo $username . " - <font color=\"red\">Found</font><br />";
//if user name is not found in the twitter text file it records the user name and tweets
} else {
//write to twitter text file
fwrite($twitter, $username."\r\n");
//shows what user names were recorded
echo $username . "<br />";
//user names for tweets
//this is where i need help dividing the usernames into these variables
$usernames_set_one = "";
$usernames_set_two = "";
$usernames_set_three = "";
//tweet
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
$content = $connection->get('account/verify_credentials');
//twitter message
$connection->post('statuses/update', array('status' => $usernames_set_one . ' thank you for tweeting about my website.' ));
$connection->post('statuses/update', array('status' => $usernames_set_two . ' thank you for tweeting about my website.' ));
$connection->post('statuses/update', array('status' => $usernames_set_three . ' thank you for tweeting about my website.' ));
return $connection;
}
}
//close the twitter text file no further writing
fclose($twitter);
You can use a while loop instead of foreach and then access the usernames as:
$usernames[1][$i];
$usernames[1][$i+1];
$usernames[1][$i+2];
For example:
$i = 0;
$count = count($usernames[1]);
while($i < $count - 3) //we will use $i+2 after all
{
$i++;
}
Change those 3 variables to arrays and when the first one is full add usernames to the second array and then to the third. When posting to twitter simply join the names with implode().