Quantcast
Channel: PHP Freaks: PHP Help
Viewing all 13200 articles
Browse latest View live

form values dissapear in captcha validation

$
0
0

Hi everyone,

 

I am unable to get the any of the form values to stay after submission with captcha.

 

My code is below.

 

Please help. Also the error of the validation doesnt display on submission



<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
.success {color:#360; background-color:#FF0;}
.fail {color:#F00; background-color:#FFF;)
</style>
</head>
<body>

<?php

 if (isset($_POST['submit'])){
 
 $name = $_POST['name'];
 $email = $_POST['email'];
 $phone = $_POST['phone'];
 $country = $_POST['country'];
 $comment = $_POST['comment'];
 $gender = $_POST['gender'];
 
 $to = "laxmon@wikigets.com";
 $subject = "New contact form submission";
 $message =" A visitor of WIKIGETS has submited a form onine\n\n $name\n\n $email\n\n $phone \n\n $country \n\n $gender\n\n $comment";
 
 
 
 
   require_once('recaptchalib.php');
  $privatekey = "6LdK8_YSAAAAAJYPJduOpxhsL4Cy86NgwpCSJCod";
  $resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
    	
	
	
 header	("Location:contact.php?s=2");
 
 
  } else {
    mail($to,$subject,$message);
	header	("Location:contact.php?s=1");
  }
  
  
}
  ?>

 <? 
 	
	$country_options= array("select","Afghanistan",	"Ã…Land Islands",	"Albania",	"Algeria",	"American Samoa",	"Andorra",	"Angola",	"Anguilla",	"Antarctica",	"Antigua And Barbuda",	"Argentina",	"Armenia",	"Aruba",	"Australia",	"Austria",	"Azerbaijan",	"Bahamas",	"Bahrain",	"Bangladesh",	"Barbados",	"Belarus",	"Belgium",	"Belize",	"Benin",	"Bermuda",	"Bhutan",	"Bolivia",	"Bosnia And Herzegovina",	"Botswana",	"Bouvet Island",	"Brazil",	"British Indian Ocean Territory",	"Brunei Darussalam",	"Bulgaria",	"Burkina Faso",	"Burundi",	"Cambodia",	"Cameroon",	"Canada",	"Cape Verde",	"Cayman Islands",	"Central African Republic",	"Chad",	"Chile",	"China",	"Christmas Island",	"Cocos (Keeling) Islands",	"Colombia",	"Comoros",	"Congo",	"Congo, The Democratic Republic Of The",	"Cook Islands",	"Costa Rica",	"Cote D'Ivoire",	"Croatia",	"Cuba",	"Cyprus",	"Czech Republic",	"Denmark",	"Djibouti",	"Dominica",	"Dominican Republic",	"Ecuador",	"Egypt",	"El Salvador",	"Equatorial Guinea",	"Eritrea",	"Estonia",	"Ethiopia",	"Falkland Islands (Malvinas)",	"Faroe Islands",	"Fiji",	"Finland",	"France",	"French Guiana",	"French Polynesia",	"French Southern Territories",	"Gabon",	"Gambia",	"Georgia",	"Germany",	"Ghana",	"Gibraltar",	"Greece",	"Greenland",	"Grenada",	"Guadeloupe",	"Guam",	"Guatemala",	"Guernsey",	"Guinea",	"Guinea-Bissau",	"Guyana",	"Haiti",	"Heard Island And Mcdonald Islands",	"Holy See (Vatican City State)",	"Honduras",	"Hong Kong",	"Hungary",	"Iceland",	"India",	"Indonesia",	"Iran, Islamic Republic Of",	"Iraq",	"Ireland",	"Isle Of Man",	"Israel",	"Italy",	"Jamaica",	"Japan",	"Jersey",	"Jordan",	"Kazakhstan",	"Kenya",	"Kiribati",	"Korea, Democratic People'S Republic Of",	"Korea, Republic Of",	"Kuwait",	"Kyrgyzstan",	"Lao People'S Democratic Republic",	"Latvia",	"Lebanon",	"Lesotho",	"Liberia",	"Libyan Arab Jamahiriya",	"Liechtenstein",	"Lithuania",	"Luxembourg",	"Macao",	"Macedonia, The Former Yugoslav Republic Of",	"Madagascar",	"Malawi",	"Malaysia",	"Maldives",	"Mali",	"Malta",	"Marshall Islands",	"Martinique",	"Mauritania",	"Mauritius",	"Mayotte",	"Mexico",	"Micronesia, Federated States Of",	"Moldova, Republic Of",	"Monaco",	"Mongolia",	"Montserrat",	"Morocco",	"Mozambique",	"Myanmar",	"Namibia",	"Nauru",	"Nepal",	"Netherlands",	"Netherlands Antilles",	"New Caledonia",	"New Zealand",	"Nicaragua",	"Niger",	"Nigeria",	"Niue",	"Norfolk Island",	"Northern Mariana Islands",	"Norway",	"Oman",	"Pakistan",	"Palau",	"Palestinian Territory, Occupied",	"Panama",	"Papua New Guinea",	"Paraguay",	"Peru",	"Philippines",	"Pitcairn",	"Poland",	"Portugal",	"Puerto Rico",	"Qatar",	"Reunion",	"Romania",	"Russian Federation",	"Rwanda",	"Saint Helena",	"Saint Kitts And Nevis",	"Saint Lucia",	"Saint Pierre And Miquelon",	"Saint Vincent And The Grenadines",	"Samoa",	"San Marino",	"Sao Tome And Principe",	"Saudi Arabia",	"Senegal",	"Serbia And Montenegro",	"Seychelles",	"Sierra Leone",	"Singapore",	"Slovakia",	"Slovenia",	"Solomon Islands",	"Somalia",	"South Africa",	"South Georgia And The South Sandwich Islands",	"Spain",	"Sri Lanka",	"Sudan",	"Suriname",	"Svalbard And Jan Mayen",	"Swaziland",	"Sweden",	"Switzerland",	"Syrian Arab Republic",	"Taiwan, Province Of China",	"Tajikistan",	"Tanzania, United Republic Of",	"Thailand",	"Timor-Leste",	"Togo",	"Tokelau",	"Tonga",	"Trinidad And Tobago",	"Tunisia",	"Turkey",	"Turkmenistan",	"Turks And Caicos Islands",	"Tuvalu",	"Uganda",	"Ukraine",	"United Arab Emirates",	"United Kingdom",	"United States",	"United States Minor Outlying Islands",	"Uruguay",	"Uzbekistan",	"Vanuatu",	"Venezuela",	"Viet Nam",	"Virgin Islands, British",	"Virgin Islands, U.S.",	"Wallis And Futuna",	"Western Sahara",	"Yemen",	"Zambia",	"Zimbabwe"
 
);

// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $countryErr = $phoneErr ="";
$name = $email = $gender = $comment = $website = $phone = "";
$country ="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
 
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}

if (empty($_POST["phone"])) {
$phone = "";
} else {

	
$phone = test_input($_POST["phone"]);
$phone = preg_replace('/\D/', '', $phone);
}
 
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
$country2 = $_POST['country'];
$country3= "select";
if($country2!= $country3)
{
	$country=$country2;
	
	}

else

 {
$country1 = "Please select your country";}
}

 
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
 ?>
 
 
 
 


 
<h2>CONTACT US</h2>
<p><?php 
$s=$_GET['s'];
if($s=='1'){
	Echo('<span class= "success"> Success!! An email has been sent to our web team. Please allow 24 hours for a response.</span>');
	}
else if ($s=='2')
{
	 
 
	Echo('<span class= "fail">Sorry! Please ensure to fill all feilds correctly</span>' );
	}

?>









</p>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  <p>Name:
  <input type="text" name="name" value="<?php echo $name;?>">
  <span class="error">* <?php echo $nameErr1;?></span>
  <br><br>
    E-mail: <input type="text" name="email" value="<?php echo $email;?>">
  <span class="error">* <?php echo $emailErr1;?></span>  </p>
  <p>Phone Number:<input type="text" name="phone" value="<?php echo $phone;?>">
  <span class="error"> <?php echo $phoneErr1;?></span>
  <br>
    <br>
    Country:
    <?php
$item = 'select';
  
echo '<select name="country">';
foreach($country_options as $c)
{
	$sel=''; // Set $sel to empty initially
	$tag = 'selected="selected"';
	
	if(isset($_POST['country']) && $_POST['country'] == $c) // Here we check if the form has been posted so an error isn't thrown and then check it's value against $c
	{ $sel = $tag; }
	elseif(!isset($_POST['country']) && $item == $c) // So that the $item doesn't override the posted value we need to check to make sure the form has NOT been submitted also in the 
	{ $sel = $tag; }	 
	 
	echo '<option value="'.$c.'" '.$sel.'>'.$c.'</option>';
}
echo '</select>';
 
?>
    <span class="error">*<?php echo (isset($country1)) ? $country1 : '';?></span>
    <br><br>
    <!--Website: <input type="text" name="website" value="<?php echo $website;?>">
    <span class="error"><?php echo $websiteErr1;?></span>
    <br><br>-->
    Gender:
    <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
    <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
    <span class="error">* <?php echo $genderErr1;?></span>
    <br><br>
    Comment: 
    <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
    <br>
    
    <?php
          require_once('recaptchalib.php');
          $publickey = "6LdK8_YSAAAAACMvxVRzJ7ZNqjQ9nT_dU6fEZdHx"; // you got this from the signup page
          echo recaptcha_get_html($publickey);
        ?>
    
    <br>
    <input type="submit" name="submit" value="Submit">
  </p>
</form>
 
 
</body>
</html>

need some help of onclick button in php

$
0
0

i have this code which fetch meta tags and title

function file_get_contents_curl($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

$html = file_get_contents_curl("http://example.com/");

//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');

//get and display what you need:
$title = $nodes->item(0)->nodeValue;

$metas = $doc->getElementsByTagName('meta');

for ($i = 0; $i < $metas->length; $i++)
{
    $meta = $metas->item($i);
    if($meta->getAttribute('name') == 'description')
        $description = $meta->getAttribute('content');
    if($meta->getAttribute('name') == 'keywords')
        $keywords = $meta->getAttribute('content');
}

if(!title == ' ')
{
echo ' found a title';
}

in this code you see in last i have if condition (!title==' ') its execute it when i open file

i want its only run when i click the html button like

<input type="button" name="Release" onclick="" value="Click ">

please tell me what i do help me

Changed an else/if but now fails... What did I miss?

$
0
0

Hey Guys,

 

I'm doing some coding and I've managed to snip something off....

 

This is the original code

<form method="post" action="{$systemsslurl}cart.php?a=add&domain=register">

<table class="table table-striped table-framed">
    <thead>
        <tr>
            <th></th>
            <th>{$LANG.domainname}</th>
            <th class="textcenter">{$LANG.domainstatus}</th>
            <th class="textcenter">{$LANG.domainmoreinfo}</th>
        </tr>
    </thead>
    <tbody>
{foreach from=$availabilityresults key=num item=result}
        <tr>
            <td class="textcenter">{if $result.status eq "available"}<input type="checkbox" name="domains[]" value="{$result.domain}" {if $num eq "0" && $available}checked {/if}/><input type="hidden" name="domainsregperiod[{$result.domain}]" value="{$result.period}" />{else}X{/if}</td>
            <td>{$result.domain}</td>
            <td class="textcenter {if $result.status eq "available"}domcheckersuccess{else}domcheckererror{/if}">{if $result.status eq "available"}{$LANG.domainavailable}{else}{$LANG.domainunavailable}{/if}</td>
            <td class="textcenter">{if $result.status eq "unavailable"}<a href="http://{$result.domain}" target="_blank">WWW</a> <a href="#" onclick="popupWindow('whois.php?domain={$result.domain}','whois',650,420);return false">WHOIS</a>{else}<select name="domainsregperiod[{$result.domain}]">{foreach key=period item=regoption from=$result.regoptions}<option value="{$period}">{$period} {$LANG.orderyears} @ {$regoption.register}</option>{/foreach}</select>{/if}</td>
        </tr>
{/foreach}
</table>

<p align="center"><input type="submit" value="{$LANG.ordernowbutton} »" class="btn btn-danger" /></p>

</form>

and I've changed it to:

 <form method="post" action="{$systemsslurl}cart.php?a=add&domain=register">
    {foreach from=$availabilityresults key=num item=result}
    
        {if $result.status eq "available"}
            
            <div style="width: 400px; color: #339933; font-size:14px;"><img src="/templates/dj/yes.jpg" style="float:left" />{$tld}<br />Available</div>
            <div style="width: 100px;" >{$name}<p style="color: #339933;">{$tld}</p></div>
            <div style="width: 200px;" ><select name="domainsregperiod[{$result.domain}]">{foreach key=period item=regoption from=$result.regoptions}<option value="{$period}">{$period} {$LANG.orderyears} @ {$regoption.register}</option>{/foreach}</select>
            <input type="submit" value="{$LANG.ordernowbutton} »" class="btn btn-danger" /></div>
           
            
        {/if}
        
        {if $result.status eq "unavailable"}
            <div style="width: 400px; color: #cc0000; font-size:14px;"><img src="/templates/dj/no.jpg" style="float:left" />{$tld}<br />Taken</div>
            <div style="width: 100px;" >{$domain}<p style="color: #cc0000;">{$tld}</p></div>
            <div style="width: 200px;" ><a href="http://{$result.domain}" target="_blank">WWW</a> <a href="#" onclick="popupWindow('whois.php?domain={$result.domain}','whois',650,420);return false">WHOIS</a></div>
        {/if}
    
    {/foreach}</form>

The original code works fine and add to my cart, the new "updated" version fails...

 

What have I done wrong?

have a script from someone that injects charecters to DB

$
0
0
<?php
/** ************************************************************************************************
  | Software Name        : VideoSwiper plugin
  | Version              : Xtubescript r14.06.30
  | Software Author      : VideoSwiper  Team
  | Website              : http://videoswiper.net
  | E-mail               : support@videoswiper.com
  |**************************************************************************************************
  |
  |**************************************************************************************************
  | Please upload/place the file in the root folder where your script is installed and setup your
  | account at videoswiper.net .
  |**************************************************************************************************
  | Copyright (c) 2009-2013 videoswiper.net. All rights reserved.
  |************************************************************************************************* */

/* Dynamic Config */

$apiUsers = "";

/* No Editing below this line */

define('_NL',"\n");
define('_TIME',time());
if(function_exists('date_default_timezone_set')) {
    date_default_timezone_set('America/New_York');
}
define('_MYSQL_TIME',date('Y-m-d H:i:s',_TIME));
define('VS','http://videoswiper.net/');
define('VSPLUS','http://www.videoswiperplus.com/api2/');

$ffmpeg = '/usr/bin/ffmpeg';
if(!is_file($ffmpeg))$ffmpeg = '/usr/local/bin/ffmpeg';

$flvtool = '/usr/bin/flvtool2';
if(!is_file($flvtool))$flvtool = '/usr/local/bin/flvtool2';

$mp4box = '/usr/bin/MP4Box';
if(!is_file($mp4box))$mp4box = '/usr/local/bin/MP4Box';

$php = '/usr/bin/php';
if(!is_file($php))$php = '/usr/local/bin/php';


class vsmod
{
    var $lastError = false;
    var $lastQuery = false;
    var $dbLink    = false;
    var $post = array();
    var $action = false;
    var $server = false;
    var $database = false;
    var $metaMap = array();

    /* Script specefic settings */

    var $cConfig = "includes/config.php";
    var $cPaths = array();
    var $cDataBase = array('host'=>'host','username'=>'username','password'=>'password','database'=>'database','prefix'=>'','extract'=>'');    
    
    var $cPrefix = '';

    var $cUserField = 'id';
    var $cUserTable = 'users';
    var $cUserConditions = "username = %s AND password = %s";

    var $cCategoryFields = 'id,name';
    var $cCategoryTable = 'categories';
    var $cCategoryConditions = "";

    var $cVideoEmbed = true;
    var $cVideoDownload = true;
    var $cVideoDownloadHD = true;
    /* video common */

    var $cImageTemp = false;
    var $cImageWidth = 160;
    var $cImageHeight = 120;

    var $cVideoField = 'id';
    var $cVideoFile = false;
    var $cVideoFilePath = false;
    var $cMp4File = false;
    var $cMp4FilePath = false;
    var $cMp4Only     = false;
    var $cVideoTable = "videos";
    var $cVideoVarMap = false; //  assc array
    var $cVideoUpdateVarMap = false;
    var $cVideoThumbs = false; // Default thumbs array

    var $cSeprator = '-';

    /* server */

    var $cServerField = 'id';
    var $cServerTable = 'servers';
    var $cServerConditions = "";
    var $cServerVarMap = false;
    var $cServerUpdateVarMap = false;

    /* constructor */

    function vsmod()
    {
        
        // get post variables
        foreach ($_POST as $var=>$val)
        {
            $this->post[$var] = stripslashes($val);
        }

        // Initialize the database

        $this->initDB();
    }

    /** some common functions */

    function path($relativePath)
    {
        if($relativePath[0] == '/') {
            return dirname(__FILE__).$relativePath;            
        }else {
            return dirname(__FILE__).'/'.$relativePath;
        }
        
        return $relativePath;
    }

    function response($payload,$success = true)
    {

        $xmlFormat = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<rsp stat=\"%s\">\n%s\n</rsp>";

        if ($success)
        {
            $response = sprintf($xmlFormat,'ok',$payload);
        }
        else
        {
            $response  = sprintf($xmlFormat,'fail','<err msg="'.$payload.'" detail="'.$this->lastError.'" />');
        }

        header("Content-type: application/xml"); 
       echo $response;
        die();
    }

    function getField($field,$table,$conditions) {

        $result = $this->query("SELECT $field FROM {$this->cPrefix}$table WHERE $conditions");

        $rowCount = mysql_num_rows($result);

        if ($rowCount) {
            $row = mysql_fetch_array($result);
            return $row[$field];
        }

        return false;

    }

    function valReplace($input)
    {
        extract($this->post);

        if (preg_match_all('%{\$([a-zA-Z0-9_.]+)}%',$input,$omatches))
        {
            $matches = array_unique($omatches[1]);

            $replaces = array();
            foreach ($matches as $match)
            {
                $replace = '';
                if(strstr($match,'.'))
                {
                    list($r_array,$r_index) = explode('.',$match);

                    $r_array = $$r_array;
                    $replace = isset($r_array[$r_index])?$r_array[$r_index]:$replace;

                } else {
                    $replace = isset(${$match})?${$match}:$replace;
                }

                $replaces[] = $replace;
            }

            $input = str_replace(array_unique($omatches[0]),$replaces,$input);
        }

        return $input;
    }

    function safeURL($title)
    {
        $title = strtolower($title);
        $title = preg_replace('/[^'.$this->cSeprator.'a-z0-9\s]+/', '', $title);
        $title = preg_replace('/['.$this->cSeprator.'\s]+/', $this->cSeprator, $title);

        return trim($title, $this->cSeprator);
    }

    function safeEncode($string)
    {
        $string = base64_encode($string);
        return str_replace(array('/','+','='),array('_','-',''),$string);
    }

    function safeDecode($string)
    {
    $string = str_replace(array('_','-'),array('/','+'),$string);
    return base64_decode($string);
    }

    function qs($value)
    {
        if (get_magic_quotes_gpc()) {
            $value = stripslashes($value);
        }

        return "'" . mysql_real_escape_string($value) . "'";
    }

    /**
     * Execute a mysql query on established connection
     *
     * @param string $query
     * @return MySql result
     */

    function query($query)
    {
        $this->initDB();
        $this->lastQuery = $query;
        $result = mysql_query($query,$this->dbLink);

        if(!$result){
            $this->response('MySQL Error executing '.$query.' : '.mysql_error(),false);
        }

        return $result;
    }

    function varMap($table,$varMap)
    {
        $qMap = array();

        foreach ($varMap as $var=>$val)
        {
            $qName  =  preg_replace('/[^A-Za-z0-9_]+/', '', $var);
            if($var[0] == '#') {
                $qValue =  $this->qs($this->valReplace($val)); // standard define
            }
            else if($var[0] == '@') {
                $qValue =  $this->valReplace($val);
            }
            else {
                $qValue =  $this->qs($this->post[$val]);
            }
            $qMap[$qName] = $qValue;
        }

       $result = $this->query("SHOW COLUMNS FROM ".$table);

       $this->metaMap = $nTable = array();
       
       while ($row = mysql_fetch_assoc($result))
       {
           $this->metaMap[$row['Field']] = 1;
           if(isset($qMap[$row['Field']]))
           {
               $nTable['`'.$row['Field'].'`'] = $qMap[$row['Field']];
           }
        }

        return $nTable;


    }

    function queryCreate($table,$varMap)
    {

        $qMap = $this->varMap($this->cPrefix.$table,$varMap);

        $qNames  = implode(',',  array_keys($qMap));
        $qValues = implode(',',  array_values($qMap));

        $sql = "INSERT INTO {$this->cPrefix}$table ($qNames) VALUES ($qValues)";

        return $this->query($sql);

    }
    
    function queryUpdate($table,$varMap,$conditions)
    {
        $qMap = $this->varMap($this->cPrefix.$table,$varMap);

        $setArray = array();
        foreach ($qMap as $var=>$val)
        {
            $setArray[] = $var."=".$val;
        }

        $setString = implode(',',$setArray);

        $sql = "UPDATE {$this->cPrefix}$table SET $setString WHERE $conditions";

        return $this->query($sql);
    }

    function getMultiDownload($url, $filename, $size) {
    
        $threads = intval($this->post['threads']);
        $splits = range(0, $size, round($size / $threads));
        $megaconnect = curl_multi_init();
        $partnames = array();
        for ($i = 0; $i < sizeof($splits); $i++) {
            $ch[$i] = curl_init();
            curl_setopt($ch[$i], CURLOPT_URL, $url);
            curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, 0);
            curl_setopt($ch[$i], CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch[$i], CURLOPT_VERBOSE, 1);
            curl_setopt($ch[$i], CURLOPT_BINARYTRANSFER, 1);
            curl_setopt($ch[$i], CURLOPT_FRESH_CONNECT, 0);
            curl_setopt($ch[$i], CURLOPT_CONNECTTIMEOUT, 10);
            $partnames[$i] = $filename . '_' . $i;
            $bh[$i] = fopen( $partnames[$i], 'w+');
            curl_setopt($ch[$i], CURLOPT_FILE, $bh[$i]);
            $x = ($i == 0 ? 0 : $splits[$i] + 1);
            $y = ($i == sizeof($splits) - 1 ? $size : $splits[$i + 1]);
            $range = $x . '-' . $y;
            curl_setopt($ch[$i], CURLOPT_RANGE, $range);
            curl_setopt($ch[$i], CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
            curl_multi_add_handle($megaconnect, $ch[$i]);
        }
    
        $active = null;
    
        do {
            $mrc = curl_multi_exec($megaconnect, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    
        while ($active && $mrc == CURLM_OK) {
            if (curl_multi_select($megaconnect) != -1) {
                do {
                    $mrc = curl_multi_exec($megaconnect, $active);
                } while ($mrc == CURLM_CALL_MULTI_PERFORM);
            }
        }
        
        for ($i = 0; $i < sizeof($splits); $i++) {
            curl_multi_remove_handle($megaconnect, $ch[$i]);            
            curl_close($ch[$i]);
        }
        curl_multi_close($megaconnect);
        
        $final = fopen($filename, "w+");
        for ($i = 0; $i < sizeof($splits); $i++) {
            fseek($bh[$i], 0, SEEK_SET);
            while(!feof($bh[$i])) {
                $contents = fread($bh[$i], 1024*1024);
                if(!$contents) break;
                fwrite($final,$contents);
            }            
            fclose($bh[$i]);
            unlink($partnames[$i]);
        }
        fclose($final);
        
        return true;
    }


    function getRemoteFileSize($url,$resume=false) {

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    
        $head = curl_exec($ch);
        curl_close($ch);

        $regex = '/Content-Length:\s([0-9].+?)\s/';
        $count = preg_match($regex, $head, $matches);
        
        if($resume) {
            if(strstr($head,'Accept-Ranges') < 0) {
                return 0;
            }
        }
    
        return isset($matches[1]) ? $matches[1] : "0";
    }

    function getRemoteFile($url,$filename = false,$params = false,$cookie = false,$precheck = false)
    {

        if (!$precheck && $filename && intval($this->post['threads']) > 1) {
    
            $size = $this->getRemoteFileSize($url,true);
    
            if ($size > 1024*500 ) { // only greater than 500 kb files 
                // check download resume supported 
                if($this->getMultiDownload($url, $filename, $size)) {
                    if(filesize($filename)>1024) {
                        return true;
                    }
                }
            }
        }
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);

        if ($params) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, base64_decode($params));
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: ')); // lighttpd fix
        }

        if ($cookie)
        {
            curl_setopt($ch, CURLOPT_COOKIE,base64_decode($cookie));
        }
        else {
            if(preg_match('/([a-z0-9]+)\.com/',$url,$match))
            {
                /*$name = $match[1];
                $cookieFile = $this->path($this->valReplace($this->cVideoFile));
                $cookieFile = dirname($cookieFile).'/'.$name.'.cookie';
                curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
                curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
                 */
            }
        }
        
        curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
            
        if ($filename) {

            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_MAXREDIRS, 5);

            if($precheck)curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Timeout

            $fp = fopen($filename, 'wb');
            if (!$fp)
            {
                $lastError = "Could not open $filename for writing";
                curl_close($ch);
                return false;
            }
            curl_setopt($ch, CURLOPT_FILE, $fp);
            curl_exec($ch);
            $data = true;
        }
        else
        {
            curl_setopt($ch, CURLOPT_HEADER, 1);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            $data = curl_exec($ch);
        }

        $error = curl_error($ch);

        curl_close($ch);

        if (!empty($error) && !($precheck && strstr($error,'timed out')))
        {
            if(preg_match('/([A-Za-z0-9]{4}:[A-Za-z0-9]{4}:[A-Za-z0-9]{4}:)/',$error)) { // ipv6 hack
                 return $data;
            }
            $this->lastError = $error;
            $this->response('Curl Error downloading '.$url,false);
        }
        
        

        return $data;
    }

    function resizeImage($sourceImage,$targetImage,$width,$height)
    {
        //ini_set('gd.jpeg_ignore_warning', 1); ( for black thumbnails in embedding )
        $srcImg = imagecreatefromjpeg($sourceImage);
        $tmpImg = imagecreatetruecolor($width,$height);
        list($widthOrig, $heightOrig) = getimagesize($sourceImage);

        imagecopyresampled($tmpImg,$srcImg,0,0,0,0,$width,$height,$widthOrig,$heightOrig);
        imagedestroy($srcImg); 
        
        imagejpeg($tmpImg,$targetImage,100);           
        imagedestroy($tmpImg);
    }

    /**
     * Initalize Database with new link
     *
     */

    function initDB($config = false)
    {
        if (!$this->database) {
            if (!$config) {
                $configFile = $this->path($this->cConfig);

                if (!is_file($configFile)) {
                    $this->response('Could not find database config file', false);
                }

                include $configFile;
            } else {
                extract($config);
            }

            if (isset($this->cDataBase['extract'])) {
                extract(${$this->cDataBase['extract']});
            }
            // New link due to time out issue

            $this->database['host']     = ${$this->cDataBase['host']};
            $this->database['username'] = ${$this->cDataBase['username']};
            $this->database['password'] = ${$this->cDataBase['password']};
            $this->database['database'] = ${$this->cDataBase['database']};
            @$this->database['prefix']   = ${$this->cDataBase['prefix']};

        } 
        
        $this->dbLink = mysql_connect($this->database['host'],$this->database['username'],$this->database['password'],true);
        
        if (!$this->dbLink)
        {
            $this->response('Could not connect to database : '.mysql_error(),false);
        }


        $result = mysql_select_db($this->database['database'], $this->dbLink);

        if (!$result) {
            $this->response('Cant use '.$this->database['database'].' : '.mysql_error(),false);
        }

        if(function_exists('mysql_set_charset')) mysql_set_charset("utf8",$this->dbLink);
        else  mysql_query ('SET NAMES utf8',  $this->dbLink);


        if(isset($this->cDataBase['prefix']))
        {
            $this->cPrefix = $this->database['prefix'];
        }

    }

    /**
     * Check CURL its required for download and Getting Thumbnails
     */

    function checkCurl()
    {
        if (!function_exists('curl_init'))
        {
            $this->response('CURL was not found on the server, please enable it',false);
        }
    }

    /**
     *  Checks video swiper plus connectivity
     */

    function checkAPI()
    {
        if(!$this->cVideoDownload) return;

        $scriptURL = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
        $response = $this->getRemoteFile(VSPLUS.'sync/'.$this->safeEncode($scriptURL));

        if (!strstr($response,'stat="ok"'))
        {
            if (preg_match('%err msg="(.*?)"%',$response,$matches))
            {
                $this->lastError = $matches[1];
            }
            $this->response('Videoswiper API connectivity check Failed',false);
        }
    }

    /**
     * Check Weather required path can be written
     *
     */

    function checkPaths()
    {
        foreach ($this->cPaths as $path)
        {
            if (!is_writable($path))
            {
                $this->response($path." is not writable, Please make it writable",false);
            }
        }
    }

    /**
     * Check if Open Base Dir is  on
     *
     */

    function checkOpenBaseDir() {
        $val = ini_get('open_basedir');

        if(!empty($val)) {
            $this->response('Server has open_basedir enabled, please disable it',false);
        }
    }

    /**
     * Returns password hash based on script , override for advanced password generation
     *
     */

    function password()
    {
        return md5($this->post['password']);
    }

    /**
     * Check if valid username is using the script
     *
     */

    function checkLogin()
    {
        global $apiUsers;

        $usersAllowed = empty($apiUsers)?false:explode(',',$apiUsers);

        // is he allowed to use this ?
        if ($usersAllowed && !in_array($this->post['username'],$usersAllowed))
        {
            $this->response('EC101 : This username is not allowed to use this script.',false);
        }

        $username = $this->qs($this->post['username']);
        $password = $this->qs($this->password());

        $conditions = sprintf($this->cUserConditions,$username,$password);

        $this->userId = $this->getField($this->cUserField,$this->cUserTable,$conditions);
        $this->post['uid'] = $this->userId;

        if (!$this->userId)
        {
            $this->response("EC102 : Could not validate username and password",false);
        }

        error_reporting(E_ALL);
        ini_set('display_errors',true);
    }

    function checkGD() {
        if(!function_exists('imagecreatefromjpeg')) {
            $this->response('Server does not have GD Enabled,Please ask host to enable it.',false);
        }
    }
    /**
     * Check All Default action
     *
     */

    function checkAll()
    {
        $this->checkCurl();
        $this->checkPaths();
        
        if($this->cVideoDownload) {
            // for downloads only 
            $this->checkOpenBaseDir();
        }
        
        $this->checkAPI();
        $this->checkGD();
        

        $this->response("All checks were successfull for Xtubescript r14.06.30 .");
    }

    /**
     * This is used to make user site as our gateway
     *
     */

    function forward()
    {
        $params = false;
        $cookie = false;
        
        if (isset($this->post['params']))
        {
            $params = $this->post['params'];
        }

        if (isset($this->post['cookie']))
        {
            $cookie = $this->post['cookie'];
        }

        $url = $this->post['url'];

        if(!strstr($url,'http://'))
        {
            $url = $this->safeDecode($url);
        }

        echo $this->getRemoteFile($url,false,$params,$cookie);
    }

    /**
     * Get Categories from user site
     *
     */

    function getInfo()
    {

        list($id,$name) = explode(',',$this->cCategoryFields);

        $where = (empty ($this->cCategoryConditions)?'':' WHERE '.$this->cCategoryConditions);

        $result = $this->query("SELECT ".$this->cCategoryFields." FROM ".$this->cPrefix.$this->cCategoryTable." $where ORDER BY ".$name." ASC");

        $rowCount = mysql_num_rows($result);

        if ($rowCount)
        {
            $categories = "";

            while ($row = mysql_fetch_array($result)) {
                $categories.= '<category id="'.$row[$id].'">'.$row[$name].'</category>'._NL;
            }

            // Supported types

            $actions = "";

            if ($this->cVideoEmbed) {
                $actions .= '<action>embed</action>';
            }
            if ($this->cVideoDownload) {
                $actions .= '<action>download</action>';
                if ($this->cVideoDownloadHD) {
                    $actions .= '<action>downloadhd</action>';
                }
            }
            

            $response = '<categories>'._NL.$categories.'</categories>';
            $response .= _NL.'<actions>'.$actions.'</actions>';

            $this->response($response);

        }

        $this->response('E103 : Could not find any categories.',false);

    }

    /**
    * Viedo Handling functions
    */

    function initPost()
    {

        static $time = _TIME;

        // database stuff

        $this->post['time']        = $time;
        $this->post['mysql_time']  = date('Y-m-d H:i:s',$time);
        $this->post['mysql_date']  = date('Y-m-d',$time);

        $this->post['alias']       = $this->safeURL($this->post['title']);

        $this->post['duration_ms'] = sprintf('%02d:%02d',$this->post['duration']/60,$this->post['duration']%60);
        $this->post['duration_hms'] = sprintf('%02d:%02d:%02d',$this->post['duration']/3600,$this->post['duration']/60,$this->post['duration']%60);

        $this->post['key']         = substr(md5($time.$this->post['title']),0,20);
        $this->post['skey']        = substr(md5($time.$this->post['title']),0,10);

    }

    function getThumbnails() {
        
        global $ffmpeg;

        $videoFilePath = $this->path($this->valReplace($this->cVideoFile));

            $index = 1;
            $interval = $this->post['duration']/(count($this->cVideoThumbs)+1);


            if(is_file($ffmpeg)) {
            // init ffmpeg
            } else if (extension_loaded('ffmpeg'))
            {
                // init ffmpeg
                $handle = new ffmpeg_movie($videoFilePath);
            } else {
                // init normal
            }


            foreach ($this->cVideoThumbs as $thumb) {
            extract($thumb);
            if (!isset($thumb['width']))
                $width = $this->cImageWidth;
            if (!isset($thumb['height']))
                $height = $this->cImageHeight;
            $thumbPath = $this->path($this->valReplace($path));
            $thumbtime = intval($interval * $index);

            if (is_file($ffmpeg) && is_file($videoFilePath)) {
                exec("$ffmpeg -i {$videoFilePath} -f image2  -ss $thumbtime -s {$width}x{$height} -vframes 1 -an -y $thumbPath");
            } else {

                if (!isset($firstImage))
                    $firstImage = $thumbPath;

                if (!is_file($firstImage)) {
                    if (!$this->getRemoteFile($this->post['thumbnail'], $firstImage)) {
                        $this->response('EC121 : Could not download thumbnail.', false);
                    }
                    $this->resizeImage($firstImage, $thumbPath, $width, $height);
                } else {
                    $this->resizeImage($firstImage, $thumbPath, $width, $height);
                }
            }
            $index++;
        }
        
        if(is_file($this->cImageTemp)) {
            unlink($this->cImageTemp);
        }

    }

    function getDuration() {
        global $ffmpeg;

        $videoFilePath = $this->path($this->valReplace($this->cVideoFile));

        if ($this->post['duration'] == 0) {
            if(is_file($ffmpeg)) {
                ob_start();
                passthru("$ffmpeg -i {$videoFilePath} 2>&1");
                $duration = ob_get_contents();
                ob_end_clean();


                if(preg_match('/Duration: (.*?),/', $duration, $matches, PREG_OFFSET_CAPTURE, 3)) {
                    $this->post['duration'] = $matches[1][0];
                }

            }

        }

    }



    function downloadVideo($precheck = false) {

        global $ffmpeg,$flvtool,$mp4box;

        $videoPath = $this->path($this->valReplace($this->cVideoFile));
        $this->cVideoFilePath = $videoPath;

        $scriptURL = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

        if (!isset($this->post['downloadURL'])) {

            // get download URL
            $downloadAPIURL = VSPLUS . 'get/' . $this->post['token'] . '/' . $this->safeEncode($this->post['permalink']) . '/' . $this->safeEncode($scriptURL . '|' . $this->post['username'] . '|' . $this->post['password']);
            // if ! flv file do something
            $response = $this->getRemoteFile($downloadAPIURL);


            if (preg_match('%err msg="(.*?)"%', $response, $matches)) {
                $this->lastError = $matches[1];
            }

            if (!$response || empty($response) || strstr($response, 'stat="Fail"')) {
                $this->response('EC111 : Could not get download URL using API.', false);
            }
        }


        if (isset($this->post['downloadURL']) || preg_match('%<download>(.*?)</download>%', $response, $match)) {
            if (!isset($this->post['downloadURL'])
                )$this->post['downloadURL'] = $match[1];

            set_time_limit(0); // can take long

            @unlink($videoPath);
            if (!$this->getRemoteFile($this->post['downloadURL'], $videoPath, false, false, $precheck)) {
                $this->response('EC112 : Could not download video file.', false);
            }

            // get size
            static $rsize = 0;

            if (!isset($this->post['size'])) {
                $rsize = $this->getremoteFileSize($this->post['downloadURL']);
            }

            // automatic mp4 conversion


            $fp = fopen($videoPath, "r");
            if (!$fp) {
                $this->response('EC113 : Could not open downloaded video file.', false);
            }
            $header = fread($fp, 3);
            fclose($fp);

            if ($header != 'FLV') {
                // Convert Video mp4 to flv
                //ffmpeg -i input.mov -ar 22050 -qscale .1 output.flv
                if ($this->cMp4File) {
                    $outPath = $this->cMp4FilePath = $this->path($this->valReplace($this->cMp4File));
                    copy($videoPath, $this->cMp4FilePath);                    
                    if(is_file($mp4box))
                    {
                        exec("$mp4box -inter 500 {$outPath} 2>&1",$return);
                    }
                }

                if (!$precheck) {
                    if (is_file($ffmpeg) && !$this->cMp4Only) {
                        $tempPath = "{$videoPath}.tmp.flv";
                        exec("$ffmpeg -i {$videoPath} -vcodec copy -acodec copy {$tempPath} 2>&1", $return);
                        if (is_file($tempPath) && (filesize($tempPath) > 1024)) {
                            copy($tempPath, $videoPath);
                            $this->cVideoFilePath = $videoPath;
                            unlink($tempPath);

                            if(is_file($flvtool))
                            {
                                exec("$flvtool -U {$videoPath} 2>&1",$return);
                            }

                        } else {
                            echo implode("\n", $return);
                        }
                    }
                }
            } 
            else {
                // Insert Meta in FLV if required
                if(is_file($flvtool))
                {
                    exec("$ffmpeg -i {$videoPath} {$videoPath}.out.flv");
                    unlink($videoPath);
                    rename("{$videoPath}.out.flv",$videoPath);
                    exec("$flvtool -U {$videoPath} 2>&1",$return);
                }
                
                // if flv file and mp4 is required 
                
                if($this->cMp4File && !$precheck) {
                    
                    if (is_file($ffmpeg)) {
                        $outPath = $this->cMp4FilePath = $this->path($this->valReplace($this->cMp4File));
                        //-vcodec libx264 -vpre lossless_medium -threads 0 -r 25 -g 50 -crf 28 -me_method hex -trellis 0 -bf 8 -acodec libfaac -ar 44100 -ab 128k -f mp4
                        exec("$ffmpeg -i {$videoPath} -vcodec libx264 -vpre lossless_medium -threads 0 -r 25 -g 50 -crf 28 -me_method hex -trellis 0 -bf 8  -acodec libfaac -ar 22050 {$outPath} 2>&1", $return);

                        if (is_file($mp4box)) {
                            exec("$mp4box -inter 500 {$outPath} 2>&1", $return);
                        }
                    }
                }
                
                
            }
            $size = filesize($videoPath);

            if ($rsize > $size) {
                $size = $rsize;
            }

            $this->post['size'] = $size;
            $this->post['size_kb'] = sprintf("%.2f", $size / (1024));
            $this->post['size_KB'] = sprintf("%.2f KB", $size / (1024));
            $size /= 1024;
            $this->post['size_mb'] = sprintf("%.2f", $size / (1024));
            $this->post['size_MB'] = sprintf("%.2f MB", $size / (1024));
            
            $size = filesize($videoPath);
            
            if($size < 1024) {
              $this->response('EC115 : Download file size is 0. ['.$this->post['downloadURL'].']',false);
            }
            // get Video Duration

            $this->getDuration();

            return;
        }

        $this->response('EC114 : No download link in API response.', false);
    }

    function uploadVideo()
    {
        $s = $this->server;

        $conn = ftp_connect($s['hostname']);
        if(!$conn)
        {
            $this->response('EC151 : Could not connect to '.$s['hostname'],false);
        }

        $result = ftp_login($conn, $s['username'], $s['password']);
        if(!$result)
        {
            $this->response('EC152 : Could not login to '.$s['hostname'],false);
        }

        // creat anyway
        ftp_mkdir($conn,$s['path']);

        $localFile  = $this->path($this->valReplace($this->cVideoFile));

        $remoteFile = $s['path'].($s['path'][strlen($s['path'])-1]=='/'?'':'/').basename($localFile);

        $result = ftp_put($conn,$remoteFile,$localFile,FTP_BINARY);
        if(!$result)
        {
            $this->response('EC153 : Could not upload '.$localFile.' to '.$remoteFile.' on '.$s['hostname'],false);
        }

        if($this->cMp4File && $this->cMp4FilePath)
        {
            $localFile  = $this->path($this->valReplace($this->cMp4File));

            $remoteFile = $s['path'].($s['path'][strlen($s['path'])-1]=='/'?'':'/').basename($localFile);

            $result = ftp_put($conn,$remoteFile,$localFile,FTP_BINARY);
            if(!$result)
            {
                $this->response('EC154 : Could not upload '.$localFile.' to '.$remoteFile.' on '.$s['hostname'],false);
            }
        }

        ftp_close($conn);

        unlink($localFile);

    }
    
    function getServer()
    {
        if(!$this->cServerVarMap) return false;
        $where = (empty ($this->cServerConditions)?'':' WHERE '.$this->cServerConditions);
 
        $result = $this->query("SELECT * FROM ".$this->cPrefix.$this->cServerTable.$where);

        $rowCount = mysql_num_rows($result);

        if ($rowCount)
        {
            $row = mysql_fetch_assoc($result);

            $m = $this->cServerVarMap;
            $this->server['id'] = $row[$m['id']];
            $this->server['hostname'] = $row[$m['hostname']];
            $this->server['username'] = $row[$m['username']];
            $this->server['password'] = $row[$m['password']];
            $this->server['path']     = $row[$m['path']];
            $this->server['url']      = $row[$m['url']];

            $this->post['server_id']   = $row[$m['id']];
            $this->post['server_path'] = $row[$m['path']];
            $this->post['server_url']  = $row[$m['url']];

            return true;
        }

        return false;
    }



    /**
    * Embed
    */

    function embed()
    {
        $this->initPost();

        $this->getThumbnails();

        $result = $this->queryCreate($this->cVideoTable,$this->cVideoVarMap);
        $this->post['id'] = mysql_insert_id();
        return $result;
    }


    /**
    * Download
    */

    function download()
    {
    	 $this->initPost();

    	 // Precheck  ( video file + size + duration )
    	 $this->downloadVideo(true);

    	 $this->getThumbnails();

    	 $this->queryCreate($this->cVideoTable,$this->cVideoVarMap);
         $this->post['id'] = mysql_insert_id();
         
    	 $this->downloadVideo();

    	 $this->getThumbnails();

         if($this->getServer())
         {
             $this->uploadVideo();
             $this->queryUpdate($this->cVideoTable,$this->cServerUpdateVarMap,$this->cVideoField. ' = '.$this->post['id']);
         }

         if($this->cVideoUpdateVarMap)
         $this->queryUpdate($this->cVideoTable,$this->cVideoUpdateVarMap,$this->cVideoField. ' = '.$this->post['id']);

         if($this->cMp4Only) {
             unlink($this->cVideoFilePath);
         }
    }

    /**
     * The main executing function
     *
     */

    function dispatch()
    {

        if (is_array($_POST) && count($_POST) && ($_POST['action']!='sync') ) {
            $this->checkLogin();
            
                if (isset($this->post['secure'])) {
                $result = $this->getRemoteFile(VS . 'cart/item/' . $this->post['secure']);
                // match 
                if (preg_match('/\[\[(.*?)\]\]/', $result, $reqMatch)) {
                    $reqArray = unserialize(base64_decode($reqMatch[1]));
                    foreach ($reqArray as $var => $val) {
                        $this->post[$var] = $val;
                    }
                } else {
                    $this->response('EC117 : Invalid response from server.', false);
                }
            }            
        } 

        $action = (isset($_POST['action']))?$_POST['action']:'default';
        $this->action = $action;
    
        switch ($action) {

            case 'login':
                break;

            case 'info':
                $this->getInfo();
                break;

            case 'embed':
                $this->embed();
                break;


            case 'downloadhd':
            case 'download':
                $this->download();
                break;
            
            case 'stream':
                $this->post['url'] = base64_decode($this->post['u']);
            case 'forward':
                $this->forward();
                break;

            case 'sync':
                $this->response("");
                break;

            default:
                $this->checkAll();
                break;
        }


        $response = "[$action]";

        if(isset($this->post['size']) && $this->post['size'] > 0 ) {
            $response .= sprintf("[size:%d]",$this->post['size']);            
        } 
        
        $this->response($response);
        

    }

}
?><?php

class xtubescript extends vsmod {

    var $cConfig = "includes/settings.inc";
    var $cPaths = array('uploads/thumbs');
    var $cDataBase = array('host' => 'DBHOST', 'username' => 'DBUSER', 'password' => 'DBPASS', 'database' => 'DBNAME', 'prefix' => '');
    var $cPrefix = '';
    var $cUserTable = 'member';
    var $cUserField = 'id';
    var $cUserConditions = "username = %s AND password = %s";
    var $cCategoryTable = 'category';
    var $cCategoryFields = 'id,name';

    function initDB($config = false) {
        
        $config_file = file_get_contents($this->cConfig);

        preg_match('/\$db_host[\s]+=[\s]+(?:\'|")(.[^"\']*?)(?:\'|")/s', $config_file, $DBHOST);
        preg_match('/\$db_user[\s]+=[\s]+(?:\'|")(.[^"\']*?)(?:\'|")/s', $config_file, $DBUSER);
        preg_match('/\$db_password[\s]+=[\s]+(?:\'|")(.[^"\']*?)(?:\'|")/s', $config_file, $DBPASSWORD);
        preg_match('/\$db_database[\s]+=[\s]+(?:\'|")(.[^"\']*?)(?:\'|")/s', $config_file, $DBNAME);
        $config = array();
        $config['DBHOST'] = $DBHOST[1];
        $config['DBUSER'] = $DBUSER[1];
        $config['DBPASS'] = $DBPASSWORD[1];
        $config['DBNAME'] = $DBNAME[1];        
        parent::initDB($config);
        $this->cPrefix = "";
    }

    /* video common */

    var $cImageTemp = 'uploads/thumbs/temp.jpg';
    var $cVideoFile = 'uploads/vids/{$skey}/{$skey}.flv';
    var $cMp4File = 'uploads/vids/{$skey}/{$skey}.mp4';
    var $cVideoTable = "media";
    var $cVideoField = 'id';
    
    var $cVideoVarMap = array('title'=>'title',
        'category' => 'category_id',
        'description' => 'description',
        'tags' => 'tags',
        'fileid' => 'skey',
        'poster' => 'username',
        'added' => 'time',
        '#status' => 'true',
        'allviews' => 'views',
        'lastviwed' => 'time',
        'duration' => 'duration_ms',
        '#mainthumb' => '1'
        );
    

    var $cVideoThumbs = array(array('path' => 'uploads/thumbs/{$skey}/1.jpg', 'width' => 180, 'height' => 136));

    function password() {
        return sha1($this->post['password']);
    }

    function embed() {        
        $this->initPost();        
       
        $this->cVideoVarMap['#mediatype'] = 'embed';
        $this->cVideoVarMap['embed'] = 'embed';
        
        mkdir('uploads/thumbs/'.$this->post['skey'],0777);
        parent::embed();    
    }

    function download() {
        
        $this->initPost();       
        
       $this->cVideoVarMap['#mediatype'] = 'video';
       $this->cVideoVarMap['#mobile'] = '1';
       $this->cVideoVarMap['#hd'] = '1';        
        
       $this->cVideoThumbs = array(); 
        
        $thumbCount = $this->getField('value','setting','setting="thumbsnumber"');
        
        for($i=1;$i<=$thumbCount;$i++) {
            $this->cVideoThumbs[] = array('path' => 'uploads/thumbs/{$skey}/'.$i.'.jpg', 'width' => 180, 'height' => 136);
        }
        
        mkdir('uploads/thumbs/'.$this->post['skey'],0777);
        mkdir('uploads/vids/'.$this->post['skey'],0777);
        
        parent::download();
        
        // create mobile video 
        
        global $ffmpeg;
        $outputFile = $this->valReplace('uploads/vids/{$skey}/mob_{$skey}.mp4');
        $cmd = $ffmpeg . ' -i ' . $this->cVideoFilePath . ' -acodec libfaac -ab 44100 -vcodec mpeg4 -b 250k -s 320x240 -y ' . $outputFile;
        exec($cmd . ' 2>&1', $return);
        
    }

}

$object = new xtubescript();

$object->dispatch();

hi I have a plugin script from videoswiper they basically download videos to my site and then add them to my database the problem is when they add the data it does not strip characters from the data so when it adds the video it needs to strip the characters from the title of the video otherwise it kills my database and the video wont play if I go in my phpmyadmin and remove the characters all is well from what I have read it seems this is also a big security issue if someone can look at this plugin and help fix this

translation

$
0
0
Hey guys I'm after a English to Arabic translation script...although I have Googled it but as you can imagine there's no script of that.

Would I have to create a array of English words and then give them the value in Arabic? :/...just wondering if I have any other options...thank you

creating a XML file from MYSQL with PHP

$
0
0

I have the code below , and when I run it on my website , it returns a XML Parsing Error: not well-formed error , which says it has a problem reading the & i think

 

please see http://www.jamesflowersreports.com/php/xml2.php

 

I think it has something to wiht the str_replace as when I change the $row['customerName'] . "</Name>\n"; to $row['customerNumber'] . "</Name>\n"; as a test it works fine , I understand XML cant handle special characters , how would prevent this happening?

 

code as below

 

 

 

$query = "SELECT * FROM customers";
$resultID = mysql_query($query, $linkID) or die("Data not found.");

$xml_output = "<?xml version=\"1.0\"?>\n";
$xml_output .= "<entries>\n";

for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
    $row = mysql_fetch_assoc($resultID);
    $xml_output .= "\t<entry>\n";
    $xml_output .= "\t\t<Name>" . $row['customerName'] . "</Name>\n";
        // Escaping illegal characters
        $row['text'] = str_replace("&", "&", $row['text']);
        $row['text'] = str_replace("<", "&lt", $row['text']);
        $row['text'] = str_replace(">", ">", $row['text']);
        $row['text'] = str_replace("\"", """, $row['text']);
    $xml_output.= "\t\t<Number>" . $row['customerNumber'] . "</Number>\n";
    $xml_output.= "\t</entry>\n";
}

$xml_output .= "</entries>";

echo $xml_output;

 

 

regards

 

James

modification of contact form

$
0
0
I am currently trying to build a contact form for a website. I have been given a script to use that was used on another site but it has an iff statement in it to change the strEmail according to the location and requirement. 
 
I would like to remove this as the form no longer has location or requirement and just have it post to a single email address. Below is the process php for the form.
 
I only have name, surname, phone, email and comment on this new form so nothing else is needed. I also have to remove the insert into database. 
 
any help would be appreciated! 
 
thank you
 
<?php
//THIS NEEDS TO BE AT THE TOP OF THE PAGE, BEFORE ANY HTML IS OUTPUT TO CLIENT
$strMessage = "";

if ($_SERVER['REMOTE_ADDR'] == "5.71.114.48") {
    error_reporting(E_ALL ^ E_NOTICE);
    ini_set("display_errors", 1);
}

//Only action if the form has been submitted
if(isset($_POST['submit-generic'])) {
    //Validate the fields again, because not everyone has Javascript, including bots
    if (isset($_POST['location']) && $_POST['location'] !== "" &&
        isset($_POST['requirement']) && $_POST['requirement'] !== "" &&
        isset($_POST['name']) && $_POST['name'] !== "" &&
        isset($_POST['surname']) && $_POST['surname'] !== "" &&
        isset($_POST['email']) && $_POST['email'] !== "" &&
	    $_POST['surname'] !== $_POST['name']) {

        switch ($_POST['location']) {
            case 'United States':
                $strEmail = "EMAIL-HERE"; break;
 
        }

        //Open DB
        $db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
        if (mysqli_connect_error()) $db = false;

        //Prepare statement
        if ($db) {
            $insertStmt = $db->prepare("INSERT INTO enquiries (EnquiryType, EnquiryEmail, EnquiryFirstName, EnquiryLastName, EnquiryPhone, EnquiryCompany, EnquiryPosition, EnquiryRequirement, EnquiryMessage, EnquiryLocationOfInterest, EnquiryDateTime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW());");
            $insertStmt->bind_param('ssssssssss', $type, $email, $firstName, $lastName, $phone, $company, $position, $requirement, $enquiry, $officeOfInterest);
        }

        //Sanitize data
        $type = "contact-form";
        $firstName = $_POST['name'];
        $lastName = $_POST['surname'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $company = $_POST['company'];
        $position = $_POST['position'];
        if ($_POST['requirement'] == "Other") {
            $requirement = $_POST['other-requirement'];
        } else {
            $requirement = $_POST['requirement'];
        }
        $enquiry = $_POST['comment'];
if ($_POST['location'] == "Other") {
            $officeOfInterest = $_POST['other-location'];
        } else {
            $officeOfInterest = $_POST['location'];
        }
        //Insert Data to DB
        if ($db) {
            $insertStmt->execute();
            $insertStmt->close();
            $db->close();
        }


        //Send to client
        $strFrom = "EMAIL HERE";
        $strTo = $strEmail;
        $strSubject = "New contact on from " . $_POST['name'] . " " . $_POST['surname'];
        $strBody = '
            <html>
                <body>
                    <h1>New contact form</h1>
                    <p>Information on form was:</p>
                    <p><strong>Name</strong>: '.$_POST['name'].'</p>
                    <p><strong>Surname</strong>: '.$_POST['surname'].'</p>
                    <p><strong>Email</strong>: '.$_POST['email'].'</p>
                    <p><strong>Phone</strong>: '.$_POST['phone'].'</p>
                    <p><strong>Company</strong>: '.$_POST['company'].'</p>
                    <p><strong>Position</strong>: '.$_POST['position'].'</p>
                    <p><strong>Location</strong>: '.$_POST['location'].'</p>
                    <p><strong>Other Location</strong>: '.$_POST['location-other'].'</p>
                    <p><strong>Requirement</strong>: '.$_POST['requirement'].'</p>
					<p><strong>Other</strong>: '.$_POST['other-requirement'].'</p>
                    <p><strong>Enquiry</strong>: '.$_POST['comment'].'</p>
                </body>
            </html>
        ';

        $strHeaders = 'From: '.$strFrom."\r\n".
        'Reply-To: '.$strFrom."\r\n" .
        'X-Mailer: PHP/' . phpversion() . "\r\n".
        'MIME-Version: 1.0' . "\r\n" .
        'Content-type: text/html; charset=UTF-8' . "\r\n";
        mail($strEmail, $strSubject, $strBody, $strHeaders);

        //Send confirmation to customer
        $strFrom = "EMAIL HERE";
        $strTo = $_POST['email'];
        $strSubject = "Thank you for contacting";
        $strBody = "Thanks for getting in touch. Your message has been received and will be processed as soon as possible.";

        $strHeaders = 'From: '.$strFrom."\r\n".
        'Reply-To: '.$strFrom."\r\n" .
        'X-Mailer: PHP/' . phpversion();
        mail($strTo, $strSubject, $strBody, $strHeaders);

        //Finally redirect
        header('Location: /contact-us/thank-you?contactlocation='.$_POST['location'].'?requirement='.$requirement) ;
        exit();
    } else {

		//Finally redirect
        header('Location: '.$_SERVER['REQUEST_URI']. '?message=Please complete the required fields.') ;
        exit();
    }
}

?>

Creating Dynamic Variables From MySQL

$
0
0

Hi there,

 

I have a table in a MySQL database where I keep a list of user privileges. I am trying to create variables where the name of variable matches the privileges in the table.

 

This is also known as variable variables (I think).

 

EDIT (17/07/2014 04:02 PM): This might be a better way to describe what I'd like, so if the value from the table is admin_panel I'd like to dynamically create a variable with that name.

 

I have created a code so far, but all I seem to be getting is a list of Notice errors telling me that the variable is undefined. (I have supplied a list of errors a bit further down the post).

 

Here is the code:

<?php
$host = "localhost";
$account = "***";
$password = "****";
$dbname = "****";

$connect = mysql_connect($host,$account,$password) or die("Unable To Connect");
$db = mysql_select_db($dbname,$connect) or die("Unable To Select DB");

$perm_query = "SELECT * FROM `privileges`";
$permission_query = mysql_query($perm_query);

while($row = mysql_fetch_array($permission_query))
{
$rows[] = $row;
}

foreach($rows as $row)
{
${$row['privilege']};
}
?>

The list of errors:

 

Notice: Undefined variable: admin_panel in C:\xampp\htdocs\DynamicVariables.php on line 20


Notice: Undefined variable: create_user in C:\xampp\htdocs\DynamicVariables.php on line 20

Notice: Undefined variable: edit_user in C:\xampp\htdocs\DynamicVariables.php on line 20

Notice: Undefined variable: delete_user in C:\xampp\htdocs\DynamicVariables.php on line 20

Notice: Undefined variable: create_group in C:\xampp\htdocs\DynamicVariables.php on line 20

Notice: Undefined variable: edit_group in C:\xampp\htdocs\DynamicVariables.php on line 20

Notice: Undefined variable: delete_group in C:\xampp\htdocs\DynamicVariables.php on line 20

Notice: Undefined variable: view_log in C:\xampp\htdocs\DynamicVariables.php on line 20

Notice: Undefined variable: log_settings in C:\xampp\htdocs\DynamicVariables.php on line 20

Notice: Undefined variable: password_change in C:\xampp\htdocs\DynamicVariables.php on line 20

 

Thanks


Making a PHP script non accessible to traffic

$
0
0

How can I make my PHP script non accessible to users? I am wanting to cron the script and don't want anybody to spam the script as it would cause performance issues if it was constantly spammed by a user. Can I put the PHP file anywhere that only the server can run it?

 

Thanks any info would be awesome.  

Formatting date and time

$
0
0

I have selected datetime values from a MySQL database (originally stored with the NOW() method) and want to present them on a page formatted in a specific way. I succeded in making it work with the following php code:

$time = date('d/m Y H:i', strtotime($row['time']));
echo $time;

I am however unsure if this is the best way to do it? I noticed some comments at php.net stating that this method has some limitations due to UNIX time. I am confused. There seem to be many ways of formatting date and time. Maybe somebody can clarify the situation, and tell me what will be appropriate in the current situation? I will appreciate any suggestions ...

 

Erik 

Help with Contact Form Maker

json_encode() function problem

$
0
0

when trying to decode a array of rows taken from my database I found that the json_encode function doesn't allow you to present you array as (with brackets [ ])

[{"name":"Destramic"}]

but returns the array as (without brackets [ ])

{"name":"Destramic"} 

I looked into the documentation and it doesn't seem as if php offer such a way of having bracket which Is a bit of a problem with passing to jquery (which I've found using their autocomplete plugin)

 

this has resulted in me having to add brackets myself

$data = "[" . json_encode($rows2) . "]";

does anyone know if you can encode it with the brackets or readable for jquery...thank you

Frustrating problem!

$
0
0

Hello everyone.

 

Bear with me here, I'm not a true PHP or otherwise coder by trade and have only a basic understanding of the terminology. I'll try to explain my issue as clearly as I can.

 

I'm working with a Wordpress theme. The "WP Conference Theme" to be exact.

 

This theme allows you to quickly and easily add Speakers to your conference by way of an automated form. When you create a new speaker, you have the option to create a new "role" for them. This can be anything you want, such as "moderator", "host, "panelist" - what have you.

 

Picture 1:

I4VcgFQ.png

 

In the general settings for the conferece, there is a dropdown where you have the option to select a "role" of speaker to display on the footer of the homepage - additionally, the category of speaker selected here is used to populate a stand-alone page showcasing all the speakers. Every speaker assigned the selected role appears in both these locations. Here is a shot of the HTML from the source code of this dropdown:

 

DlesYOm.png

Here you can see the default role "Speaker" and the new role I have created, "whyattend".

 

Currently the footer and speaker page show whichever "role" is selected from the dropdown in the general settings.

 

I want to show one category of speaker in the footer (whyattend), and have an entirely different category show on the speaker page (Speaker).

 

Since the Speaker page populates automatically by way of the role selected in the general settings, I started with the code for the Footer.

 

Here is the PHP for the Footer:

 

ecGD1TA.jpg

 

I have tried playing around with this already and have gotten results CLOSE to what I am looking for, but not quite.

 

The closest I came was by changing the last instance of "('role'=>$speaker" to "('role'=>$whyattend".

 

Doing this shows ONLY those desginated as "speakers" on the Speaker page, but it still shows all of the roles on the footer.

 

The PHP on the Speaker page is identical to this code on the footer.

 

I apologize if this is confusing.

Expiration date

$
0
0

Hi everyone,

 

My googling seems to have found an way to add x days to the current date, and I'm sure that finding x days from a date pulled from my database must be pretty similar, but I just can't seem to get it working.

 

My task involves teachers setting notifications which are displayed for a number of days designated by the teacher.

 

So when the teacher creates the notiication, the `notificatin_date` field is updated with the timestamp.  The `notification_duration` field is an integer between 1 and 21.

 

I can get this info out of the database without problem:

$notification_set  = date('Y-m-d', strtotime($notification['notification_date']));
			   $notification_duration = $notification['notification_duration'];
			   echo $notification_duration . "<br/>";
			     echo  $notification_set . "<br/>";

However, when I try and add the duration to the date when the notification was set, to echo the expiry date, I run in to problems. This is what I've got at the current time, but I'm obviously not 'adding' $notification_duration and $notification_set correctly in the first line below, which is causing all my problems. Any help is much appreciated.

	$expiration_date = $notification_set + strtotime($notification_duration . "days");
			   
			   if ($expiration_date> date)
			   {
				echo "Your notification will expire on ";   
			   }
			   else if ($expiration_date < date)
			   {
				echo "Your notification expired on ";   
			   }
			   else echo "Your notification expires today ";
			   
			   
			   echo   date('jS', strtotime($expiration_date));
			echo " of ";
	echo date('F', strtotime($expiration_date));
				echo ", ";
	echo date('Y', strtotime($expiration_date));   

Thanks for your time,

Dave

 

 

 

 

 

How to take automatic preview of apk file using php?

$
0
0
<?php
$files=glob('apk/*');
foreach( $files as $file)
{ echo '<img scr="'.$file.'">'.basename($file).'</img><br/>';

}

?>

How/what script can I execute (on Page/Form Load) in order to show/hide a container?

$
0
0

Hi,

 

In reference to my first attached image, I have a form which displays two SELECT/drop-down fields (labeled "Store Name" and "Item Description".....and both of which pull-in values from two separate lookup/master tables, in addition to providing an additional option each for "NEW STORE" and "NEW ITEM").

 

Now, when first-run, and/or if "NEW STORE" and "NEW ITEM" are not selected from the drop-down's then the two fields in green ("New Store Name" and "New Item Name" are hidden, by means of the following code:

 

<div class="new-store-container" id="new-store-container" name="new-store-container" style="display:none;">
    <div class="control-group">
        <div class="other-store" id="new_store_name">
            <?php echo standardInputField('New Store Name', 'new_store_name', '', $errors); ?>
        </div>
    </div>
</div>

 

Conversely, if "NEW STORE" and/or "NEW ITEM" are selected from the two drop-down's then one (or both) of the "New Name" fields are unhidden by means of the following two pieces of code, one PHP and the second JS:

 

 

<select class="store-name" name="store_id" id="store_id" onclick="toggle_visibility('store_id','new-store-container')">
    <?php echo $store_options; ?>
                            
    <?php
        if($values['store_id'] == "OTH")
            {
                echo "<option value='OTH' selected> <<<--- NEW STORE --->>> </option>";
            }
        else
            {
                echo '<OPTION VALUE="OTH"> <<<--- NEW STORE --->>> </OPTION>';
            }
    ?>
</select>

 

function toggle_visibility(fieldName, containerName)
{
    var e = document.getElementById(fieldName);
    var g = document.getElementById(containerName);
            
    if (e.value == 'OTH')
        {
            if(g.style.display == 'none')
                g.style.display = 'block';
            else
                g.style.display = 'none';
        }
}

 

All  of that is working just fine. The problem I'm having is that when I click the "Create" button, after having left any one of the form fields blank, the two "New Name" fields are hidden again, which I don't want to happen i.e. I want them to remain visible (since the values of "store_id" and/or "item_id" are "OTH"), so that the user can enter values into one or both of them, without havng to click on the drop-down a second time in order to execute the "on-click" code.

 

The second attached image shows how the fields are hidden, after clicking "Create".

 

How can I achieve that? It would be greate if someone could cobble-up the required code and provide it to me, since I'm relatively new to this.

 

Thanks much.

 

Snap1.png

 

Snap2.png

 

 

 

convert input text into images based on alphabet

$
0
0

the idea on what im doing is like a converter, like showing what your name would look like with certain images per letter, when you input text (your name for example) and when you press the submit button you would get a series of images in a row that represent each character that you typed.

 

here is the example that i did...

<html>

<?php
 if(isset($_POST['Translate'])) {
$image = array(
    'a' => 'a.png',
    'b' => 'b.png',
    'c' => 'c.png',  );
$char = $_POST["ConvertEng"];
for  ($i=0; $i<strlen($string); $i++) {
?>
Character: <?php echo $char[$i]; 
}?><br /><br />
<img src="<?php echo $image[$char]; ?>"
     alt="Images for the '<?php echo $char ?>' character."
/><br /><br />
<?php } ?>
  <p style="text-align: center;">
     <form action='convert.php' method ='POST'>
<table border="2">
<tr>
<td>Convert English into images :</td><td><input type="text" name="ConvertEng" size"20"></input></td>
</tr>
</table>
<input type="submit" name = "Translate" value = "Translate">
</form>   <p>
</html>
so far this works on 1 character 1 image only , BUT :happy-04: how would i correct this coding by getting the whole text(more than 1 character in the inputed text) into their correct sequence of images... 

Event updater and news form

$
0
0

So I have no experience with PHP what so ever, I just pretty much learned and copy and paste...

I made my friend a website for his racing, and I manually update his upcoming races and have to go into the .php to add news, etc..

 

I was wondering if there was a way where the upcoming races could be automatically updated?

 

Also if there was a way where I could just easily submit a new news article through a forum and post it to the home page directly?

 

Any help is greatly appreciated!

 

If you want to take a look at what I mean, the website is bobbykendallracing . com 

I am not trying to advertise, or promote anything, just trying to get help with PHP!

Parse the return values of a webservice object

$
0
0

I call a web service and it retuens the values in the following format

$response = $client->submitRequest($requestParams);

Which returns

stdClass Object
(
    [return] => stdClass Object
        (
            [result_code] => 0
            [result_data] => City[0]=Chicago
            [message_text] => 
        )

)

what I want is just the value for

[result_data] => City[0]=Chicago

assigned to a variable

 

 

Psedo Code

$city = [result_data] => City[0]=Chicago;

so that $city = Chicago;

 

Date, between date column and date column -3 days

$
0
0

Hellow, i need help please, writing code and it doesn't work. please help... :)

 

Here it is

WHERE start_date BETWEEN 'start_date".strtotime('-3 day')."' AND 'start_date'";

without this code everithing works fine :)

 

Thank you

Viewing all 13200 articles
Browse latest View live