mardi 4 août 2015

kcfinder have upload directory selected through URL

Problem: As found in kcfinder's definition I am using this link to open kcfinder:

window.open('/kcfinder/browse.php?type=files&dir=files/public&subDir=/PO/'+editId, 'kcfinder_textbox',
            ', width=800, height=600');

In here, I have modified the URL to also include the subdirectory path so that the URL becomes something like this http://ift.tt/1VZ7aBx .

The subDir part has the directory name to be set to (and created if not exists). In the config.php I already have a directory set to be the root. So if the subDir is provided it will create the subDir inside the root of config.php. Now I would want this subDir to be the new root directory for kcfinder.

So for example if my uploadURL in the config is /var/www/html/web/upload/ the new root for the above URL will become /var/www/html/web/upload/PO/200836/.

Attempt: So far I have been able to successfully create the directory /var/www/html/web/upload/PO/200836/ for the above URL (or any URL) provided. However, the root in kcfinder is still set to /var/www/html/web/upload/. So when I open the kcfinder, the directory gets created internally but the root is still set to the original root from config.php.

I added the following lines to change my root directory to the sub directory I pass through URL:

$this->config["uploadURL"] .= $_GET['subDir'];
$this->config["uploadDir"] .= $_GET['subDir'];
$this->typeDir = $this->config["uploadDir"] ."/files";
$this->typeURL = $this->config["uploadURL"] ."/files";

I have also raised this as an issue on github but no response from there yet. I am assuming the only change I need to do is set the root directory to display to the new directory being created but I am not sure where I am supposed to do this.

Is there a workaround for this?

PS: I am also open to any other web file manager PHP/jQuery solutions which has a way to do this. Using symfony as the framework.



via Chebli Mohamed

Composer, class within my package is not being autoloaded in application using it

I'm creating a module which I will include in several projects. However, in a project that uses the module, the autoloader doesn't seem to include the class in the module.

The module structure (etc) is as follows:

Directory structure in the git repository:

/
/composer.json
/src/
/src/EbayAPI.php

composer.json:

{
    "name": "jodes/ebay-api",
    "autoload": {
        "psr-4" : {
            "Jodes\\EbayAPI\\" : "src"
        }
    }
}

EbayAPI.php:

<?php
namespace Jodes;
class EbayAPI {}

And the application I'm trying to include it in has the following:

composer.json:

{
    "require": {
        "behat/behat": "@stable",
        ....other requirements in here...
        "jodes/ebay-api": "dev-master"
        },
    "config": {
        "bin-dir": "bin/"
    },
    "repositories": [
        {
            "type": "vcs",
            "url": "http://ift.tt/1P3M0gX"
        }
    ]
}    

And the php file that wants to use my package via the autoloader is:

<?php

use Jodes\EbayAPI;
require_once 'vendor/autoload.php';

class HelloWorld {
    public function __construct(){
        $ebay = new EbayAPI();
    }
}

The error I get is

Fatal error: Class 'Jodes\EbayAPI' not found

What am I doing wrong? Thanks



via Chebli Mohamed

HTML/PHP selecting a value from dropdown menu and retrieving the associated row and output all the data from that row

Its a bit hard to express what I want to do but let me give it a shot.

First of all I have a database with a table. One of the columns from that table I will be showing in a select dropdown menu in HTML, to be more precise: this outputs the column 'name' in the dropbown menu:

<?php
$query = mysql_query("SELECT name from table");

echo "<select name='select1'>";

while ($row = mysql_fetch_array($query))
{
echo "<option value'" . $row['name'] ."'>" . $row['name] . "</option>;
}
echo "</select>";
?>

Then when a value is selected in that dropdown, that value needs to be saved in a variable.

if (isset($_POST['button']))
{
$select = $_POST['select1'];
}

As last bit, the value in variable $select needs to be used to make a SELECT query. I want to use that variable in the SELECT statement to look for the corresponding row (in the same table) that is related to the value in the dropdown menu and pick a column and output that value to a textbox or checkbox, depending on as what the value needs to be outputted.

Example:

TABLE

      id - name - street - number - ...
row 1: 0 - test1 - teststreet1 - 1 - ...
row 2: 1 - test2 - teststreet2 - 2 - ...
row 3: 2 - test3 - tesstreett3 - 3 - ...

1) I select test2 from the dropdown menu (dropdown menu is filled with the column name from database)

2) test2 is saved as a variable in $name

3) select query searches for value of street column where $name = test2

SELECT street from table where ?
row 2: 1 - test2 - tesstreett2 - 2 - ...

So I want teststreet2 from street to be outputted in a textbox

<input type='text' value='?'>

I need help with the select query or how to call this.

Thanks in advance and taking time to read this!

Kind Regards



via Chebli Mohamed

PHP, prevent javascript from running

I am making a website where people will publish an article. I make them write their article in a textarea, but I don't want them to add javascript, php or any other langage than html to prevent XSS or SQL injections.

How can I do this?



via Chebli Mohamed

How to push only validation error messages into an array using Laravel

I have a validator, it has error messages, and my goal is to get only error messages with the field names.

$validator = Validator::make(
   array(
      'firstField' => Input::get('firstFieldName');
      'secondField' => Input::get('secondFieldName');
   ),
   array(
      'firstField' => 'required';
      'secondField' => 'required';
   )
);

if($validator->fails()){
   return $validator->messages();
}

So, this piece of code is returning some values to my js file as following

function getErrorMessages(){
   //Some UI functions
   var myDiv = document.getElementById('messageDivID');
   $.post('validationRoute', function(returedValidatorMessageData)){
      for(var a in returedValidatorMessageData){
         myDiv.innerHTML = myDiv.value + a;
      }
   }
}

Problem is, the only values i get from post request is like firstField secondField but i'd like to get like firstField is required message. What would be the easiest way ?

Thanks in advance.



via Chebli Mohamed

How to match any characters without space and don't array usefull things

How to search all characters without space and optimize speed of my script by don't adding LTEXT, PUSHBUTTON etc to the array.

My pattern:

$pattern = '/(LTEXT|PUSHBUTTON|CAPTION|GROUPBOX|RTEXT|MENUITEM|[0-9]+|IDS_.+|STRING_.+) .*"(.+)".*\R?/';

To be more specific: searching chars without characters must be in this place of code: "(.+)"

Input:

IDS_NO_SUCH_FILE "FIND: %s: Plik nie został znaleziony\n"
LTEXT_BLANK " "
0 "Some text"
1 " Some text "

Output

FIND: %s: Plik nie został znaleziony\n
Some text
 Some text 



via Chebli Mohamed

build an array of mysql query?

Could someone please let me know how I can create an array from the MYSQL query?

The array should look like this:

<?php
$testLocs = array(
    '1' => array( 'info' => '1. New Random info and new position', 'lat' => 45345345, 'lng' => 44.9634 ),
    '2' => array( 'ino'  => '1. New Random info and new position', 'lat' => 686788787, 'lng' => 188.9634),
    '3' => array( 'info' => '1. New Random info and new position', 'lat' => 88888, 'lng' => 144.9634),
    '4' => array( 'info' => '1. New Random info and new position', 'lat' => 666666, 'lng' => 144.964 )
);
echo json_encode($testLocs);
exit();
?>

where the Texts for info and numbers for lat and lng are mysql $rows.

Any help would be appreciated.



via Chebli Mohamed

Execute Python script from Php

I have a PHP webpage on my raspberry pi with 2 buttons (on and off) The on button button redirects to On.php The off button redirects to Off.php In "/usr/lib/cgi-bin" I have a python script that I would like to execute (script.py) I can perfectly execute it from the terminal by typing

cd /usr/lib/cgi-bin
sudo python script.py

It works if I do it from the terminal.

The problem is the PHP file (On.php) in my "/var/www" folder. This is what I wrote:

<?php
exec('cd /usr/lib/cgi-bin');
exec('sudo python script.py');
?>

Why is the script executing from the terminal, but not from my PHP?



via Chebli Mohamed

Input to Javascript from file via php

I have a setup where I want to send the results of a python script asynchronously to a webpage. I currently have a HTML page setup, with a Javascript file that deals with the information dynamically.

However, I don't really understand how to get the Javascript to interact with Server-side files, seeing as its done through PHP. What do I do to set up a php file that takes the input from a text file (generated every x seconds from the python script), and sends it to the Javascript?



via Chebli Mohamed

PHP Gearman Worker / Client does not work

I am trying to execute this minimal example of a gearman Job Server with php:

worker.php:

<?php
ini_set('display_errors', 1);
error_reporting(~0);
$worker= new GearmanWorker();
$worker->addServer();
$worker->addFunction("reverse", "my_reverse_function");
echo "Starting Worker...\n";
while ($worker->work());

function my_reverse_function($job)
{
  return strrev($job->workload());
}
?>

client.php:

<?php
ini_set('display_errors', 1);
error_reporting(~0);
echo "Starting Client...\n";
$client= new GearmanClient();
$client->addServer();
print $client->doNormal("reverse", "Hello World!");
?>

I am trying it in the console with php worker.php which gives the output "Starting Worker..." Then I am trying php client.php (in another console-window) which gives the output Starting Client... (no more). However I am expecting the output "!dlroW olleH" or at least a suitable error message.... The code following gives me the output: 1.0.6, so I am assuming, the gearman software is installed correctly. I am on a debian 8.1 btw.

<?php
echo gearman_version();
?>

What is wrong? Why does my Gearman Worker and / or Client not work?



via Chebli Mohamed

Laravel how to join tables and use where condition using Eloquent?

Lets say there are 2 tables:

videos (id, file_name)

matches (id, videos_id, match_number)

I want to get video file_name by match_number. I have read that using eloquent, you can avoid joins.

So I try various things from examples like this:

Video.php

class Video extends Eloquent {

    protected $table = 'videos';

    public function matches()
    {
        return $this->hasMany('Match', 'videos_id');
    }

    /*public function match()
    {
        return $this->belongsTo('Match', 'id');
    }*/

    /**
     * @param $matchNumber
     * @return mixed
     */
    public function getByMatchNumber($matchNumber)
    {
        return $this
            ->matches()
            //->select('videos.file_name')
            //->limit(10)
            ->where('matches.match_number', $matchNumber)
            ->file_name;
             //   ->match()


    }
}

But nothing works.

I think I am assuming well that video hasMany matches because in reality there are many matches which have same video.

So how it should look?

Update

Match_number column is unique, like id. There cannot be multiple matches with same match number. And there is only one video for one match. Limit(10) just was doing to try without where condition, to not get millions of results. But same video is assigned to many matches.



via Chebli Mohamed

Handling conflict in xdiff_file_merge3

I've to allow annotations in a HTML file by multiple users and merge annotations on server side. My example files are:

file1.html

<div class="a1 b1">This is example text by Kapil and Krish</div>

User 1 changes (annotations) file2a.html

<div class="a1 b1">This is example text by <span class='comment_123'>Kapil</span> and Krish</div>

User 2 changes file2b.html

<div class="a1 b1">This is example text by Kapil and <span class='comment_234'>Krish</span></div>

Expected output file2.html

<div class="a1 b1">This is example text by <span class='comment_123'>Kapil</span> and <span class='comment_234'>Krish</span></div>

On server side, I'm using PHP's xdiff_file_merge function. That works well in case changes are on different line but on same line, it gives error.

Is there any way handle that error using custom code, only for line having conflicts. Currently, in case of conflicts, file2.html (expected output) is exact copy of file2a.html (user 1 changes).

Even outside php (linux commands), is there any way to handle conflicts during file merge?



via Chebli Mohamed

Using multiple rows in another table to use IN SQL function

First off, let me apologise for the title, I couldn't get the wording correct. Anyway, here's my problem, I have a table with user's qualifications like so:

Qualifications table

CREATE TABLE IF NOT EXISTS `qualifications` (
  `qualification_id` int(11) NOT NULL,
  `qualification_qualification` varchar(255) NOT NULL,
  `qualification_establishment` varchar(255) NOT NULL,
  `qualification_dateobtained` date NOT NULL,
  `qualification_about` varchar(255) NOT NULL,
  `qualification_user` int(255) NOT NULL,
  `qualification_date` datetime NOT NULL,
  `qualification_enabled` int(11) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now when another use adds a job, they can add required qualifications before said user can apply, which puts it in the tables jobs like 1,2,3 which is the qualification_id

Now in my SQL I want to check multiple qualification_id to see if they're IN the job_requirements Here is my job table:

jobs table

CREATE TABLE IF NOT EXISTS `jobs` (
  `job_id` int(11) NOT NULL,
  `job_name` varchar(100) NOT NULL,
  `job_description` text NOT NULL,
  `job_duration` int(11) NOT NULL,
  `job_country` varchar(100) NOT NULL,
  `job_category` int(50) NOT NULL,
  `job_user` int(100) NOT NULL,
  `job_employer` varchar(100) NOT NULL,
  `job_enabled` int(2) NOT NULL DEFAULT '1',
  `job_startdate` date NOT NULL,
  `job_wage_type` int(1) NOT NULL,
  `job_wage` int(9) NOT NULL,
  `job_requirements` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

At the moment, this is the way I am doing it, I am using a foreach for all of the user's qualifications, then using IN which isn't working because I have done it wrong, here is my PHP code:

//get job details so we can get the requirements
$job = $database->prepare("SELECT * FROM jobs WHERE job_id = ?");
$job->execute(array($id));
$job_results = $job->fetch();

//get the users qualifications 
$user_qualifications = $database->prepare("SELECT * FROM qualifications WHERE qualification_user");
$user_qualifications->execute(array($user->user_id));
$user_results = $user_qualifications->fetchAll();

//I need to do this in 1 query FFS.... use IN(1,2,3,4)

//check if qualifications meet requirements
foreach ($user_results as $requirements):
    //check if id is IN job requirements
    $requirement_check = $database->prepare("SELECT * FROM jobs WHERE qualification_qualification IN(jobs_requirements)");
endforeach;



via Chebli Mohamed

Payment gateway not deleting cache (Very Important) Prestashop

Website- designinfo.in

This payment gateway which I have attached is working fine and converts the currency from Dollar or Euro to Rupee before sending the value to the payment gateway (PayuMoney Payment Gateway)

The PROBLEM is that when the customer changes the quantity of products or purchases a new product from the same browser then the price shown in the payment gateway does not change and shows the price of his previous order

Example-

Order 1 ------Final Cost =$1000 Price sent to payment gateway = INR 64000 ( $1000*64 ) .....( If 64 is the exchange rate for $ to INR ).

Order 2-------Final Cost =$2000 Price sent to payment gateway = INR 64000 unchanged ( $1000*64 ) .....( If 64 is the exchange rate for $ to INR ).

In order 2 the price sent should have been INR 128000 ( $2000*64 ).

Therefore the cache is not getting deleted and hence the old price is being shown.

Please note -

          1.The conversion is correct for the first time.

          2. Closing the browser and rebuying the product is not solving the problem.

          3. Changing the browser is solving the problem.

The code below has the payment.php file where the modification for the conversion code ( From Yahoo Finance ) is added.

Please advise what should I change.

<?php
    include(dirname(__FILE__).'/../../config/config.inc.php');
    include(dirname(__FILE__).'/../../init.php');
    include(dirname(__FILE__).'/payu.php');
    $context = Context::getContext();
    $fc = new Frontcontroller();
    $fc->setmedia();

    include(dirname(__FILE__).'/../../header.php');

    global $smarty,$cart,$cookie;

    //Added function for currency converter: This requires the library curl to be installed on the server.
    function currencyConverter($currency_from,$currency_to,$currency_input){
        $yql_base_url = "http://ift.tt/yEhaBW";
        $yql_query = 'select * from yahoo.finance.xchange where pair in ("'.$currency_from.$currency_to.'")';
        $yql_query_url = $yql_base_url . "?q=" . urlencode($yql_query);
        $yql_query_url .= "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
        $yql_session = curl_init($yql_query_url);
        curl_setopt($yql_session, CURLOPT_RETURNTRANSFER,true);
        $yqlexec = curl_exec($yql_session);
        $yql_json =  json_decode($yqlexec,true);
        $currency_output = (float) $currency_input*$yql_json['query']['results']['rate']['Rate'];
        return $currency_output;
    }

    $payu = new payu();
    if (!$cookie->isLogged(true))
        Tools::redirect('authentication.php?back=order.php');
    elseif (!$cart->getOrderTotal(true, Cart::BOTH))
        Tools::displayError('Error: Empty cart');

    if ($cart->id_customer == 0 OR $cart->id_address_delivery == 0 OR $cart->id_address_invoice == 0 OR !$payu->active)
        Tools::redirectLink(__PS_BASE_URI__.'order.php?step=1');

    // Prepare payment

    $customer = new Customer((int)$cart->id_customer);

    if (!Validate::isLoadedObject($customer))
        Tools::redirectLink(__PS_BASE_URI__.'order.php?step=1');

    $currency = new Currency(Tools::getValue('currency_payement', false) ? Tools::getValue('currency_payement') : $cookie->id_currency);
    //id_currency == 2 => Currency = INR; do not convert
    if ($cookie->id_currency == 2)
        $total = (float)($cart->getOrderTotal(true, Cart::BOTH));
    #id_currency == 3 => Currency = EUR; convert
    elseif ($cookie->id_currency == 3) {
        $from = "EUR";
        $to = "INR";
        $amt = (float)($cart->getOrderTotal(true, Cart::BOTH));
        $total = (float) currencyConverter($from, $to, $amt);
    }
    #id_currency == 1 => Currency = USD; convert
    else {
        $from = "USD";
        $to = "INR";
        $amt = (float) ($cart->getOrderTotal(true, Cart::BOTH));
        $total = (float) currencyConverter($from, $to, $amt);
    }

    $key=Configuration::get('PAYU_MERCHANT_ID');
    $salt=Configuration::get('PAYU_SALT');
    $mode=Configuration::get('PAYU_MODE');
    $log=Configuration::get('PAYU_LOGS');


    $customer = new Customer((int)($cart->id_customer));

    $action='http://ift.tt/1eQdIkd';

    //$cart = new Cart((int)($cookie->id_cart));;
    $orderId = (int)($cookie->id_cart);

    //echo "<br/>id_order:" . $id_order;

    $txnid= $orderId+232585630456;
    $amount=$total;
    $productInfo='PayUMoney product information';
    $firstname=$customer->firstname;
    $Lastname= $customer->lastname;
    $deloveryAddress = new Address((int)($cart->id_address_delivery));
    $service_provider='payu_paisa';


    $Zipcode      =  $deloveryAddress->postcode;
    $email=$customer->email;
    $phone=$deloveryAddress->phone_mobile;

    if($mode=='real') {
          $action='http://ift.tt/1Fi5l9v';
    }

    $request=$key.'|'.$txnid.'|'.$amount.'|'.$productInfo.'|'.$firstname.'|'.$email.'|||||||||||'.$salt;
    //echo $request;
    //die();
    $Hash=hash('sha512', $key.'|'.$txnid.'|'.$amount.'|'.$productInfo.'|'.$firstname.'|'.$email.'|||||||||||'.$salt); 

    $baseUrl=Tools::getShopDomain(true, true).__PS_BASE_URI__;        

    if($log==1) {
        $query="insert into ps_payu_order(id_order,payment_request) values($orderId,'$request')";
        Db::getInstance()->Execute($query);
    }

    $surl=$baseUrl.'modules/'.'payu'.'/success.php'; 
    $curl=$baseUrl.'modules/'.'payu'.'/cancel.php?id='.base64_encode($orderId); 
    $furl=$baseUrl.'modules/'.'payu'.'/failure.php';    
    $Pg='CC';

    $payuInfo=array('action' => $action,
                    'key' => $key,
                    'txnid' => $txnid,
                    'amount' => $amount,
                    'productinfo' => $productInfo,
                    'firstname' => $firstname,
                    'Lastname' => $Lastname,
                    'Zipcode' => $Zipcode,
                    'email' => $email,
                    'phone' => $phone,
                    'surl' => $surl,
                    'furl' => $furl,
                    'curl' => $curl,
                    'Hash' => $Hash,
                    'Pg' => $Pg            
                    //'service_provider' => $service_provider
        );


    $smarty->assign('Message','Please wait, you will be redirected to PayU Checkout');
    $smarty->assign($payuInfo); 
    $smarty->display('payment.tpl');


        //$payu->display(__FILE__, 'payu.tpl');
    echo '<br/><br/>Please wait. We are processing your request<form action="'.$action.'" method="post" id="payu_form" name="payu_form" >
        <input type="hidden" name="key" value="'.$key.'" />
        <input type="hidden" name="txnid" value="'.$txnid.'" />
        <input type="hidden" name="amount" value="'.$amount.'" />
        <input type="hidden" name="productinfo" value="PayUMoney product information" />
        <input type="hidden" name="firstname" value="'.$firstname.'" />
        <input type="hidden" name="Lastname" value="'.$Lastname.'" />
        <input type="hidden" name="Zipcode" value="'.$Zipcode.'" />
        <input type="hidden" name="email" value="'.$email.'" />
        <input type="hidden" name="phone" value="'.$phone.'" />
        <input type="hidden" name="surl" value="'.$surl.'" />
        <input type="hidden" name="furl" value="'.$furl.'" />
        <input type="hidden" name="curl" value="'.$curl.'" />
        <input type="hidden" name="Hash" value="'.$Hash.'" />
        <input type="hidden" name="Pg" value="'.$Pg.'" />
        <input type="hidden" name="service_provider" value="'.$service_provider.'" />            

        </form> 

        <script type="text/javascript">

        setTimeout(document.payu_form.submit(),5000)

        </script>';
//$payu->validateOrder((int)$cart->id, Configuration::get('PS_OS_PREPARATION'), $total, $payu->displayName, NULL, NULL, (int)$currency->id, false, $customer->secure_key);

//$order = new Order($payu->currentOrder);
//echo $payu->currentOrder;
//Tools::redirectLink(__PS_BASE_URI__.'order-confirmation.php?id_cart='.(int)$cart->id.'&id_module='.$payu->id.'&id_order='.$payu->currentOrder.'&key='.$customer->secure_key);
?>



via Chebli Mohamed

Not checking for User if existing [duplicate]

This question already has an answer here:

I have spent hours to check if a users exists or not. Whether there is a little typo or I completely messed up that stuff.

Here is my code:

if($_POST['username']) {
    if ( $password == $c_password ) {

        $db_name     = '*';
        $db_user     = '*';
        $db_password = '*';
        $server_url  = '*';

        $mysqli = new mysqli($server_url , $db_user, $db_password, $db_name);


        /* check connection */
        if (mysqli_connect_errno()) {
            error_log("Connect failed: " . mysqli_connect_error());
            echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
        } else {

            $check="SELECT * FROM USER WHERE 'Name'='". $username."'";
            $rs = mysqli_query($mysqli,$check);



             $data = mysqli_fetch_array($rs, MYSQLI_NUM);
             echo $data;
            if($data[0] > 1) {
                echo "User Already in Exists<br/>";
                                }

                else
            {

            $stmt = $mysqli->prepare("INSERT INTO USER (Name, Password) VALUES (?, ?)");
            $password = md5($password);
            $stmt->bind_param('ss', $username, $password);

            /* execute prepared statement */
            $stmt->execute();

            if ($stmt->error) {error_log("Error: " . $stmt->error); }

            $success = $stmt->affected_rows;

            /* close statement and connection */
            $stmt->close();

            /* close connection */
            $mysqli->close();
            error_log("Success: $success");

            if ($success > 0) {
                error_log("User '$username' created.");
                echo '{"success":1}';
            } else {
                echo '{"success":0,"error_message":"Username Exist."}';
            }}
        }
    } else {
        echo '{"success":0,"error_message":"Passwords does not match."}';
    }
} else {
    echo '{"success":0,"error_message":"Invalid Username."}';
}

It keeps registering users even though I added a check inside. The echo does not give me a accurate feedback on how to fix this issue...

Best, Dan



via Chebli Mohamed

How to upload two files at two different paths in Yii2?

public function actionCreate()
{
        $model = new RoomTypes();
        if ($model->load(Yii::$app->request->post())) 
        {
            $imageName_1 = $model->room_type.'_'.'1';
            $model->pic_1 = UploadedFile::getInstance($model, 'pic_1');
            $model->pic_1->saveAs('uploads/room_pics/'.$imageName_1.'.'.$model->pic_1->extension);
            $model->pic_1 = 'uploads/room_pics/'.$imageName_1.'.'.$model->pic_1->extension;

            $imageName_2 = $model->room_type.'_'.'2';
            $model->pic_2 = UploadedFile::getInstance($model, 'pic_2');
            $model->pic_2->saveAs('uploads/room_pics/'.$imageName_2.'.'.$model->pic_2->extension);
            $model->pic_2 = 'uploads/room_pics/pic2/'.$imageName_2.'.'.$model->pic_2->extension;
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else 
        {
            return $this->render('create', [
                'model' => $model,
            ]);
        }  
}

I'm not able to store 2nd image in folder, this code is storing 1st or 2nd image in folder, only one image is getting stored not all two, how to achive this?



via Chebli Mohamed

How to access a entity class from twig page

Suppose I have an entity class named Userinfo where the fields are name, guid, status...

So now from a twig page if i want to show all available name from the entity class Userinfo, how i can do that.

as an example --- in the page there can a table where it will show -- name and status.

So from entity class Userinfo all the names and their status will be shown.

Can someone knows how to dynamically show the data into the twig page from an entity class, can you kindly give me an example if possible.



via Chebli Mohamed

Uber Uploader XML ERROR: XML_ERR_NAME_REQUIRED at line 1 with hwdMediaShare

Uber uploader was working perfectly, and then suddenly it doesn't work and has this error:

XML ERROR: XML_ERR_NAME_REQUIRED at line 1

It occasionally starts working again and then goes back to this problem.



via Chebli Mohamed

youtube v3 api, check if Video existing

I've tried to check if a youtube video is online, not private, not deleted etc. I need it for a Video-Blog.

All of the code I've found and tried hadn't worked. I hope you can help me. I've registered for the new API v3.

My code is as follows, but I always get "Bad Request 400"

$theURL = "http://ift.tt/1eQdIk1". get_post_meta($post->ID,"wpzoom_post_embed_code", true) ."&key=my_api_key";
//                echo $theURL;
                //$theURL = "http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=". get_post_meta($post->ID,"wpzoom_post_embed_code", true) ."&format=json";
                $headers = get_headers($theURL);
                print_r ($headers);
                if (substr($headers[0], 9, 3) !== "404") {
                    echo "online";
                } else {
                    echo "offline";
                }  



via Chebli Mohamed

i have two fields.today sale and yesterday sale.i want to change the image when sale valuew change how can i change that?

I found this script: http://ift.tt/1gHeQZi Unfortunately I can't login. I had a look at the code but can't figure out what is wrong. When starting this script the user has to type ...



via Chebli Mohamed

phishing link placed on shared hosting web pages

This morning I received notification from Google (noreply@gooogle.com) that several of my accounts on my shared Linux hosting reseller account had phishing links placed on them. They were all different hosted domains on the same reseller account. The links had something in common, so were probably placed by the same hacker. All suspicious links looked like this:

http://ift.tt/1MKksxQ

I contacted the hosting company about a possible vulnerability on their servers, but I was wondering if these links could have been placed on my accounts due to one of my admin passwords being compromised. I also would like to know where I could find these links and remove them myself. I'm not sure where to track down the /~cp/request/linkd/ Linux directory. Is this related to a cpanel directory? My search of my file system for index.php did not find any suspicious files or directories.

Also, some sites were running WordPress, but are all up to date and hardened installs, and some sites were basic html5 sites (no WordPress).



via Chebli Mohamed

Meta Query Filter by Tag Wordpress

I currently have multiple pages, and in each page is a custom field which is named 'country'.

In the 'country' field I have this value 'uk, usa, brazil'.

What I'm wanting to do is display posts on the page which have the tags I have listed in the custom field 'country' (In this case show posts which has any of the tags 'uk', 'usa' and 'brazil').

I have the following code, but I don't know how to manipulate it to do the above?

$args = array (
    'post_type'              => array( 'post' ),  // YOUR POST TYPE
    'meta_query'             => array(
        array(
            'key'       => 'country',  
            'value'     => $your_country,  // THE COUNTRY TO SEARCH
            'compare'   => 'LIKE',  // TO SEARCH THIS COUNTRY IN YOUR COMMA SEPERATED STRING
            'type'      => 'CHAR',
        ),
    ),
);

// The Query
$query = new WP_Query( $args );

It seems to just be filtering for a single value?

Any help to achieve the above would be greatly appreciated.



via Chebli Mohamed

PHP - MySQL I always got username exists, but why? [duplicate]

This question already has an answer here:

I tried echo($numrows);

numrows is equal to 0. then why i got this error : username exists?

I went trough it all many times, but I can't find what is the problem..

<?php

function generateRandomString($length = 6) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

//innen regiszt:
$username = strip_tags($_POST['username']);
$email1 = strip_tags($_POST['email1']);
$email2 = strip_tags($_POST['email2']);
$pw1 = strip_tags($_POST['pw1']);
$pw2 = strip_tags($_POST['pw2']);

if($username&&$email1&&$email2&&$pw1&&$pw2)
    {
     if ($email1==$email2)
         {
             if ($pw1==$pw2)
             {               
                 if (5<strlen($pw1)&&20>=strlen($pw1))
                 {
                    if (5<strlen($pw1)&&20>=strlen($pw1)) 
                    {                       
                    $connect = mysql_connect('HOST','UNAME','PW');
                    $database = mysql_select_db('virtualtc',$connect);  
                    $query = mysql_query("SELECT * FROM users WHERE username='$username'");
                    $querymail = mysql_query("SELECT * FROM users WHERE email='$email1'");
                    $numrowsmail = mysql_num_rows($querymail);
                    $numrows = mysql_num_rows($query);
                       if ($numrows=0)
                       {
                            if ($querymail=0)  
                            {
                                $md5pass= md5($pw1);
                                $date=date("Y-m-d");
                                $query3 = mysql_query(
                                    "INSERT INTO users VALUES '','$username','$md5pass','$email1', 0 ,'$date'");
                                include("registration_complete.php");//regist

                            }else include("/errors/email_exists.html");//email exists
                       }else include("/errors/user_exists.html")//user exists                   
                    }else include("/errors/uname_length.html");//username length 6-20!                   
                 }else include("/errors/pass_length.html"); //password length 6-20!              
             } else include("/errors/different_pw.html");//different password
         } else include("/errors/different_email.html");//different email
    } else include("/errors/empty_regist.html");//empty field


?>



via Chebli Mohamed

foreach every 3 put inside a new ul

Actually I have this foreach loop:

<ul>
    <?php foreach ( $tasks as $task ) { ?>
        <li>
            ...
        </li>
    <?php } ?>
</ul>

It returns:

<ul>
    <li>...</li>
    <li>...</li>
    <li>...</li>
    <li>...</li>
    ...
</ul>

Now I need to change the loop to put every 3 <li> into a new <ul>, so I can have:

<div>
    <ul>
        <li>...</li>
        <li>...</li>
        <li>...</li>
    </ul>
    <ul>
        <li>...</li>
        <li>...</li>
        <li>...</li>
    </ul>
    ...
</div>

How I have to modify the foreach loop to achieve that result?



via Chebli Mohamed

Wordpress prepared LIKE query

I'm trying to use a prepared LIKE query within Wordpress, but it doesn't seem to be working. I've followed the codex for the syntax.

public function userByJobId($id){        
    global $wpdb;
    $result = $wpdb->get_row($wpdb->prepare( "SELECT * FROM use_users WHERE use_job_id LIKE = d%;", '%' . $wpdb->esc_like((int)$id)) . '%');

    if(!empty($result)){
       return $result;
    }
    return false;
}

Calling the method like so:

$userid = 1
$user = new Users();
$user_id = $user->userByJobId($userid);

Cant see where the issue lies..



via Chebli Mohamed

ORDER BY one ID when there are more of the same ID's in one table

I have 4 tables:

  1. Users
  2. Forums
  3. Discussies (discussions)
  4. Forumberichten (messages)

The table Forumberichten (messages) contains the id's of the Discussion (discussions) table as a reference to reactions on a discussion. If there are 5 reactions to a discussion, there are 5 id's in the table with the same value.

How do I display an echo of one discussion of every different discussion with the latest reaction on it?

I've tried ORDER BY, DISTICT, GROUP BY and other things but I can't get it to work. I keep getting more outputs of the same discussion or one discussion with the original input and not the latest reaction to it.

<?php
// DISCUSSIES FORUM SCHRIJVEN

$sql="SELECT forumberichten.discussieid,forumberichten.datum,discussies.discussieid,discussies.titel,discussies.forumid,discussies.highlight,forums.forumid,forums.forumnaam,users.userid,users.userimage,users.username FROM forumberichten,discussies,forums,uers WHERE forumberichten.discussieid=discussies.discussieid AND discussies.forumid=forums.forumid AND forumberichten.userid=users.userid AND forums.forumid=1  ORDER BY forumberichten.bericht_id DESC LIMIT 3";
    $result = $conn->query($sql) or die ("The query could not be completed. try again");
    if ($result->num_rows > 0) {

    echo "
    <br>
    <table id='forumschrijvenklein'>
    <tbody>
    <tr>
    <td bgcolor='#1E1E1E'></td>
    <td nowrap bgcolor='#1E1E1E'>&nbsp;</td>
    <td nowrap bgcolor='#1E1E1E' class='sterrenkleur'>Discussie</td>
    <td nowrap bgcolor='#1E1E1E' class='sterrenkleur'>Laatste reactie</td>
    <td nowrap bgcolor='#1E1E1E' class='sterrenkleur'>Datum</td>
    <td nowrap bgcolor='#1E1E1E' class='sterrenkleur'></td>
    </tr>
     ";

    // output data of each row
       while ($row = $result->fetch_assoc()) {

    echo" 
    <tr>";if ($row["highlight"] == '1') {
    echo " <td bgcolor='#FC6'></td>";
    } else {
    echo "<td bgcolor='#1E1E1E'></td>";
    }
    echo"
    <td nowrap bgcolor='#1E1E1E'>";if ($row["userimage"] == '') {
    echo "
    <a href='user.php? id=" . $row['userid'] . "'</a><img    src='Images/users/nopicture.png' alt='nopicture'  class='userimage-tooltip-small' title='".$row['username']."''></a>";
    } else {
    echo "<a href='user.php? id=" . $row['userid'] . "'</a><img src='Images/users/".$row['userimage']."' class='userimage-tooltip-small' title='".$row['username']."''></a>";
    }           
    echo"</td>
    <td bgcolor='#1E1E1E'><a href='discussie.php? id=" . $row['discussieid'] . "'>".$row["titel"]."</a></td>
    <td bgcolor='#1E1E1E'><a href='user.php? id=" . $row['userid'] . "'</a>".$row["username"]."</a></td>
    <td nowrap bgcolor='#1E1E1E'>"; echo date("d-m-y H:i",strtotime($row["datum"]));"
    ";
    echo"
    </td> 
    <td nowrap bgcolor='#1E1E1E'></td>
    </tr>
    ";
    }
    }
    echo " 
    <tr>
    <td bgcolor='#1E1E1E'>&nbsp;</td>
    <td bgcolor='#1E1E1E'>&nbsp;</td>
    <td bgcolor='#1E1E1E'><img src='Images/lijntransparant.png' width='315' height='2'></td>
    <td bgcolor='#1E1E1E'><img src='Images/lijntransparant.png' width='140' height='2'></td>
    <td bgcolor='#1E1E1E'>&nbsp;</td>
    <td bgcolor='#1E1E1E'>&nbsp;</td>
    </tr>
    </tbody>
    </table>
    ";  
    }
    ?>



via Chebli Mohamed

concatenate query result in a string

I am getting a db result as 3 rows (Please see image link below).

enter image description here

The sql statement used is

select tevmkt.ev_mkt_id, tevmkt.name, tevmkt.ev_id, tevoc.ev_oc_id, 
       tevoc.desc, tevoc.fb_result, tevoc.lp_num, tevoc.lp_den, 
       tev.start_time
from tevmkt, tev,tevoc
where tevmkt.name = '|Match Result|' and tev.ev_id=tevmkt.ev_id and 
      tevoc.ev_mkt_id=tevmkt.ev_mkt_id and tev.start_time>=Today;

I will like to use php to concatenate each of the 3 rows into string or maybe use SQL statement.

So, the first 3 rows will display as ;

632274|Match Result||Draw||Aldershot Town||Arsenal FC|

And the next 3 rows

637799|Match Result||Draw||Southend United||Oxford United|



via Chebli Mohamed

jQuery live calc multirow input

This is my code:

<?php
    for($i=1;$i<10;$i++){ 
        echo '<input type="text" class="count value'. $i .'">';
        echo '<input type="text" class="count '. $i .'value">';
        echo '<input type="text" disabled="disabled" id="result'. $i .'"><p>';
    }
        echo '<input type="text" disabled="disabled" id="total"><p>';
    ?>

and jq

$(document).ready(function(){
    $(".count").keyup(function(){
        for (var i = 0; i < 10; i++) {
            var val1 = +$(".value"+ i).val();
            var val2 = +$("."+ i +"value").val();
            $("#result" + i).val(val1*val2);
        }
   });
});

$(document).ready(function(){
    $(".count").keyup(function(){
        for (var i = 0; i < 10; i++) {
            var vala = 0;
            vala += +$("#result"+ i).val();
            }
            $("#total").val(vala);
   });
});

First part of code works great. Return multiplication two inputs to id=result$i. I have a problem with last one id=total. It should return sum of all resultX inputs but now only return the last multiplication. Do You have any idea what's wrong?



via Chebli Mohamed

setting ftp to passive mode by default in php.ini

after a server change, it seems all php script which use ftp need to be modified as follows

$conn = ftp_connect("host.com");    
ftp_login($conn,"user", "pass");     

//must add this:
ftp_pasv($conn, true);

is there a simple way to mimic this call to ftp_pasv through php.ini (or some other config file)

would be easier than modifying each script



via Chebli Mohamed

CakePHP - How to continue saving if associated model fails validation

Let's say I have an array:

array(
    'Foo' => array(
        'field1' => 'value1',
        'field2' => 'value2'
    ),
    'Bar' => array(
        'field1' => 'value1',
        'field2' => 'value2'
    )
)

Where Foo and Bar have model relationships set up and have their own validation conditions in he model.

How can I make it so if I am doing $this->Foo->save(); even if Bar fails its validation then it will still go ahead and save Foo only



via Chebli Mohamed

how to pass variables though javascript to ajax using jquery-tabledit?

I am currently using the jquery plugin Tabledit and when i use an inline edit as in example 3 it calls my php page. I have no idea how to pass the changes I made in the edit to the new php page so i can change it in the database. it changes when you hit enter. (im guessing on enter it calls the edittask.php)

html here is one section of the table. it changes on hitting enter after you type in new text.

   <td class="tabledit-view-mode">
       <span class=" tabledit-span ">header text</span>
       <input class="tabledit-input form-control input-sm" type="text" name="description" value=" " style="display: none;" disabled="">
   </td>

javascript

   $('#thetable').Tabledit({
    url: 'editTask.php',
    editButton: false,
    deleteButton: false,
    columns: {
       identifier: [0, 'id'],
      editable: [[1, 'Header'], [2, 'Description']]
          }
});



via Chebli Mohamed

ucfirst() not working properly with scandinavic characters

How to get ucfirst() working with scandinavic characters?

$str = "SÄKYLÄ";
echo ucfirst(strtolower($str)); //prints SÄkylÄ

One possibility is use mb_convert_case() but I'd like to know if this is possible using ucfirst()

$str = "SÄKYLÄ";
echo mb_convert_case($str, MB_CASE_TITLE, "UTF-8"); //prints Säkylä

Which function is faster for string capitalization?



via Chebli Mohamed

Does redirecting www to https:// require AllowOverride or can it be set globally?

I am trying to change my apache2 server configuration which I'm sure is sub-optimal. Right now I have all the AllowOverride set to None. I would like to keep that configuration to set global rules and increase page load times.

However, the problem now is that I use a separate virtual host and directory with a .php file to redirect www.example.com to https://www.example.com. I'm sure that this is not optimal. I would prefer to use a mod_overwrite.

From what I have read, a rule set like the following would enable this. However, I would like to know where to put this code if I want to keep AllowOverride None.

RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

I believe that if I add a rule set like this in the right place, I can also disable the additional virtual host that I'm using to redirect.



via Chebli Mohamed

mysql warning during php json script

I am new in android developing.I got warning during querying the remote database.I can't access the database from my android app.please help me. here I attach mysql warning.

Warning: mysqli_connect(): Headers and client library minor version mismatch. Headers:50542 Library:50625 in /home/almadllf/public_html/new.php on line 7

{"result":["",{"id":"1","bus_name":"vinayaka","time":"06:50:00"},{"id":"2","bus_name":"kannan","time":"07:30:00"},{"id":"3","bus_name":"kuthirumal kalpaka","time":"07:30:00"},{"id":"4","bus_name":"vinayaka","time":"07:40:00"},{"id":"5","bus_name":"shethrapalaka","time":"08:10:00"}................



via Chebli Mohamed

Mysql select multiple count giving wrong values

I'm trying to find a patient's appointments and messages count. My table records are like below 3 table patient, appointments and messages
Patient table

pid     fname   lname
1      john     sid
2      rother   ford
3      megan    rough
4      louis    kane

appointments table

id  pid     appointment_date
1   1   2015-08-04
2   2   2015-08-05
3   1   2015-08-06
4   1   2015-08-07
5   3   2015-08-07
6   2   2015-08-08
7   4   2015-08-13
8   1   2015-08-12

Messages table

id  pid     description     message_date
1   2        join           2015-08-04
2   2        update         2015-08-05
3   3        join           2015-08-05
4   4        update         2015-08-10
5   3        test           2015-08-07

So if write query to find counts i'm getting wrong values

SELECT pd.fname,pd.lname , pd.pid, COUNT( a.id ) AS app_cnt, COUNT(   m.id   ) AS mes_cnt
FROM patient pd
LEFT OUTER JOIN appointments a   ON a.pid = pd.pid
LEFT OUTER JOIN messages m ON m.pid = pd.pid
GROUP BY pd.pid
ORDER BY pd.pid  

fname   lname   pid     app_cnt     mes_cnt
john    sid     1         4            0
rother  ford    2         4            4
megan   rough   3         2            2
louis   kane    4         1            1

Here pid 1 have 4 appointments and 0 messages, pid 2 have 2 appointments and 2 messages but getting wrong values.

Can someone please help to resolve this issue. I'm not interested in writing sub queries for this.

Functionality looks simple but I'm really facing problem for writing query.



via Chebli Mohamed

Get user information from users table

I have a query set where I am outputting comments which are bound to posts and also showing the user who posted the comment via this query:

$q = "SELECT p.post_id, f.created_date, f.comment_id, f.comment_content, j.id, u.user_id
         FROM forum_post AS p
         INNER JOIN comment_post_join AS j ON p.post_id = j.post_id
         INNER JOIN forum_comment AS f ON f.comment_id = j.comment_id
         INNER JOIN user_comment_join AS u ON u.user_id = u.user_id
         WHERE p.post_id = '$id'
         ORDER BY created_date ASC
     ";   

$r = mysqli_query ($dbc, $q); // Run the query.


// FETCH AND PRINT ALL THE RECORDS
while ($row = mysqli_fetch_array($r)) {

echo '
<div style="border-bottom: thin solid #ddd;">
    <p style="font-size: 13px;">'.$row["comment_content"] . '</p>
    <p style="font-size: 12px;">By: <a href="user_view.php?id=' . $row["user_id"] . '">'.$row["user_id"] . '</a> ' .date("F j, Y, g:i a", strtotime($row["created_date"])). '</p>
</div>
';

}  

As you can see the end result outputs the comment and also the user_id but if I ass u.first_name for example it fails to give me output. In my above it will output the users ID of who posted but struggling to get their name.

I have these tables:

users
  user_id
  first_name
  last_name

comment_post_join
  comment_id (Fk)
  post_id (Fk)

user_comment_join
  user_id (Fk)
  comment_id (Fk)

user_post_join
  user_id (Fk)
  post_id (Fk)

forum_post
  post_id
  post_title
  post_content
  post_created
  post_topic

forum_comment
  comment_id
  comment_content
  created_date

UPDATE

 function build_post_view(){

        global $dbc;

        $id = $_GET['post_id'];

        $q = "SELECT u.user_id, u.first_name, u.last_name, f.post_created, f.post_id, f.post_title, f.post_content, j.id 
                 FROM users AS u
                 INNER JOIN user_post_join AS j ON u.user_id = j.user_id
                 INNER JOIN forum_post AS f ON f.post_id = j.post_id
                 WHERE f.post_id = '$id'
             ";   

        $r = mysqli_query ($dbc, $q); // Run the query.

        // FETCH AND PRINT ALL THE RECORDS
        while ($row = mysqli_fetch_array($r)) {

        echo '
        <div style="border-bottom: thin solid #ddd;">
            <h3>'.$row["post_title"]. '</h3>
            <p style="font-size: 13px;">By: <a href="user_view.php?id=' . $row["user_id"] . '">'.$row["first_name"] . ' ' .$row["last_name"]. '</a> ' .date("F j, Y, g:i a", strtotime($row["post_created"])). '</p>
            <br>
            <p style="font-weight: 500; line-height: 150%;">' . $row["post_content"] . '</p>
            <br><br>
        </div>    
        ';

        } 


$q = "SELECT p.post_id, f.created_date, f.comment_id, f.comment_content, j.id, u.user_id, u.first_name, u.last_name
         FROM forum_post AS p
         INNER JOIN users AS us ON us.user_id = u.user_id
         INNER JOIN comment_post_join AS j ON p.post_id = j.post_id
         INNER JOIN forum_comment AS f ON f.comment_id = j.comment_id
         INNER JOIN user_comment_join AS u ON u.user_id = u.user_id
         WHERE p.post_id = '$id'
         ORDER BY created_date ASC
     ";   

$r = mysqli_query ($dbc, $q); // Run the query.


// FETCH AND PRINT ALL THE RECORDS
while ($row = mysqli_fetch_assoc($r)) {

echo '
<div style="border-bottom: thin solid #ddd;">
    <p style="font-size: 13px;">'.$row["comment_content"] . '</p>
    <p style="font-size: 12px;">By: <a href="user_view.php?id=' . $row["user_id"] . '">'.$row["user_id"] . ' '.$row["first_name"] . ' '.$row["last_name"] . '</a> ' .date("F j, Y, g:i a", strtotime($row["created_date"])). '</p>
</div>
';

}   
}



via Chebli Mohamed

Checking for users with a enum value of 1

what I am looking for is just a simple way to check a mysql db if a user has a enum row which is equal to one. What I want to do is to check if the user is a admin so say enum is =1 then he/she is an admin and can view the admin dir but I have no idea how to get that to work!



via Chebli Mohamed

ReflectionException - Class name does not exist in Laravel 5.0

I have a little problem trying to seed my comments table. I'm 100% sure that I have the Class CommentTableSeeder.php in my /database/seeds directory.


CommentTableSeeder.php

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class CommentTableSeeder extends Seeder {

    public function run()
    {
        DB::table('comments')->delete();

        Comment::create(array(
            'author' => 'Chris Sevilleja',
            'text' => 'Look I am a test comment.'
        ));

        Comment::create(array(
            'author' => 'Nick Cerminara',
            'text' => 'This is going to be super crazy.'
        ));

        Comment::create(array(
            'author' => 'Holly Lloyd',
            'text' => 'I am a master of Laravel and Angular.'
        ));
    }

}


Then when I run : php artisan db:seed

I kept getting

enter image description here

I've also try running composer update and run : php artisan db:seed - still get the same result.

Any hints / help will be much appreciated !



via Chebli Mohamed

GET request error on null file on every page

I am running a wordpress site and there is an error:

x GET http://mywebsite/null (index):1

and on every other page (example) the same error:

x GET http://mywebsite/mypage/null (index):1

The line of code at index:1 is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http//http://ift.tt/mOIMeg">

but it's not the code which is causing the error as if I move the code or remove it altogether the error persists.

I have searched high and low for a solution to get rid of this error. Does anybody know what I should be looking for?



via Chebli Mohamed

XMLHttpRequest error with Github Pages and subdomain [duplicate]

This question already has an answer here:

My custom domain is using my Github Pages source (domain.github.io), except a php file located at a subdomain on my account: http://ift.tt/1P3G0Vr to keep the info separate/private from Github. Now that my domain is going through Github Pages, I'm getting this error after my form submit.

The bizarre thing is, the form still works. It sends the text message, but I'm still getting the XMLHttpRequest error (and does not show ajax was successful).

Why is this an error if both domains are using domain.com?

XMLHttpRequest cannot load http://ift.tt/1P3G0Vr. Origin http://DOMAIN.com is not allowed by Access-Control-Allow-Origin. sendjquery-2.1.4.min.js:4:14958 ajaxjquery-2.1.4.min.js:4:10717 (anonymous function) formLogic.js:65 dispatchjquery-2.1.4.min.js:3:6472 handlejquery-2.1.4.min.js:3:3247



via Chebli Mohamed

Checkbox check all by name

Here is my fiddle which will select checkbox in the page.

But i wanted to check the group of checkbox with common class name.

Here is the Jsfiddle I have for that.

How can i achieve this ?

Here's the Script i have so far

$(document).ready(function(){
    $('.check:button').toggle(function(){
        $('input:checkbox').attr('checked','checked');
        $(this).val('uncheck all')
    },function(){
        $('input:checkbox').removeAttr('checked');
        $(this).val('check all');        
    })
})



via Chebli Mohamed

Insert a docx file into another docx file with PHP (and openTBS)

I use the PHP plugin OpenTBS to fill in placeholders in a Word .docx Document with normal ASCII text from a HTML form. Is there any possibility to insert the content of another docx file at a certain position (placeholder) in the template docx file? The important requirement is, that the text in the output file should be still formatted as the text in the input file.



via Chebli Mohamed

JSON post which returns answer in formatted string from webservice

JSON post which returns answer in formatted string from webservice (for example, i have a website with a search box, whatever i type in the search box, i want a formatted string instead it gives me a dump of the answer which is not formatted)

Here is the HTML/PHP code with JSON:

 <!-- Start of Search Wrapper -->
            <div class = "imageContainer">
            <a href="#"><img src="images/" title="logo" /></a>
            </div>
            <div class="search-area-wrapper">
                    <div class="search-area container">

                            <h3 class="search-header">Have a Question?</h3>
                            <p class="search-tag-line">If you have any question you can ask below or enter what you are looking for!</p>

                            <form id="search-form" class="search-form clearfix" method="get" action="" autocomplete="off">
                                    <input class="search-term required" type="text" id="questionText" name="questionText" placeholder="What is non medical prescribing?"
                                    title="* Please enter a search term!" />
                                    <input class="search-btn" type="submit" value="Search" />
                                    <div id="search-error-container"></div>
                            </form>
                    </div>
            </div>

                            <?php

                                    header('Content-type: application/json');
                                    header("Content-Type:application/json");

                                    // Credentials login details and URL connect
                                    $username = "";
                                    $password = "";
                                    $question = $_REQUEST['questionText'];
                                    $url = "https://test.com";
                                    $auth = base64_encode($username . ":" . $password);
                                    //askQuestion();

                       //     ------------------------------------------------------------------------------------------------------------- //

                            try {

                                   $data = json_encode(array(

                                   'question' => array(
                                   'evidenceRequest' => array('items' => 1),
                                       'formattedAnswer' => true,
                                   'questionText' => $question,

                                   ))
                                  );
                                 //$Extract = json_decode($data,true);
                                 // echo $data;
                                  //  echo $result;

                                  $curl = curl_init();

                                  curl_setopt($curl, CURLOPT_HTTPHEADER, array(

                                      'Content-Type: application/json',
                                      'Accept: application/json',
                                      'X-synctimeout: 30',
                                      'Authorization: Basic ' . $auth,
                                      'Content-Length: ' . strlen($data))
                                  );

                                    curl_setopt($curl, CURLOPT_POST, true);
                                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                                    curl_setopt($curl, CURLOPT_URL, $url);
                                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                                    $result = curl_exec($curl);


                                } catch(Exception $e) {
                                              echo '<p>There Was an Error Accessing the Webservice!!!</p>';
                                              echo $e->getMessage();
                                            }

                                    ?>




                    <!-- End of Search Wrapper -->

    <!-- Start of Page Container -->

            <div class="page-container">
                    <div class="container">

                            <!-- start of page content -->
                            <div class="span8 page-content">

                                            <!-- Basic Home Page Template -->

                        <div class="widget-area no-padding blank">
                            <div class="status-upload">
                                <form>
                                      <textarea class='mail' name="body" cols="50" rows="5" align="left">

                                      <?print_r(json_decode($result));?>

                                     </textarea>

                                </form>
                            </div><!-- Status Upload  -->
                        </div></div></div></div>

Extraction when run:

 {"question":{"qclasslist":[{"value":"DESCRIPTIVE"},{"value":"FOCUSLESS"},{"value":"DEFINITION"}],"focuslist":[{"value":"brent"}],"latlist":[{"value":"brent"}],"evidencelist":[{},{"value":"0.04949565976858139","text":" To achieve Community Care BLAHBLAHBLAH.........ETC

What i really want, is the string return (To achieve Community Care BLAHBLAHBLAH.........ETC)

I have improved the code and commented out $extract, confused me. i also changed the echo code into print_r(json_decode($result));

Extraction when run:

 stdClass Object

( [question] => stdClass Object ( [qclasslist] => Array ( [0] => stdClass Object ( [value] => DESCRIPTIVE )

                [1] => stdClass Object
                    (
                        [value] => FOCUSLESS
                    )

            )

        [evidencelist] => Array
            (
                [0] => stdClass Object
                    (
                        [value] => 0.48106712102890015
                        [text] => BLAH BLAH BLAH BLAH
                        [id] => 001
                        [title] => What is non-medical prescribing?
                        [document] => Post/question/djncjabuvas
                        [copyright] => "URL"
                        [termsOfUse] => "URL"

I am getting closer to my goal and just need help on just extracting the [Title] and [text] field, this is just a simple question and answer concept. Your help is greatly appreciated. I heard formattedAnswer would help but unsure if i declared it correctly.



via Chebli Mohamed

Add elements to existing array

I have an array that looks like this

array(3) {
      [0]=>
      array(4) {
        ["sort"]=>
        string(0) ""
        ["day"]=>
        string(2) "2"
        ["month"]=>
        string(1) "8"
        ["year"]=>
        string(4) "2015"
      }
      [1]=>
      array(4) {
        ["sort"]=>
        string(0) ""
        ["day"]=>
        string(1) "5"
        ["month"]=>
        string(1) "8"
        ["year"]=>
        string(4) "2015"
      }
      [2]=>
      array(4) {
        ["sort"]=>
        string(0) ""
        ["day"]=>
        string(1) "9"
        ["month"]=>
        string(1) "8"
        ["year"]=>
        string(4) "2015"
      }
    }

As you can see it consists of sort, date, month and year. I want to add new element into the same array with value "day" +1.

If the 8th of august 2015 is in array the it should also include 9th of august 2015. I need a way to extract values, calculate new date and put back in all dates. The result should look like this:

array(3) {
          [0]=>
          array(4) {
            ["sort"]=>
            string(0) ""
            ["day"]=>
            string(2) "2"
            ["month"]=>
            string(1) "8"
            ["year"]=>
            string(4) "2015"
          }
          [1]=>
          array(4) {
            ["sort"]=>
            string(0) ""
            ["day"]=>
            string(1) "5"
            ["month"]=>
            string(1) "8"
            ["year"]=>
            string(4) "2015"
          }
          [2]=>
          array(4) {
            ["sort"]=>
            string(0) ""
            ["day"]=>
            string(1) "9"
            ["month"]=>
            string(1) "8"
            ["year"]=>
            string(4) "2015"
          }
          [3]=>
          array(4) {
            ["sort"]=>
            string(0) ""
            ["day"]=>
            string(2) "3"
            ["month"]=>
            string(1) "8"
            ["year"]=>
            string(4) "2015"
          }
          [4]=>
          array(4) {
            ["sort"]=>
            string(0) ""
            ["day"]=>
            string(1) "6"
            ["month"]=>
            string(1) "8"
            ["year"]=>
            string(4) "2015"
          }
          [5]=>
          array(4) {
            ["sort"]=>
            string(0) ""
            ["day"]=>
            string(1) "10"
            ["month"]=>
            string(1) "8"
            ["year"]=>
            string(4) "2015"
          }
        }

Ideally it should also exclude new dates, if allready identical date is in the array.



via Chebli Mohamed

When echoing out html tags the output prints out everything

I want to apply the html tags to the variable.

Code: echo '<strong>'.$message['sender'].' Sent'.'</strong>';

Output: <strong>The actual message Sent</strong>

Desired output: The actual message Sent

How can i apply the strong class to the $message variable?

Full context code::

<textarea name="message" disabled  rows="6"  style="resize:none;" placeholder="Loading...">
<?php
    $messages = get_msg();
    foreach($messages as $message){
        echo '<strong>'.$message['sender'].' Sent'.'</strong>';
        echo $message['message'].'<br/><br/>';
    }

    if(isset($_POST['send'])){
        if(send_msg($_POST['sender'],$_POST['message'])){
            echo 'Message Sent.';
        }else{
            echo 'Message failed to send';
        }
    }
?>
</textarea>



via Chebli Mohamed

Warning: session_start() [function.session-start] headers already sent [duplicate]

This question already has an answer here:

I have my Opencart webshop updated to the latest version.. Now I get the following error on the admin page.

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/barbecue/domains/http://ift.tt/1P3G0oh) in /home/barbecue/domains/http://ift.tt/1hhxh6P on line 17

What should I do?



via Chebli Mohamed

Installing Composer on Windows 7 using windows installer

I've been trying to install Composer for a while now and still I could not figure out what I am doing wrong. First I installed WAMP Server 2.5(Windows 7 64-bit), then downloaded and run Composer-Setup.exe, installed shell Menus .

I chose this path C:\wamp\bin\php\php5.5.12\php.exe

But once I clicked next I bumped into this:

Please review this settings PHP version 5.5.12

C:\wamp\bin\php\php5.5.12\php.exe.

Which settings should I use instead? When I try to run composer it does start but then shuts down immediately.



via Chebli Mohamed

Wordpress get_permalink doesn't work [on hold]

EDIT: No idea what's unclear in my question. It's simple - I need my blog posts to be openable by clicking post image or post title. The question is - how do I do that if get_permalink doesn't work? There's no way to describe it simplier...


I've got some trouble with unclickable images and post titles in my Wordpress blog template. Get_permalink doesn't work (according to what I've read it's because that function should be in loop.php but my template doesn't have that file).

The weird thing is, there's a "read more" link under each post and it has get_permalink attribute - and it works, but when I try to make post image or title clickable the same way, nothing changes. It's a little annoying when people can't open blog posts by clicking on image or header :(

Could you help me with that?

Here's the list of files my template contains, maybe that will be helpful?

404.php

bootstrap_tests.php

class.redux-plugin.php

index.php

kill-travis.php

redux-framework.php

uninstall.php

archive.php

author.php

category.php

comments.php

content-audio.php

content-gallery.php

content-quote.php

content-video.php

content.php

footer.php

class-tgm-plugin-activation.php

color.php

post_type.php

wp_bootstrap_navwalker.php

functions.php

header.php

index.php

(page-templates/alt-header.php)

(page-templates/blog-timeline.php)

(page-templates/blog1.php)

(page-templates/blog2.php)

(page-templates/blog_sidebar1.php)

(page-templates/blog_sidebar2.php)

(page-templates/blog_sorting.php)

(page-templates/template-canvas.php)

(page-templates/template-portfolio.php)

page.php

search.php

shortcodes.php

sidebar-footer.php

sidebar.php

single-portfolio.php

single.php

tag.php

vc_shortcode.php

vc_column.php

vc_row.php

vc_tab.php

vc_tabs.php

Style

style.css

rtl.css



via Chebli Mohamed

How to use /dev/urandom with PHP to get CS random numbers

I need to create random integers between the values of 0 and 10,000,000, and I will need several million such numbers. The numbers must be as close to a CSPRNG as possible in that should (for example) someone get to read, so 1 million out of 2 million such numbers that they would find it impracticable to work out the remaining 1 million numbers.

After some research I’ve come to the conclusion that with the tools I have available, (Unix/PHP) using /dev/urandom will be my best bet.

I came across this solution:

// equiv to rand, mt_rand
// returns int in *closed* interval [$min,$max]
function devurandom_rand($min = 0, $max = 0x7FFFFFFF) {
    $diff = $max - $min;
        if ($diff < 0 || $diff > 0x7FFFFFFF) {
        throw new RuntimeException("Bad range");
        }
        $bytes = mcrypt_create_iv(4, MCRYPT_DEV_URANDOM);
    if ($bytes === false || strlen($bytes) != 4) {
        throw new RuntimeException("Unable to get 4 bytes");
    }
    $ary = unpack("Nint", $bytes);
    $val = $ary['int'] & 0x7FFFFFFF;   // 32-bit safe
    $fp = (float) $val / 2147483647.0; // convert to [0,1]
    return round($fp * $diff) + $min;
}

Source: http://ift.tt/1Dq2oqK

Given that I need to create a large amount of random numbers, would I be better piping /dev/urandom to a file(s), and then read 3 bytes (2^24 = 16 million) at a time and convert to integer?

Is either solution suitable for my needs?



via Chebli Mohamed

how to find out missing date in mysql using php

How to find out missing date in MySQL using PHP?

echo "<tr> <th>Username</th><th>Date</th><th>Check In</th><th>Check Out</th> </tr>";

// get results1 from database 
$result1 = mysql_query("SELECT * FROM attend WHERE user_name='ali' AND date BETWEEN '2015-07-01' AND '2015-07-15' order by date");

while($row = mysql_fetch_array($result1))
{   
    // echo out the contents of each row into a table
    echo "<tr>";
    echo '<td>' . $row['user_name'] . '</td>';
    echo '<td>' . $row['date'] . '</td>';
    echo '<td>' . $row['checkin'] . '</td>';
    echo '<td>' . $row['checkout'] . '</td>';
    echo "</tr>";    
}
echo "</table>";

currently result

Username    Date    Check In    Check Out
ali     2015-07-01  11:30:34    17:23:47
ali     2015-07-02  10:11:34    17:15:15
ali     2015-07-03  09:32:34    18:16:27
ali     2015-07-06  10:41:34    16:56:13
ali     2015-07-07  08:51:34    17:36:01
ali     2015-07-08  05:61:34    17:16:26
ali     2015-07-09  04:11:34    17:14:12
ali     2015-07-10  02:81:34    17:25:25
ali     2015-07-13  11:71:34    17:02:29
ali     2015-07-14  10:81:34    17:04:20
ali     2015-07-15  09:31:34    17:00:43

and i want result like this

Username    Date    Check In    Check Out
ali     2015-07-01  11:30:34    17:23:47
ali     2015-07-02  10:11:34    17:15:15
ali     2015-07-03  09:32:34    18:16:27
        2015-07-04
        2015-07-05
ali     2015-07-06  10:41:34    16:56:13
ali     2015-07-07  08:51:34    17:36:01
ali     2015-07-08  05:61:34    17:16:26
ali     2015-07-09  04:11:34    17:14:12
ali     2015-07-10  02:81:34    17:25:25
        2015-07-11
        2015-07-12
Ali     2015-07-13  11:71:34    17:02:29
ali     2015-07-14  10:81:34    17:04:20
ali     2015-07-15  09:31:34    17:00:43



via Chebli Mohamed