How to create folder on dropbox using php - php

I want to create the folder dynamically on dropbox and i am using the below code but it gives me error please help me
function CreateFolder($path) {
return $this->apiCall("fileops/create_folder", "POST", array('root'=> $this->rootPath, 'path' => $path));
}
$x = 'test';
CreateFolder($x);
But it gives me the error
Parse error: syntax error, unexpected '$x' (T_VARIABLE), expecting
function (T_FUNCTION) in
/home/stsgbnet/public_html/stockpile/DropPHP-master/DropboxClient.php
on line 451
My complete code is here
http://pastebin.com/HnPvV4b0

Since CreateFolder function seems to be in a class ($this->apiCall points to that), $x should be encapsulated in a function (that is the error that's shown). So to make it work, just call it from outside class.
You are using DropboxClient.php so following sample.php from this package your create a php file and put the following code on it:
<?php
// these 2 lines are just to enable error reporting and disable output buffering (don't include this in you application!)
error_reporting(E_ALL);
enable_implicit_flush();
// -- end of unneeded stuff
// if there are many files in your Dropbox it can take some time, so disable the max. execution time
set_time_limit(0);
require_once("DropboxClient.php");
// you have to create an app at https://www.dropbox.com/developers/apps and enter details below:
$dropbox = new DropboxClient(array(
'app_key' => "",
'app_secret' => "",
'app_full_access' => false,
),'en');
// first try to load existing access token
$access_token = load_token("access");
if(!empty($access_token)) {
$dropbox->SetAccessToken($access_token);
echo "loaded access token:";
print_r($access_token);
}
elseif(!empty($_GET['auth_callback'])) // are we coming from dropbox's auth page?
{
// then load our previosly created request token
$request_token = load_token($_GET['oauth_token']);
if(empty($request_token)) die('Request token not found!');
// get & store access token, the request token is not needed anymore
$access_token = $dropbox->GetAccessToken($request_token);
store_token($access_token, "access");
delete_token($_GET['oauth_token']);
}
// checks if access token is required
if(!$dropbox->IsAuthorized())
{
// redirect user to dropbox auth page
$return_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']."?auth_callback=1";
$auth_url = $dropbox->BuildAuthorizeUrl($return_url);
$request_token = $dropbox->GetRequestToken();
store_token($request_token, $request_token['t']);
die("Authentication required. <a href='$auth_url'>Click here.</a>");
}
echo "<pre>";
echo "<b>Account:</b>\r\n";
print_r($dropbox->GetAccountInfo());
// Here will create the folder.
$dropbox->CreateFolder('test');
function store_token($token, $name)
{
if(!file_put_contents("tokens/$name.token", serialize($token)))
die('<br />Could not store token! <b>Make sure that the directory `tokens` exists and is writable!</b>');
}
function load_token($name)
{
if(!file_exists("tokens/$name.token")) return null;
return #unserialize(#file_get_contents("tokens/$name.token"));
}
function delete_token($name)
{
#unlink("tokens/$name.token");
}
function enable_implicit_flush()
{
#apache_setenv('no-gzip', 1);
#ini_set('zlib.output_compression', 0);
#ini_set('implicit_flush', 1);
for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
ob_implicit_flush(1);
echo "<!-- ".str_repeat(' ', 2000)." -->";
}
?>
Hope it helps.

Related

How To Start Multiple Session

Hye, I've been creating this Quiz System, and I found myself in an error...The error started when I tried to add a DDOS Protection...Both start.php and configs.php started a session..and if the include function called start.php first, then it will only run start.php session and ignored the configs.php and vice versa. My question is how do i start both session at the same time so my website can work properly? Take a look at my code.
This is configs.php
P/S : I cut of some code to keep it short
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 'On');
function rewrite_urls($change){
$match = [
'/userdetails.php\?id=([0-9]+)/',
'/userdetails.php/',
'/plans.php/',
'/statistics.php\?id=([0-9]+)&t=([A-Za-z0-9_-]+)/',
'/quizzes.php\?request=my/',
'/quizzes.php\?id=([0-9]+)&t=([A-Za-z0-9_-]+)&request=results&r=([0-9]+)/',
'/quizzes.php\?id=([0-9]+)&t=([A-Za-z0-9_-]+)&request=results/',
'/quizzes.php\?id=([0-9]+)&t=([A-Za-z0-9_-]+)/',
'/quizzes.php\?c=([0-9]+)\&t=([A-Za-z0-9_-]+)\&page=([0-9]+)/',
'/quizzes.php\?c=([0-9]+)\&t=([A-Za-z0-9_-]+)/',
'/quizzes.php\?page=([0-9]+)/',
'/quizzes.php/',
This is my start.php
P/S : I cut of some code to keep it short
<?php
/**
* AntiDDOS System
* FILE: index.php
* By Sanix Darker
*/
function safe_print($value){
$value .= "";
return strlen($value) > 1 && (strpos($value, "0") !== false) ? ltrim($value, "0") : (strlen($value) == 0 ? "0" : $value);
}
if(!isset($_SESSION)){
session_start();
}
if(isset($_SESSION['standby'])){
// There is all your configuration
$_SESSION['standby'] = $_SESSION['standby']+1;
$ad_ddos_query = 5;// ​​number of requests per second to detect DDOS attacks
$ad_check_file = 'check.txt';// file to write the current state during the monitoring
$ad_all_file = 'all_ip.txt';// temporary file
$ad_black_file = 'black_ip.txt';// will be entered into a zombie machine ip
$ad_white_file = 'white_ip.txt';// ip logged visitors
$ad_temp_file = 'ad_temp_file.txt';// ip logged visitors
$ad_dir = 'anti_ddos/files';// directory with scripts
$ad_num_query = 0;// ​​current number of requests per second from a file $check_file
$ad_sec_query = 0;// ​​second from a file $check_file
$ad_end_defense = 0;// ​​end while protecting the file $check_file
$ad_sec = date("s");// current second
$ad_date = date("is");// current time
$ad_defense_time = 100;// ddos ​​attack detection time in seconds at which stops monitoring
I also have head.php which will be called in every page
This is the code for head.php
<?php
try{
if (!file_exists('anti_ddos/start.php'))
throw new Exception ('anti_ddos/start.php does not exist');
else
require_once('anti_ddos/start.php');
}
//CATCH the exception if something goes wrong.
catch (Exception $ex) {
echo '<div style="padding:10px;color:white;position:fixed;top:0;left:0;width:100%;background:black;text-align:center;">'.
'The "AntiDDOS System" failed to load '.
'properly on this Web Site, please de-comment the \'catch Exception\' to see what happening!</div>';
//Print out the exception message.
//echo $ex->getMessage();
}
include __DIR__."/configs.php";
?>
Any Idea?

How could I check if there is code outside a class in php?

Let's say that you have a class in php with functions and all that. How could you check if there is no code outside the class?
I tried to code this checker with PHP and did it with regex and tokens but nothing worked for me :/
An exmple
<?php
class example {
var $name;
var $password;
function __construct($name, $password) {
$this->name = $name;
$this->password = $password;
}
----Allowed code----
}
----Not allowed code----
?>
EDIT: (SOLVED)
Thanks #user3163495 for all the information
Here what I did:
1º I tried to get the class name inside the file with this two functions:
function getClass($tokens) {
$clases = array();
for($i = 0; $i < count($tokens); $i++) {
//Tipo del token actual
$tokenName = getTokenName($tokens, $i);
if($tokenName === "T_CLASS") {
//Searchs the name that it has in the file.
return getClassName($tokens, $i);
}
}
return "";
}
function getClassName($tokens, $i) {
$index = $i + 1;
//Line in which is the class inside the file
$lineaClase = getTokenLine($tokens, $i);
//Line to be updated while searching
$lineaTemp = getTokenLine($tokens, $index);
//Type of token to be updated while searching
$tokenName = getTokenName($tokens, $index);
//Searchs in the parsed array for the first class token
while($index < count($tokens) &&
$lineaClase === $lineaTemp &&
($tokenName === "UNKOWN" || $tokenName === "T_WHITESPACE")) {
$index++;
$tokenName = getTokenName($tokens, $index);
$lineaTemp = getTokenLine($tokens, $index);
}
//Returns the name of the class
return getTokenContent($tokens, $index);
}
Then, I injected PHP code in the end of the file that I tried to check if it's only a class. Also I saved this new content in a new file called temp.php and finally I shell-executed this to get the echo of the injected code, that will correspond to beginning_of_class:end_of_class. Here is where I used what #user3163495 told me, thank you again.
function codeInjection($clase, $contenido) {
//PHP code to inject, thanks to #user3163495
$codigoPHP = "<?php \$class = new ReflectionClass(\"{$clase}\"); \$comienzo = \$class->getStartLine(); \$fin = \$class->getEndLine(); echo \$comienzo . \":\" . \$fin; ?>";
$contenido .= $codigoPHP;
//Creating temp file
file_put_contents("temp.php", $contenido);
//Returning result of execution
return shell_exec("php temp.php");
}
Further, I removed from the token parsed array those tokens which line where between the beginning and the end of the class. Last I go through the array searching for something that is different than a comment, white space, etc..
(Variables are in spanish, if you don't understand the meaning of some feel free to ask)
If you are wanting to "scan" the questionable file from another script to see if there is any code outside the class, then you could use the ReflectionClass in PHP.
Step 1: get the file name that your class is defined in
$class = new ReflectionClass("example");
$fileName = $class->getFileName();
Step 2: get the starting and ending lines of code that the class definition occupies in the file
$startLine = $class->getStartLine();
$endLine = $class->getEndLine();
$numLines = $endLine - $startLine;
Step 3: use file_get_contents() on the file name you obtained in Step 1, and see if there is any forbidden code before the start line or after the end line. You'll have to test and play around with what you get as I don't know exactly where getStartLine() and getEndLine() consider "start" and "end", respectively.
I hope you get the idea.
Some code lifted from this answer: https://stackoverflow.com/a/7909101/3163495

DropBox configration via composer

Hello guys I'm new to composer thing. Previously I had configured dropbox manually in my codeigniter project but my head asked me to do it using composer now. I have configured composer somehow and installed dropbox using composer. Now this was my login function which I used before
public function login() {
// $this->CI->session->set_userdata('state', 1);
$this->CI->session->dropbox_success = false;
$oauth = new Dropbox_OAuth_PHP($this->CI->config->item('APP_KEY'), $this->CI->config->item('APP_SECRET'));
$this->dropbox = new Dropbox_API($oauth);
if ($this->CI->session->state) {
$state = $this->CI->session->state;
} else {
$this->CI->session->set_userdata('state', 1);
$state = 1;
}
switch ($state) {
/* In this phase we grab the initial request tokens
and redirect the user to the 'authorize' page hosted
on dropbox */
case 1 :
// echo "Step 1: Acquire request tokens\n";
$tokens = $oauth->getRequestToken();
// echo "<a href='".$oauth->getAuthorizeUrl(site_url())."' >Authorize</a>";
// header('Location: '. $oauth->getAuthorizeUrl());
echo "<img width='30px' src='" . base_url() . "somePAth'> Connect Dropbox";
$this->CI->session->set_userdata('state', 2);
$this->CI->session->set_userdata('oauth_tokens', $tokens);
return FALSE;
/* In this phase, the user just came back from authorizing
and we're going to fetch the real access tokens */
case 2 :
if (!$this->CI->session->oauth_tokens) {
$this->CI->session->set_userdata('state', 1);
header("Location: ?");
}
$oauth->setToken($this->CI->session->oauth_tokens);
$tokens = null;
try {
$tokens = $oauth->getAccessToken();
} catch (Exception $e) {
$this->CI->session->set_userdata('state', 1);
header("Location: ?");
return false;
}
$this->CI->session->set_userdata('state', 3);
$this->CI->session->set_userdata('oauth_tokens', $tokens);
header("Location: ?");
case 3 :
// echo "The user is authenticated\n";
$this->CI->session->dropbox_success = true;
$oauth->setToken($this->CI->session->oauth_tokens);
echo "<a class='btn btn-primary float-right' href=" . base_url('somePath') . ">Disconnect Dropbox</a>";
return true;
}
}
Now after I installed dropbox using composer and after going through the configration I created the app-info.json file and included the code which dropbox asked me to add in the code which is $oauth = dbx\AppInfo::loadFromJsonFile("../config/app-info.json"); in place of the second uncommented line but it's not working. It is throwing me this error.
ERROR : Exception of type 'Error' occurred with Message: Class 'dbx\AppInfo' not found in File D:\Ampps\www\softcake\application\libraries\Dropbox.php at Line 30
So can somebody please guide me what is it that I'm doing wrong and redirect me to some solution which would help me in configuring drop box in my app. Thanks in advance

Twilio REST API sequential Dialling

I really can't figure out why my code isn't working because Twilio's debugger isnt giving me errors so I don't know what to do...I am trying to make Sequential dialing in REST api using Twilio so it should keep calling numbers in order until one person picks up..Below is my code I have written so far. I am using sessions to keep track of the calls.
File Name:dial.php
<?php
session_start();
require 'Services/Twilio.php';
$version = "2010-04-01";
$arr = array('4167641123','6478604321','9058553456');
$sid = '....';
$token = '...';
$from = '....';
$to = '416.....';
$callback = 'www.site.com/dial.php';
$client = new Services_Twilio($sid, $token, $version);
//if this is our very first call then CallStatus should be empty so it means we can use the emptiness of this variable
//to trigger our very first call
if (!(isset($_REQUEST['CallStatus'])))
{
try {
$call = $client->account->calls->create(
$from,
$arr[0],
'http://demo.twilio.com/welcome/voice/',
array('Timeout' => 1,
'StatusCallback' => $callback)
);
var_dump($call);
} catch (Exception $e) {
var_dump($e);
}
}
// if the CallStatus variable is not empty then the else statement will execute
else
{
//if this part of code runs for the first time, it means this is our 2nd call because the 1st person did not pick up
//this means the second number in the array will be called
//each time this statement runs it adds a 1 to the index of the array but if the last index number called was the final and
//last number in the array, then this statement wont run and instead session at the bottom if statement will be initialized to 0
//so that if this script is ran again it will start off from the first number in the array
if (!($_SESSION['X']>=count($arr)-1) && isset($_REQUEST['CallStatus']) && ($_REQUEST['CallStatus']=='failed'|| $_REQUEST['CallStatus']=='no-answer' || $_REQUEST['CallStatus']=='busy'))
{
$_SESSION['X']=$_SESSION['X']+1;
try {
$call = $client->account->calls->create(
$from,
$arr[SESSION['X']],
'http://demo.twilio.com/welcome/voice/',
array('Timeout' => 1,
'StatusCallback' => $callback)
);
var_dump($call);
} catch (Exception $e) {
var_dump($e);
}
}
//initializes the session to 0 because if we have reached to this else statement,
//then it means the if statement above did not run and we have already called the last person
//in the phone number array so we are at an end and we must close the program
//by leaving session at 0 for the next trial to run properly
else
{
$_SESSION['X']=0;
}
}
I have this other file same, sequential diallnig written using php and twilio's Dial verb, the Dial verb's parameters allow it to pass the array index but in my case I don't know how to pass the array index parameter....any ideas?
<?php
// Set the numbers to call
$numbers = array("<number to call 1>", "<number to call 2>", "<number to call n>");
$number_index = isset($_REQUEST['number_index']) ? $_REQUEST['number_index'] : "0";
$DialCallStatus = isset($_REQUEST['DialCallStatus']) ? $_REQUEST['DialCallStatus'] : "";
header("content-type: text/xml");
// Check the status of the call and
// that there is a valid number to call
if($DialCallStatus!="completed" && $number_index<count($numbers)){
?>
<Response>
<Dial action="attempt_call.php?number_index=<?php echo $number_index+1 ?>">
<Number url="screen_for_machine.php">
<?php echo $numbers[$number_index] ?>
</Number>
</Dial>
</Response>
<?php
} else {
?>
<Response>
<Hangup/>
</Response>
<?php
}
?>
Your code has syntax errors and such.
For example SESSION['X']=0; is not doing what you might have thought it is doing. If that's a session variable, it should be written as $_SESSION['X']=0;.
To spot these issues, enable error reporting to the highest level, then log errors to a file and then watch that file. It will give you some hints.
See Error Handling and Logging Docs.

Echo can you hear me?

Why is showphp_Smartfm() Not echoing at all.
foreach($response->quizzes as $quiz)
{
echo $quiz->question; // not echoing
echo $quiz->answer; // not echoing
}
Followup Question to Navigating objects and arrays
http://github.com/klanestro/Vortoj
<html>
<body>
<?php
// Created by Talisman 01/2010 ★✩
$vorto = $_GET['vorto']; // Get the Word from Outer Space and Search for it!
if (isset($vorto))
{
echo " Your Direct search was " . $vorto . ' <br></br> ';
} else {
$Help = "No Vorto -> add ?vorto=TheWordYouWant to the end of this website";
echo $Help;
}
// Now Lets Search Alex's Vortaro, It uses jsonp
// ex. http://vortaro.us.to/ajax/epo/eng/petas/?callback=?
/* Future Feature inproved language functinality */
// I used the capital AV to denote variables belonging to Alex's Vortaro
// #Plans for ( traduku.net, tn
// :apertium.org,ap // I think its apertium.org
// :reto-vartaro,rv
// each root word has an xml file, but how to you find this xml file?
// there is a xml link on the bottom of a search result, but I can't figure
// out a way to get to this info.
// :project gutenburg, pg
// :google books, gb
// BUT NEXT UP ЄЭ smart.fm
// it also assumes epo-eng
function getphp_AlexVortaro ($vorto)
{
$AVurl1 = "http://vortaro.us.to/ajax/epo/eng/";
$AVurl2 = "/?callback=";
$AVfinalurl= $AVurl1 . $vorto . $AVurl2;
$AVcontent = file_get_contents($AVfinalurl) ;
// Now we need to trim the () jsonp to json
$AVcontent = substr($AVcontent, 1);
$AVcontent = substr($AVcontent,0,-1);
$AVDecode = json_decode($AVcontent);
return ($AVDecode);
}
function getphp_Smartfm($vorto)
{
$SFurl="http://api.smart.fm/items/matching/";
// $SFurl2=urlencode($vorto); // +".json";
$SFurl3="?language=eo&translation_language=en";
$SFfinalurl = $SFurl . $vorto . ".json" . $SFurl3; // you can change .json to .xml
$SFcontent = file_get_contents($SFfinalurl);
$SFDecode = json_decode($SFcontent);
return ($SFDecode);
}
$AVvorto = getphp_AlexVortaro ($vorto);
$SFvorto = getphp_Smartfm($vorto);
function showphp_AlexVortaro ($AVvorto)
{
$AVvortoshow = $AVvorto->text;
echo $AVvortoshow;
}
showphp_AlexVortaro ($AVvorto);
function showphp_Smartfm($SFvorto)
{
// $objects is the array with all those objects
foreach($SFvorto as $object)
{
echo $object->cue->language; // language
foreach($object->responses as $response)
{
// if there are no quizzes, we skip the part below
// we skip it because $object->quizzes will produce a warning or a notice
// if "quizess" is not a member of the $object
if(!isset($object->quizzes))
{
continue;
}
// quizess
foreach($response->quizzes as $quiz)
{
echo $quiz->question; // question
echo $quiz->answer; // answer
}
}
}
}
showphp_Smartfm($SFvorto);
?>
</body>
</html>
This fixed it
- if(!isset($object->quizzes))
0
+ if(!isset($object->responses))
Go here
http://github.com/klanestro/Vortoj/commit/625fce9ffbd2a4d45d7b8dffddff6986fe521a00#comment_43364
Start doing 'echo-debugging'.
print_r($response);
print_r($response->quizzes);
foreach($response->quizzes as $quiz)
{
echo $quiz->question; // question
echo $quiz->answer; // answer
}
Maybe there are no $response->quizzes
Maybe the question and answer are empty string
Maybe this code is never being reached
Maybe it's outputting inside an HTML tag and you never thought to check View Source
Maybe it's dying way earlier in the script and you don't have error reporting turned on.
Enable all the error reportings:
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
//or directly edit your php.ini !
and try with:
foreach($response->quizzes as $quiz)
{
var_dump($quiz->question); // question
var_dump($quiz->answer); // answer
}
and see what is going on

Categories