I could not find this problem anywhere and nothing really related that I can see. I have a URL Shortening script that I purchased, this script works great on my first server, installed the database, FTP'd the files and was all set and shortening URLs.
But since then I moved it to a VPS server, I setup the server exactly same, with Centos 5.6. Installed the script, everything is fine. But the only thing that I find that does not work is the shortening process. I have no idea why it won't work. I have little knowledge of Ajax and JavaScript which I think the problem is with.
Here is ajax.php
<?php
require_once '../config.php';
function url_exist($url)
{
$c=curl_init();
curl_setopt($c,CURLOPT_URL,$url);
curl_setopt($c,CURLOPT_HEADER,1);
curl_setopt($c,CURLOPT_NOBODY,1);
curl_setopt($c,CURLOPT_RETURNTRANSFER,1);
if(!curl_exec($c)){
return false;
}else{
return true;
}
}
function shorteURLFromID ($integer)
{
$base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = strlen($base);
$out = '';
while($integer > $length - 1)
{
$out = $base[fmod($integer, $length)] . $out;
$integer = floor( $integer / $length );
}
return $base[$integer] . $out;
}
if(isset($_POST['url']))
{
$l_type = (string) $db->escape(trim(strip_tags($_POST['type'])));
$url = trim(strip_tags($_POST['url']));
$url = str_replace(array("http://"), array(''), $url);
if(strlen($url) < 3) {
print '<style>.alert-300{width:325px;margin-left:182px;}</style>';
die("<div class='alert alert-error alert-300'>".translate('empty_url_error')."</div>");
}
if(stristr($url, $_SERVER['SERVER_NAME'])) {
print '<style>.alert-300{width:325px;margin-left:182px;}</style>';
die("<div class='alert alert-error alert-300'>".translate('same_site_error')."</div>");
}
if(url_exist($url))
{
//check if exists for this user
$rs = $db->get_row("SELECT string FROM links WHERE uID = '".$usersObject->ID()."' AND
destination = '".mysql_real_escape_string($url)."' LIMIT 1");
if(count($rs)) {
$string = $rs->string;
print "http://".$_SERVER['SERVER_NAME']."/".$string;
}else{
$rs = $db->query("INSERT INTO links (destination, added, ip, uID, type) VALUES
('".$db->escape($url)."', '".time()."', '".ip2long($_SERVER['REMOTE_ADDR'])."',
'".$usersObject->ID()."', '".$l_type."')");
if($rs) {
$string = shorteURLFromID($db->insert_id);
$rs = $db->query("UPDATE links SET string = '$string' WHERE linkID = '".mysql_insert_id()."'");
print "http://".$_SERVER['SERVER_NAME']."/".$string;
}else{
print '<style>.alert-300{width:325px;margin-left:182px;}</style>';
print "<div class='alert alert-error alert-300'>Could not create shortened link ".mysql_error()."</div>";
}
}
}else{
print '<style>.alert-300{width:325px;margin-left:182px;}</style>';
print "<div class='alert alert-error alert-300'>".translate('invalid_url_error')."</div>";
}
}else{
print '<style>.alert-300{width:325px;margin-left:182px;}</style>';
print '<div class="alert alert-error alert-300">'.translate('invalid_url_error').'</div>';
}
?>
The only thing that comes to mind without further info (or source of the script) is the version of PHP you're using. Is it different than that of the old server? If so, is it pre-5.2?
Try adding in this option:
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
It looks like the default was changed with cURL 7.10 to true, so it is possible PHP 5.2.17 was using a version prior to 7.10.
Levi
Related
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
I have a php script handling an incoming ajax request. It looks up some credentials from text files and if they match requirements it sets two cookies, one called username and one called creds on the client machine.
When I do this from my local web server, all three cookies get set and I receive all the php feedback from the echoes.
When I do this from my hosted web server the first setcookie works ("cookies","enabled") but the next two dont! However I get all the echoes confirming that php has reached the point in my script where they should be set. Any ideas please? I am thoroughly stumped.
<?php
//george:bloog
//emeline:sparg
setCookie("primacy[cookies]","enabled", time()+3600*24*30,'/');
//convert string to summed int
function pwdInt($pw)
{
$pwdIntVal = 0;
for($i=0; $i<strlen($pw);$i++)
{
$pwdIntVal = $pwdIntVal + ( ord(strtolower($pw[$i])) - 96 );
}
return $pwdIntVal;
}
//retrieve user account creation date by parsing savefile for accountCreate var
function getACD($aUSR)
{
$saveFileName = "saveFiles/" . $aUSR . ".txt";
echo "Fetched save successfully.<br>";
$lines = file($saveFileName);
foreach($lines as $line)
{
if( explode(":",$line)[0] == "accountCreate");
$lineDate = explode(":",$line)[1];
return $lineDate;
}
}
//accept incoming vars
if(isset($_POST['username']) && !empty($_POST['username']))
{
$uN = strtolower($_POST['username']);
$pwd = strtolower($_POST['password']);
$found = "Invalid user";
//test for presence in creds
$lines = file("creds/creds.txt");
foreach($lines as $line)
{
$lineName = explode("_",$line)[0];
if($uN == $lineName)
{
//matched username before delimiter "_"
$found = $lineName;
echo "Found user, " . explode("_",$line)[0] . " checking password<br>";
//check two: use int of pwd with account creation date from user save
$usrACD = getACD($uN);
echo $usrACD;
if( (pwdInt($pwd) * $usrACD) == (explode("_",$line)[1]) )
{
echo "Tests passed: granting access cookies";
setCookie("uN",$uN, time()+3600*24*30,'/');
setCookie("cred",(pwdInt($pwd) * $usrACD), time()+3600*24*30,'/');
}
else
{
echo "Failed password check for allowed user<br>";
}
}
}
}
else
{
echo $found . pwdInt($pwd) . "<br>";
}
?>
You should either enable output buffering or move echoes after setCookie method. Setting cookies is thing that happens during headers of response. All headers should be sent before content. Echoing things is setting up content, so every header edition (like setting cookies) after first echo will fail.
How can you mimic a command line run of a script with arguements inside a PHP script? Or is that not possible?
In other words, let's say you have the following script:
#!/usr/bin/php
<?php
require "../src/php/whatsprot.class.php";
function fgets_u($pStdn) {
$pArr = array($pStdn);
if (false === ($num_changed_streams = stream_select($pArr, $write = NULL, $except = NULL, 0))) {
print("\$ 001 Socket Error : UNABLE TO WATCH STDIN.\n");
return FALSE;
} elseif ($num_changed_streams > 0) {
return trim(fgets($pStdn, 1024));
}
}
$nickname = "WhatsAPI Test";
$sender = ""; // Mobile number with country code (but without + or 00)
$imei = ""; // MAC Address for iOS IMEI for other platform (Android/etc)
$countrycode = substr($sender, 0, 2);
$phonenumber=substr($sender, 2);
if ($argc < 2) {
echo "USAGE: ".$_SERVER['argv'][0]." [-l] [-s <phone> <message>] [-i <phone>]\n";
echo "\tphone: full number including country code, without '+' or '00'\n";
echo "\t-s: send message\n";
echo "\t-l: listen for new messages\n";
echo "\t-i: interactive conversation with <phone>\n";
exit(1);
}
$dst=$_SERVER['argv'][2];
$msg = "";
for ($i=3; $i<$argc; $i++) {
$msg .= $_SERVER['argv'][$i]." ";
}
echo "[] Logging in as '$nickname' ($sender)\n";
$wa = new WhatsProt($sender, $imei, $nickname, true);
$url = "https://r.whatsapp.net/v1/exist.php?cc=".$countrycode."&in=".$phonenumber."&udid=".$wa->encryptPassword();
$content = file_get_contents($url);
if(stristr($content,'status="ok"') === false){
echo "Wrong Password\n";
exit(0);
}
$wa->Connect();
$wa->Login();
if ($_SERVER['argv'][1] == "-i") {
echo "\n[] Interactive conversation with $dst:\n";
stream_set_timeout(STDIN,1);
while(TRUE) {
$wa->PollMessages();
$buff = $wa->GetMessages();
if(!empty($buff)){
print_r($buff);
}
$line = fgets_u(STDIN);
if ($line != "") {
if (strrchr($line, " ")) {
// needs PHP >= 5.3.0
$command = trim(strstr($line, ' ', TRUE));
} else {
$command = $line;
}
switch ($command) {
case "/query":
$dst = trim(strstr($line, ' ', FALSE));
echo "[] Interactive conversation with $dst:\n";
break;
case "/accountinfo":
echo "[] Account Info: ";
$wa->accountInfo();
break;
case "/lastseen":
echo "[] Request last seen $dst: ";
$wa->RequestLastSeen("$dst");
break;
default:
echo "[] Send message to $dst: $line\n";
$wa->Message(time()."-1", $dst , $line);
break;
}
}
}
exit(0);
}
if ($_SERVER['argv'][1] == "-l") {
echo "\n[] Listen mode:\n";
while (TRUE) {
$wa->PollMessages();
$data = $wa->GetMessages();
if(!empty($data)) print_r($data);
sleep(1);
}
exit(0);
}
echo "\n[] Request last seen $dst: ";
$wa->RequestLastSeen($dst);
echo "\n[] Send message to $dst: $msg\n";
$wa->Message(time()."-1", $dst , $msg);
echo "\n";
?>
To run this script, you are meant to go to the Command Line, down to the directory the file is in, and then type in something like php -s "whatsapp.php" "Number" "Message".
But what if I wanted to bypass the Command Line altogether and do that directly inside the script so that I can run it at any time from my Web Server, how would I do that?
First off, you should be using getopt.
In PHP it supports both short and long formats.
Usage demos are documented at the page I've linked to. In your case, I suspect you'll have difficulty detecting whether a <message> was included as your -s tag's second parameter. It will probably be easier to make the message a parameter for its own option.
$options = getopt("ls:m:i:");
if (isset($options["s"] && !isset($options["m"])) {
die("-s needs -m");
}
As for running things from a web server ... well, you pass variables to a command line PHP script using getopt() and $argv, but you pass variables from a web server using $_GET and $_POST. If you can figure out a sensible way to map $_GET variables your command line options, you should be good to go.
Note that a variety of other considerations exist when taking a command line script and running it through a web server. Permission and security go hand in hand, usually as inverse functions of each other. That is, if you open up permissions so that it's allowed to do what it needs, you may expose or even create vulnerabilities on your server. I don't recommend you do this unless you'll more experienced, or you don't mind if things break or get attacked by script kiddies out to 0wn your server.
You're looking for backticks, see
http://php.net/manual/en/language.operators.execution.php
Or you can use shell_exec()
http://www.php.net/manual/en/function.shell-exec.php
Here is my code, you can view an example of it by going to:
www.craftquake.com/statusChecker.php?site=MCnet
<?php
$getter = $_GET['site'];
if ($getter == 'ts3')
{ $site = test_port('ts3.craftquake.com',10011,4); }
if ($getter == 'MCquake')
{ $site = test_port('play.craftquake.com',25565,4); }
if ($getter == 'MCnet')
{ $site = test_port('minecraft.net',80,4); }
$teamspeak = test_port('ts3.craftquake.com',10011,4);
$online = '<img src="/online.png">';
$offline = '<img src="/offline.png">';
$unknown = '<span class="status-unknown" id="status-image">Unknown</span>';
function test_port($host,$port=80,$timeout=1)
{
$fsock = fsockopen($host, $port, $errno, $errstr, $timeout);
if ( ! $fsock )
{
return FALSE;
}
else
{
return TRUE;
}
}
?>
##HEADER & CSS, ETC
<?php
if ($site == 1)
{ $status = $online;
} else if ($site == 0) {
$status = $offline;
} else {
$status = $unknown;
}
header('content-type: image/png');
readfile($status);
echo $status;
?>
I want to, in the footer of my page, link to this page to display the status. I was doing this with another site's script by linking their status of Minecraft.net's servers as the and it worked perfectly, however I have no idea how they made that work. The images are PNG's, but if there is only one format that works, I can convert them.
I have tried the header(blablabla) function, but it doesn't seem to work...
Thank you very much!
Your variables contain HTML instead of the path name to the image files:
$online = '<img src="/online.png">';
should be:
$online = 'online.png';
Create a unknown status image and put it in $unknown too.
An image should be a seperate request (so, put an <img src="/yourimagescript.php"> in your html page, and in that seperate script output only the image, no html. You could embed (small) images with the data: protocol, but I strongly advise against it.
This issue came up to me in vBulletin system. i want to build a block in sidebar area to help me autmate some daily works.. i wrote php code like this :
<?php
$myDay = date('D');
$myHour = date('G');
// Saturday
if ($myDay == "Sat") {
if ($myHour >= 7) {
$output = include('textFilePath/saturday.txt');
} else {
$output = include('textFilePath/friday.txt');
}
}
// Sunday
if ($myDay == "Sun") {
if ($myHour >= 7) {
$output = include('textFilePath/sunday.txt');
} else {
$output = include('textFilePath/saturday.txt');
}
}
// and it goes on to friday...
// and in the end :
return $output;
?>
my problem is with include() function . when i return the $output value it returns a boolean(0 or 1) and include function writes out the txt files content in the beginning of document instead of "sidebar block"
i know i can echo the actual content instead of using include and txt files. but as i said i want to automate the daily tasks and give the users access to edit the txt files.
is there any other technique or function to assign the content of a local file to a variable ?
you may want to check
$output = file_get_contents('textFilePath/saturday.txt');
more information here : http://in3.php.net/file_get_contents