mardi 4 août 2015

How to add "you save" option in the shopping cart of opencart?

I am trying to create a you save option in the shopping cart of opencart.com. I have done the same feature of you save to be displayed in the product page using vqmod. But i am finding it difficult to do it for the shopping cart. here is my vqmod code for adding you save option in the product page.

<modification>
    <id><![CDATA[@tik Savings Note]]></id>
    <version><![CDATA[1.1]]></version>
    <vqmver><![CDATA[2.1.7]]></vqmver>
    <author><![CDATA[OC2PS]]></author>
    <file name="catalog/view/theme/default/template/product/product.tpl">
        <operation>
            <search position="before" offset="2" error="log"><![CDATA[<?php if ($tax) { ?>]]></search>
            <add><![CDATA[<br /><span class="you-save" style="color:red;"><?php echo $text_yousave; ?> <?php echo $yousave; ?></span>]]></add>
        </operation>
    </file>
    <file name="catalog/language/english/product/product.php">
       <operation>
            <search position="replace" error="log"><![CDATA[// Entry]]></search>
            <add><![CDATA[$_['text_yousave']        = 'You save:';// Entry]]></add>
       </operation>
    </file>
    <file name="catalog/controller/product/product.php">
        <operation>
            <search position="replace" error="log"><![CDATA[$data['text_tax'] = $this->language->get('text_tax');]]></search>
            <add><![CDATA[$data['text_tax'] = $this->language->get('text_tax');
                 $data['text_yousave'] = $this->language->get('text_yousave');]]></add>
        </operation>
        <operation>
            <search position="replace" error="log"><![CDATA[$data['special'] = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));]]></search>
            <add><![CDATA[$data['special'] = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));
                $data['yousave'] = $this->currency->format($this->tax->calculate($product_info['price']-$product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));
                $data['yousavepercent'] = round(($product_info['price']-$product_info['special'])*100/$product_info['price'],0);]]></add>
        </operation>
        <operation>
            <search position="replace" error="log"><![CDATA[$special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));]]></search>
            <add><![CDATA[$special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
                    $yousave = $this->currency->format($this->tax->calculate($result['price']-$result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
                    $yousavepercent = round(($result['price']-$result['special'])*100/$result['price'],0);]]></add>
        </operation>        
    </file>
</modification>

Signing JSON objects

I have to exchange JSON objects between different platforms and implementations of a service and make its integrity verifiable via digital signatures. So a platform A would create such an object and create a digital signature. Said signature is then included into the object and sent to platform B. The JSON objects can contain arbitrary attributes and data.

E.g. in PHP:

function signObject($jsonObjectToSign, $privateKey) {
    $jsonObjectToSign->signature = "";
    $msgToSign = json_encode($jsonObjectToSign);

    openssl_sign($msgToSign, $jsonObjectToSign->signature, $privateKey, OPENSSL_SLGO_SHA1);

    return $jsonObjectToSign;
}

Problem is, that e.g. in Java, there is no way to tell whether the attributes of a JSON object will be in the same order you added them (via JSONObject.put()). So, if I do a

$json = json_encode('{"a":1, "b":2}');

in PHP, sign this object as stated above, transfer it to a java based server, decode the json object and then try to verify the signature, I'd probably get a different order of the object's attributes.

So what I need, is a reliable way to create a String from a JSONObject, independent of the language or platform used.

The example object above needs always to output {"a":1, "b":2} and NEVER {"b":2, "a":1}. Unfortunately, this is the usual case e.g. in Java.

Is there any "best practice" to sign JSON Objects in a secure way?

But let me describe the problem in another way:

Let's say I want to do this in Java (or any other language):

JSONObject j = new JSONObject();
j.put("a", 1);
j.put("b", 2);

Now, I need a serialization function, that outputs always the same string representation for this object, no matter how and with what language this object is created.

MySQL trigger: updating column depending of a submitted value

Ths my trigger but it doesn't work.

CREATE TRIGGER events_events_a BEFORE INSERT ON events_events
FOR EACH ROW
BEGIN 
IF NEW.public = 1 THEN
UPDATE events_cats SET etotal=etotal+1, etotal_NEW.region=etotal_NEW.region+1 WHERE id=NEW.category;
END IF;
END;

I need to update column depending of a submitted value.

if NEW.region value is 1, I need to update column etotal_1=etotal_1+1
if NEW.region value is 2, I need to update column etotal_2=etotal_2+1
if NEW.region value is 3, I need to update column etotal_3=etotal_3+1

etc. Is there any way how to update column depending of NEW.region value?

How to write NULL instead of 0 when I leave a field empty

I have a problem with inserting data. When I leave a field empty then he writes a 0 in my db instead of 0. What I have to do that he writes NULL.

<?php

if ($date == '' || $name_home == ''|| $name_away == '')
{

$error = 'Please enter the details!';

valid($date, $name_home, $name_away, $score_home, $score_away, $error);
}
else
{

mysql_query("INSERT name_matches SET date='$date', name_home='$name_home', name_away='$name_away', score_home='$score_home', score_away='$score_away'")
or die(mysql_error());

header("Location: view.php");
}
}
else
{
valid('','','','','','');
}
?>

Divs, including php to appear next to each eachother

Using Bootstrap to layout the page and at first I had images in a grid, like on Facebook, there were 4 in a row and as the page shrunk so did the number of images in a row. Now I have added php so it is easier to update the page but the images all appear under each other. How can I have it the way it was?

Code used:

<section  id="alf40">
   <div class="container-fluid no-padding ">
<div class="row">

        <div class="col-lg-3 col-md-4 col-xs-6 thumb" style="display:inline-block; float:left; position:relative;" >
        <?php $SQL = "SELECT * FROM nw_photo";
        $result = mysql_query($SQL);
        while ( $db_field = mysql_fetch_assoc($result) ) { ?>

            <a class="thumbnail" href="#"><img class="img-responsive" src="
    <?php echo $db_field['image']; ?>" style="display:inline-block; float:left; position:relative;">
            <?php } ?></a>
        </div>

</div>
</div>
  </section>

Alternative to strtotime() in MySQL

I have an EventSet table with those fields:

  • start_day (ex. Monday)
  • start_time (ex. 14:20:00)

I want to create a query that selects specific records by comparing their day an time with the current ones.

So, using a little help from the PHP's strtotime() method I am aiming at something similar to:

SELECT * 
FROM 
   `EventSet` 
WHERE 
    DATE_FORMAT(NOW(), '%W %H:%i:%s') <= 
    date('%W %H:%i:%s', strtotime('start_day start_time'))

*the last date() part is of course pure PHP


So far I've tried using DATE_FORMAT with CONCAT_WS and also TIMESTAMP() / UNIX_TIMESTAMP() but am clearly messing something up.

SELECT * 
FROM 
    `EventSet` 
WHERE 
    DATE_FORMAT(NOW(), '%W %H:%i:%s') <= 
    DATE_FORMAT(CONCAT_WS(' ', start_day, start_time), '%W %H:%i:%s')

I've looked through many similar questions here and in the net, but they all already have a date field to work with and there's no need to concatenate anything, so I can't use any of them.

How to access protected variable form given response [duplicate]

This question already has an answer here:

I want to retrieve _href:protected from given response but i don't know How i can access it .

 Recurly_Subscription Object
(
    [_values:protected] => Array
        (
            [subscription_add_ons] => Array
                (
                )

            [account] => Recurly_Stub Object
                (
                    [objectType] => account
                    [_href:protected] => http://ift.tt/1MJI9ao
                    [_client:protected] => Recurly_Client Object
                        (
                            [_apiKey:Recurly_Client:private] => 
                            [_acceptLanguage:Recurly_Client:private] => en-US
                        )

                    [_links:protected] => Array
                        (
                        )

                )






)
)

i try $sub->account->href for account href but not success. Please provide solution .

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

Codeigniter Deprecated: mysql_real_escape_string():

Got below error while using codigniter 3.0

FYI using PHP Version 5.5.12,Apache Version Apache/2.4.9 (Win64) PHP/5.5.12

A PHP Error was encountered

Severity: 8192

Message: mysql_real_escape_string(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

Filename: models/common_model.php

Line Number: 21

Backtrace:

File: C:\wamp\www\Codeigniter\application\models\common_model.php Line: 21 Function: mysql_real_escape_string

get total price of configurable product according to size swatch

I am new in magento.I have created a store and managed some configurable products in it.What I want to do now is show total price in the size swatch dropdown but in default magento gives the individual size price in the dropdown with + or - sign with it.Can anyone suggest me any idea so i can show total price instead of unit price?Any help is appreciated!!Thanks

Wordpress get_permalink doesn't work

I've got some trouble with unclickable images and post titles in my Wordpress blog template. Get_permaling 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

DRAG and DROP file upload work like multiple file upload

I want to make a form with informations such as "name, type, etc.." and i want to make a 'Drag and Drop' image uploader with click fuction. SO drag and drop or click to select the images. Max is 5 images. I found some script and divs but it alway upload the file whzen you drag and drop it or choose it. I want to submit the upload with the whole form, because it is connected to a mysql database. I did't find a solution for this.

Getting date value with find() and Checking if the date is < 30 mins

I try to make an app. that sends e-mail to the user. Whenever i run the code, the current time and date is saved to the database under the name of "created" (column). There are 2 conditions. I could make the first one in that if loop. Second condition is sending e-mail after 30 mins from the previous e-mail. To do this, I try to get those saved values by using find() and compare them to do 30 mins condition. (Btw I am very newbie at programming. I ve been learning for 3 weeks)

Here is the code;

class TemperatureReading extends AppModel {

    function afterSave($created, $options = array()) {

    $temperature = $this->data['TemperatureReading']['temperature'];

    $result = $this->Location->find('first' , array(
            'conditions' => array(
                    'Location.id' => $this->data['TemperatureReading']['location_id']
            )));

    $high_threshold = $result['Location']['high_threshold'];

    $low_threshold = $result['Location']['low_threshold'];

    $created = $this->data['TemperatureReading']['created'];

    $id = $this->data['TemperatureReading']['id'];

    $models_Temp_Loc = $this->find('first' , array(
            'conditions' => array(
                    'TemperatureReading.id' => $id
            )));

    $prev_created_time = $models_Temp_Loc['TemperatureReading']['created'];

// The part, where I have problems. I want to get the values of created (time and date) and compare them to check 30 mins condition. (ex: Assume that app. ran and e-mail sent for the first time at specific time. The application can be run 100 or 241 or 4144.. times in 10 mins after the first e-mail, so there are many date and time data saved in created in 10 mins to be compared for 30 mins condition.)

    $deneme = $this->find('all' , array(
        'conditions' => array(
                'created.id' => $id
                ), 
                    'condition' => array(
                        'created' <30
                )));

    //The part where i can make the first condition without problem

    if ($temperature > $high_threshold || $temperature < $low_threshold) {

        $Email = new CakeEmail('gmail');
        $Email->from(array('xxxxxxx@gmail.com' => 'My Site'));
        $Email->to('xxxxxxxxxx@gmail.com');
        $Email->subject('Temperature Warning!');
        $Email->send('Temperature is at critical value of');

    }

Excuse me for any meaningless things, i am very noob and trying to do hard things.

This is what goes on there without $deneme (wrong part). for every id, there is a date and time to be compared for the 30 min condition.

Temperature is: 12
High_threshold is: 90
Low_threshold is: 0
Created is: 2015-08-04 14:47:52
Id is: 340

Array
(
    [TemperatureReading] => Array
        (
            [id] => 340
            [created] => 2015-08-04 14:47:52
            [temperature] => 12
            [location_id] => 1
        )

    [Location] => Array
        (
            [id] => 1
            [name] => Spor Salonu
            [high_threshold] => 90
            [low_threshold] => 0
            [send_warning_to] => onurcucen@gmail.com
        )

)

2015-08-04 14:47:52

ty for any possible recommendations, comments, answers.

PHP - How to merge foreach arrays into one loop

Here is my code:

$url = "http://ift.tt/1IDweUE";

libxml_use_internal_errors(true); 
$doc = new DOMDocument();
$doc->loadHTMLFile($url);

$xpath = new DOMXpath($doc);

$n = $xpath->query('//td[@data-column-name="Model"]');
$r = $xpath->query('//td[@data-column-name="RAM"]');

foreach ($n as $entry) {
    $Name = $entry->nodeValue;
    $RAM  = $r->nodeValue;
    echo " $Name - RAM: $RAM<br>";
}

I successfully echo $Name but i can not get the value for $RAM because i do not have it in my array. My question is how i can add $r into this foreach loop and make it work ?

Thanks in advance!

How to use Different Button in bootstrap Form

i have used Bootstrap and created form.my form Looks like

  <form action="default_results.php"   method="post" class="calculator"  name="frmCalculator">  

i have put this code begin of the code and end of the page i have used three button Looks like

                            <button id="button2" class="dont-compare shadow-inset" value="reset" >
                                    Reset</button>
                            <button id="button3" data-toggle="pop" class="dont-compare shadow-inset" class="update" >
                                    Update MI</button>
                            <button id="Button4"  class="dont-compare shadow-inset" class="calculator" >
                                    Calculate Scenarios</button>
                        </div>

i have another page its called default_ results.php page. i want load that page when i click Calculate Scenarios button . i used href tag that button. but that three button also load default_results page. how to set particular button? please any idea about it?

Redis scan skipping keys

I'm using predis (with laravel if it makes any difference) php client to work with Redis.

I need to fetch all the keys from Redis that match certain prefix and I do it like this:

$keys = [];
    foreach (new Iterator\Keyspace($this->redis(), Cache::KEY_PREFIX.'*') as $key) {
        $keys[] = $rate_key;
    }

After the work with those keys is done, operation repeats - I'm getting those keys again in again in a loop. I noticed that after a few iterations some keys are not included in $keys array.

The strangest thing is that keys that disappear never appear in next iterations. Restart of the php process (it's a daemon) fixes the problem.

I'm using Redis 3.0.2 with Predis 1.0 and PHP 5.4

P.S. Within the loop over keys, I change values for some of them. I'm not deleting any keys, however.

How to upload image and save URL in database in php

In this php code i want to customize the image upload destination. with this php file, i have directory called uploads. i want to add all my uploaded images to this directory and store path in db. how can i do this?

<?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "image_upload";
$username_connect= "root";
$password_connect= "";

$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR); 
@mysql_select_db($database_connect) or die (mysql_error()); 

if($_POST) { 
    // $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.

    if ($_FILES["file"]["error"] > 0) {
        // if there is error in file uploading 
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

    } else {
        // check if file already exit in "images" folder.
        if (file_exists("images/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " already exists. ";
        } else {  
            //move_uploaded_file function will upload your image.  if you want to resize image before uploading see this link http://ift.tt/UVKZR0
            if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"])) {
                // If file has uploaded successfully, store its name in data base
                $query_image = "insert into acc_images (image, status, acc_id) values ('".$_FILES['file']['name']."', 'display','')";
                if(mysql_query($query_image)) {
                    echo "Stored in: " . "images/" . $_FILES["file"]["name"];
                } else {
                    echo 'File name not stored in database';
            }
       }
   } 

}
}
?>

currently when i run the upload i am getting warnings

Warning: move_uploaded_file(images/1409261668002.png): failed to open stream: No such file or directory in D:\xampp\htdocs\image-upload\index.php on line 29

Warning: move_uploaded_file(): Unable to move 'D:\xampp\tmp\php1C1F.tmp' to 'images/1409261668002.png' in D:\xampp\htdocs\image-upload\index.php on line 29

MySQL - One table of each client or Single table with all clients

I am beginning a project where there will be multiple clients. In the database, each client can potentially have hundreds of thousands of rows.

Instead of having all of the clients in a single table, would it make sense to split the clients so that each has their own table? To me this makes sense since each time you query for a client, you would only be looking up a table with their data.

POST a series of products in Laravel / PHP

I'm using Laravel to post a series of products. The user can choose a quantity of each product.

Now I'm wondering how I can post a series, but still have the names of the products.

I have tried the following.

This result gives me an undefined offset error

<input name="{{ $products[$product->id] }}" />

This result doesn't include the name, but does make it a series

<input name="products[]" />

Any idea how I might end up with an array that's called $products, and has all the products in there by name

How to package PHP code like jar or exe or dll?

How to package PHP code like jar in java or exe and dll in visual studio ?

such that when i host it my source code isn't directly available.

Access to config in static method

How can I get access to config in static method of controller? I have Phalcon 1.3 . This method is not working:

$offerSource = $this->config->offerSource;

How to create a tiny Prolog compiler?

Now, I want to create a very tiny Prolog compiler. But, I don't know much about a tiny compiler.

Can you help me to write a very tiny Prolog compiler? Please don't delete or close this question.

I will use your code for my private programming learning only. So, please keep your source code be private. (see at the end of this question: Note.)


Your own compiler must works as these features:

  • Simple as these code (http://ift.tt/1ImnCm8, or http://ift.tt/1KNGMqM) only: (as in Description section).
  • Allow space insensitive.
  • Some replaces for syntax rules:
    • Connection (is comma) (,) is replaced by star (*).
    • Djsjuntion (is semicolon) (;) is replaced by plus (+).
    • Rule (is :-) (:-) is replaced by colon (:).
    • Query/question (is ?-) is replaced by question mark (?).
  • Lexical scope: global.
  • Allow these variables: _ABC, abc, Abc ...
  • Allow use brackets (such as: ()) to change the order of precedence.
  • Cut and list are not required.
  • String type is not required.
  • Show all possible solution.

Your code must be:

  • Written in PHP, and compatible with PHP 4, PHP 5.
  • Please don't write your code in object oriented programming.
  • Your code be tested with QuickPHP).
  • Please don't test your code with online IDEs, such as: ideone.com, eval.in ...

Here is my own HTML interface:

<?php

$source_code_box = $_POST['source_code_box'];

?>
<form action="compiler.php">
<textarea name="source_code_box"></textarea>
<br />
<input type="submit" name="compile_button" />
</form>
<hr />
<?php

yourfunction($source_code_box);

?>


Here are some useful source code:


Sorry about my English, it is so bad. If my question is not clear, please comment bellow this question.


Note: Your complete source code must be uploaded, at here (http://ift.tt/1ImnBi6). Then, if your file is uploaded, it will return an MD5 string. Please copy this MD5 string, and paste it into Stack Overflow as your answer. I will read your code later, and give my own 500 score bounty for you.

Group Price not working in Bundle Products Magento

I am creating Simple and Bundle product programmatically using Magento, However Group Price is working perfectly in Simple Product but its not working when I create Bundle Product any idea why this happening?

If you have any code or if I am missing anything please guide me here is my code.

$groupPrices = array(

        array(
            'website_id' => 1,
            'cust_group' => 8,
            'price' => 10
        ),

        array(
            'website_id' => 1,
            'cust_group' => 6,
            'price' => 15
        )
    );

    $Product->setData('group_price', $groupPrices);

The above code working perfectly in simple product but not working in Bundle Product.

Thanks in advance

SonataAdminBundle, filtering by function result

In my Symfony project I'm using SonataAdminBundle. And I got a question: For example I have some entity with a function:

class Entity {
protected $id;

public idBiggerThan($value) {
     return $id > $value;
}

And I want to create a filter that filters list by the result of this function (for example to be able choose only entities that have id bigger that current user).

I understand that this filter can be written without using this function, but I have much more complex functions, for which I don't want to write queries.

Thanks for your help.

Laravel mail not sending

I'm trying to send an email to the website admin, but it isn't working as expected. I did this before, where the exact same code is working.. I'm using my gmail account to send emails with my Laravel application.

So my setup is as follows

'driver' => 'smtp',
'host' => 'smtp.gmail.com',
'port' => 587,
'from' => array('address' => 'postmaster@test.com', 'name' => 'Postmaster'),
'encryption' => 'tls',
'username' => 'xxx@gmail.com',
'password' => 'xxx',
'sendmail' => '/usr/sbin/sendmail -bs',
'pretend' => false,

The next thing I do is fill in a (test) form

{{ Form::open(array('id'=>'mail-form', 'url'=>'en/mail', 'method' => 'post')) }}
{{ Form::text('first_name', null , array('placeholder'=>Lang::get('quotation.first_name'), 'class'=>'text-input')) }}
{{ Form::text('name', null , array('placeholder'=>Lang::get('quotation.name'), 'class'=>'text-input')) }}
{{ Form::text('email', null , array('placeholder'=>Lang::get('quotation.email'), 'class'=>'text-input')) }}
{{ Form::submit(Lang::get('quotation.send'), array('class'=>'submit-mail')) }}
{{ Form::close() }}

This gets processed in my HomeController

public function postMail(){
    $input = Input::all();

    $data = array(
        'first_name' => $input['first_name'],
        'name' => $input['name'],
        'email' => $input['email'],
    );

    Mail::send('_emails.quotation', $data, function($message){
        $message->to($input['email'], $input['name'].' '.$input['first_name'])->subject('Test');
    });

    return Redirect::back();
}

When I submit the form I get a 302 found HTTP code, which then directly redirects me to the homepage..

Check if FORMAT is valid based on a pattern list

Using URLs.. I have a list of acceptable url formats, like this:

  1. domain.com/test
  2. domain.com/test/
  3. http://ift.tt/1ImnCm4
  4. http://ift.tt/1KNGNLw

User input this http://ift.tt/1ImnB1C will return True based on my #3 entry at url format list..

The user input something like http://ift.tt/1KNGNLy return false.. domain.com/ return false, because does not match with any entry of my format list.

whats the best way to do this?

edit: im not trying to check if url is valid! i'm trying to check if FORMAT is valid based on my pattern list..

How do I resize a page scraped with cURL?

I have an html page built with Bootstrap, in which there's a panel that occupies 6/12 of the screen size; this panel is in the center of the page, and has a 3/12 panel on each side.
At the same time, I have a cURL and PHP script that scrapes a web page, given a link by the user, and shows it in the panel described above; this script gets all the page content (images, text, code, scripts, etc.) and has (at the moment) the simple task of showing it inside the panel.

Everything is fine about that: the page is showed, and only Google homepage has some problems, related to the complexity of the scripts going on there (and some security measures by Google to prevent phishing and so, I suppose).
The problem is that the page does not fit correctly inside the panel: it starts where it should, but it seems impossible to resize it in order show it all in the panel: it exceeds the right and bottom border.
The only way I know to resize the page is through CSS (applied to the panel content), but it doesn't work; I tried many possibilities (margins, width and heigth, paddings, etc.) but I am unable to make it fit.

I'm beginning to think that I need to add some resize function inside the script, but considering that the user may enter any address, it's kinda impossible to create a specific function to deal with that... do you have any idea?

Preg_Match PHP Script not working

I have been referring to the PHP Manual and other sites to build this but cannot seem to get it working even though I have checked the source of the site that contains a link to externally hosted jquery file by Google so a match should be found.

I did check the regex to make sure it correctly picks up script links within the HTML but it just does not want to match it with the $sign (Signatures) that I am hoping it would match.

$regex = "/<script.+src=\"(.+)\"><\/script>/i";
$site = file_get_contents("http://ift.tt/18qQonn");
$sign = 'jquery';
$sign = 'jQuery v2.1.3';

if (preg_match($regex, $site, $sign)) {
    echo 'A match was found.';
} else {
    echo 'A match was not found. boo boo';
}

What am i doing wrong could you please advise? Thanks for your help in advanced.

Best way to handle static text / messages in PHP OOP project (JSON maybe?)

Until now, unless I made a multilingual website (where I would use .mo & .po files), all the text would be scrambled all around the template and / or class files. Instead, I would like to store all static text in a file that is easily editable by my coworkers and clients (that rules out database storage and POedit).

I made a JSON file that stores the messages / static text like this:

{
  "titles": {
    "main_title": "This is the main title of the website",
    "login_page_title": "Please, sing in",
    "about_page_title": "About us"
  },

  "errors": {
    "empty_required_field": "This field is required.",
    "database_connection_error": "Couldn't connect to the database.",
  }

}

Then I import it in the index.php file:

$messages = json_decode(file_get_contents("messages.json"));

And use it like:

echo($messages->titles->main_title);

Which has been working so far so good (although I'm uncertain that there aren't better ways to archieve this). At least in the template pages where everything is html with minimal logic.

But I'm having trouble using the strings from the JSON file inside the classes' functions. I would like to use the error messages when throwing exceptions, for example. But I'm quite reluctant about stating "global $message" in every function where it's used (feels repetitive). Also everybody says that globals are naughty.

So my questions are two:

1) Is the JSON file a good way to handle my problem? (and if not, why, and which method would be better?).

2) How could I retrieve the stored strings from inside the classes? I'm thinking something like extending the Exception class to include the error messages, but I'm unsure of how to do it.

Thanks in advance for your help.

Special charecters doesn't work

I have a webpage with the special charecters working on: http://ift.tt/1E61zyg

But with the exactly the same code on another page it does not work: http://ift.tt/1M8TgtG

I know that there is a solution where i can put code in that makes the charecter, such as Ø, Å etc.

But i want to avoid using these since it would take a long time to switch out all "æ, ø, å" charecters with the codes.

My charset is defined in my .htacces file, which looks like this;'

DirectoryIndex index.php index.html index.htm

Options -Indexes
Options +FollowSymlinks

<Files .htaccess>
deny from all
</Files>

php_value include_path ".:/usr/www/gtgmodweb/public/inc"

ErrorDocument 404 http://ift.tt/1M8TiBz
ErrorDocument 403 http://ift.tt/1E61zyk



<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On 
# Default directive
ExpiresDefault "access plus 1 month"
# Images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
# CSS
ExpiresByType text/css "access plus 1 month"
# Javascript
ExpiresByType application/javascript "access plus 1 year"
</IfModule>

AddDefaultCharset iso-8859-1

Header unset ETag
FileETag None

If anyone has a clue on what causes the page to not displaying the charecters correctly, then please help me solving it!

Magento: How can I get at all the cart data from the form_key

I have added a form onto the bottom of the cart page, and changed the cart page to redirect to my own custom page.

This custom page currently just outputs the submitted data from the previous page, like so: print_r($_POST);

This produces the following output:

Array
(
    [form_key] => 2AJOmd7GhFVICntG
    [cart] => Array
        (
            [20] => Array
                (
                    [qty] => 1
                )
        )
)

So my question is, how can I get at all the cart data from the form_key.

A solution in pure PHP would be preferable. This is Magento 1.9.x.

MySQL UPDATE query syntax error

I have this simple code and for some reason it doesn't work.

$query_2 = mysql_query("UPDATE movimenti
                        SET
                        movimenti.id_dentista = $hidden_id_dottore,
                        movimenti.id_trattamento = $hidden_id_tratt,
                        movimenti.id_cliente = $hidden_id_paz,
                        movimenti.movimenti = $movimento
                        WHERE movimenti.id = $id")
                        or die(mysql_error());

this is the error about the query:

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE movimenti.id = '79'' at line 7"

Laravel Excel Download using Controller

So I created a PHP Controller to handle exporting data which is posted by JS. The problem is I can see it creates something in the console but the file download never starts. I tried using ->store (laravel excel) and keeping it in an export folder but again when I try to use

return \Response::download($result);

it still won't start the download. The problem I'm having is just getting the download to start.

Angular Controller

$scope.exportMatrix = function () {
    var postData = {list: $scope.list, matrix: $scope.matrix};
    $http({
        method: 'POST',
        url: '/export',
        dataType: 'obj',
        data: postData,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function (data) {
        console.log(data);
    }).error(function (data) {
        console.log("failed");
    });
}

Route

Route::post('/export', 'ExportController@export');

PHP Controller

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App;
use Excel;
use Response;
class ExportController extends Controller {

public function export()
{

    $excel = App::make('excel');

    Excel::create('Test', function($excel) {
        $excel->setTitle('new awesome title');

        $excel->sheet('Sheet', function($sheet) {
            $sheet->fromArray(array(
                array('data1', 'data2'),
                array('data3', 'data4')
            ));
        });


    })->export('xlsx');
}

several doubts about node.js and php

In my case i'm making something like this :- http://ift.tt/1ImnC5F

Not that website , i'm talking about the diagram. In my case i will have a page where a client can buy access to some service (done in node.js ). Each user buying service will be assigned a new node.js script file. So what to use in this case ? I want to dynamically add more and more node.js scripts and it should be controlled by a webpage where user can login

What i came across is something like this :- service1.myaddress.com service2.myaddress.com

I think this isn't efficient , cause i can have 100s of service page

2) If you ask me to use php , then how to make node.js and php call each other? I came across Dnode but i have no idea if that is effective in my case or not.

3) While reading a source code of php and node.js script, i came across this :-

In node.js script :-

var url = 'http://'+name+'/exec.php';
request(url, function(err, response, body){});

And that exec.php contains some imp functions , is this is how we are supposed to call a php function from node.js ? and what if a random unauthorized client visits http://'+name+'/exec.php , will that function in the exec.php will be executed ?

jQuery AJAX not working on Firefox

I have a function and an AJAX call. After clicking it gets the function and function works fine, on alert it shows the data, but after that it does not send the data to PHP. Any ideas why this happens on Firefox? It works well in IE and Chrome.

function siparisolustur() {
    var toplamsiparis = $('.urunrow').length;
    var i = null;
    var siparisid = $("#siparis_id").text();

    var name = $("#siparisad").val();
    var surname = $("#siparissoyad").val();
    var tel = $("#siparistel").val();
    var adres = $("#sepetadres").val();
    var semt = $("#sepetilce").val();
    var sehir = $("#sepetsehir").val();
    var notlar = $("#siparisnotu").val();
    var odeme = $('input[name="odemeyontemi"]:checked').attr("id");

    bilgiDataString = '&siparisid=' + siparisid + '&name=' + name + '&surname=' + surname + '&tel=' + tel + '&adres=' + adres + '&semt=' + semt + '&sehir=' + sehir + '&notlar=' + notlar + '&odeme=' + odeme;

    alert(bilgiDataString);

    $.ajax({
        type: "POST",
        url: "http://ift.tt/1DpLDvA",
        data: bilgiDataString,
        cache: false,
        success: function (html) {

        }
    });

    $("#payForm").submit(function (e) {
        var siparisdurdur = 0;
        var ad = $("#siparisad").val();
        var soyad = $("#siparissoyad").val();
        var tel = $("#siparistel").val();
        var adres = $("#sepetadres").val();
        var ilce = $("#sepetilce").val();
        var sehir = $("#sepetsehir").val();
        var sepeturunadetget = parseInt($("#sepeturunsayisi").text());

        if (ad == "" || soyad == "" || tel == "" || adres == "" || ilce == "" || sehir == "" || sepeturunadetget < 1) {
            siparisdurdur = 1;
        }

        if (ad == "") {
            e.preventDefault();
            $("#siparisad").css("border-    color", "#cd2828")
        } else {
            $("#siparisad").css("border-color", "#d1d2e6");
        }
        if (soyad == "") {
            e.preventDefault();
            $("#siparissoyad").css("border-color", "#cd2828")
        } else {
            $("#siparissoyad").css("border-color", "#d1d2e6");
        }
        if (tel == "") {
            e.preventDefault();
            $("#siparistel").css("border-color", "#cd2828")
        } else {
            $("#siparistel").css("border-color", "#d1d2e6");
        }
        if (adres == "") {
            e.preventDefault();
            $("#sepetadres").css("border-color", "#cd2828")
        } else {
            $("#sepetadres").css("border-color", "#d1d2e6");
        }
        if (ilce == "") {
            e.preventDefault();
            $("#sepetilce").css("border-color", "#cd2828")
        } else {
            $("#sepetilce").css("border-color", "#d1d2e6")
        }
        if (sehir == "") {
            e.preventDefault();
            $("#sepetsehir").css("border-color", "#cd2828")
        } else {
            $("#sepetsehir").css("border-color", "#d1d2e6")
        }
        if (blocksubmit == 1) {
            e.preventDefault();
            $("#personalinfosubmit").fadeOut("fast").fadeIn("fast").fadeOut("fast").fadeIn("fast");
        }
        if (sepeturunadetget < 1) {
            e.preventDefault();
            $("#shoppingcost").css("color", "#cd2828");
            $("#shoppingcost").fadeOut("fast").fadeIn("fast").fadeOut("fast").fadeIn("fast");
        }

        if (blocksubmit == 0 && siparisdurdur == 0) {
            siparisolustur();
        }
    });

php composer installing the whole source code and extra files

I'm totally new to composer and read the whole manual and started using it, but there is this thing that I can't figure it out. when I run the command

composer require example/example

ok, composer downloads the source code of library, but it has downloaded the WHOLE source code including the samples, readme, test files, anything. I plan to use many libraries and I don't want extra files to reside on my server.

How can I get rid of extra files composer downloads??

how to delete member from chat room xmpp server via php

I am trying to delete a member of chat room from XMPP server via php. I am using curl request for that.

I am following this documentation: http://ift.tt/1ImnAL8

$url = "http://ift.tt/1KNGMag".$roomName."/members/".$userJID;
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/xml", "Authorization : ******")); //I am using plugin.userservice.secret key here
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");    
    $json_response = curl_exec($curl);

        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

It should return me http response 201, but I am getting login form of server in response or 401 (unauthorized user).

I am trying to do this since last one week, but did not get any solution of this till, please help me.

Thanks in advance for your kind support.

Email Form Not Sending Message - HTML

I have this email code from a website template that I want to use for my site. The problem is that when I click on the "Send message" button, the form simply refreshes and nothing is sent. If there is any text data in the fields, it simply disappears. I have tried to look at possible solutions from this HTML Email Form Not Sending Message but to no avail.

Form HTML

<form name="sentMessage" id="contactForm" method='post' novalidate action="public_html/bin/contact_me.php">
   <div class="control-group form-group">
      <div class="controls">
         <label>Full Name</label>
         <input type="text" class="form-control" name="name" id="name" placeholder="Full Name" required data-validation-required-message="Please enter your name.">
         <p class="help-block"></p>
      </div>
   </div>
   <div class="row">
      <div class="col-md-6">
         <div class="form-group">
            <label>Email Address</label>
            <input type="email" class="form-control" name="email" id="email" placeholder="Email Address" required data-validation-required-message="Please enter your email address.">
         </div>
      </div>
      <div class="col-md-6">
         <div class="form-group">
            <label>Phone Number</label>
            <input type="tel" class="form-control" name="phone" id="phone" placeholder="Phone Number" required data-validation-required-message="Please enter your phone number.">
         </div>
      </div>
   </div>
   <div class="form-group">
      <label>Subject</label>
      <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required data-validation-required-message="Please enter your phone number.">
   </div>
   <div class="form-group">
      <label>Message</label>
      <textarea rows="10" cols="100" class="form-control" name="message" id="message" placeholder="Please Enter Your Message Here..." required data-validation-required-message="Please enter your message" maxlength="999" style="height:150px;"></textarea>
   </div>
   <div id="success"></div>
   <div>
      <button type="submit" class="btn btn-two">Send message</button>                          
      <p><br/></p>
   </div>
</form>

PHP Code

<?php
// check if fields passed are empty
if(empty($_POST['name'])        ||
   empty($_POST['phone'])       ||
   empty($_POST['email'])       ||
   empty($_POST['subject'])         ||
   empty($_POST['message'])         ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
    echo "No arguments Provided!";
    return false;
   }

$name = $_POST['name'];
$phone = $_POST['phone'];
$email_address = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

// create email body and send it    
$to = 'info@mywebsite.com'; // PUT YOUR EMAIL ADDRESS HERE
$email_subject = "$subject"; // EDIT THE EMAIL SUBJECT LINE HERE
$email_body = "You have received a new message from your website's contact form.\n\n"."Here are the details:\n\nName: $name\n\nPhone: $phone\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply@your-domain.com\n";
$headers .= "Reply-To: $email_address"; 
mail($to,$email_subject,$email_body,$headers);
return true;            
?>

Js

$(function() {

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // something to have when submit produces an error ?
            // Not decided if I need it yet
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var phone = $("input#phone").val();
            var email = $("input#email").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "./bin/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                cache: false,
                success: function() {
                    // Success message
                    $('#success').html("<div class='alert alert-success'>");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("<strong>Your message has been sent. </strong>");
                    $('#success > .alert-success')
                        .append('</div>');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-danger').append("<strong>Sorry " + firstName + " it seems that my mail server is not responding...</strong> Could you please email me directly to <a href='mailto:me@example.com?Subject=Message_Me from myprogrammingblog.com;>me@example.com</a> ? Sorry for the inconvenience!");
                    $('#success > .alert-danger').append('</div>');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});


/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});

How do I solve this?

How can I limit the number of images shown per page?

I have a certain number of images that are displaying per page. I want to set a maximum limit for the number of images shown on any page, for example setting a property such that no more than eight are shown. I've written this logic in PHP but I'm still seeing all images showing on any given page, ignoring any limit I set. The code:

$counter = 0;

foreach ($device as $value) {
  $entry = $value;
  echo "<head>";
  echo '<script type="text/javascript">',
           'window.setInterval(function() { ',
           "document.getElementById('$counter').src='/latimage.php?&dev=$entry&random='+new Date().getTime();",
           '},1000)',
       '</script>';
echo "</head>";
echo "<body onLoad='setTimeout('refresh()',1000)'>";
echo "<td>$entry<img id= '$counter'  width='100%'  height='auto'></img></td>";

$counter = $counter + 1;

if ($counter == 4 || $counter == 8) {
    echo " <tr>";
}

Magento 1.9 Logo not being displayed on Shipping PDF

When trying to print a delivery for an order in Magento the logo is not displaying. I have narrowed it down to the following line of code in app/code/core/Mage/Sales/Model/Order/Pdf/Abstract.php line 133 in the insertLogo() method.

$image = Mage::getStoreConfig('system/filesystem/media', $store) . '/sales/store/logo/' . $image;

I can't see that this option is being set anywhere and doesn't appear in the core_config_data table. Any ideas on getting this to work? Have I missed a configuration setting?

Symfony 2 not loading database config file

I'm new to symfony and im following the book with heroku as host, im trying to flush a object to database with doctrine but im getting the following error:

[2015-08-04 05:23:58] request.CRITICAL: Uncaught PHP Exception PDOException: "SQLSTATE[08006] [7] could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?" at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php line 40 {"exception":"[object] (PDOException(code: 7): SQLSTATE[08006] [7] could not connect to server: Connection refused\n\tIs the server running on host \"127.0.0.1\" and accepting\n\tTCP/IP connections on port 5432? at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:40)"} []

I got my configuration files working (i guess):

 parameters.yml
 database_host: host....
 database_port: 5432
 database_name: ddas1mq8intjqt
 database_user: ymmpjzoqbyokbr
 database_password: password.....
 mailer_transport: smtp
 mailer_host: 127.0.0.1
 mailer_user: null
 mailer_password: null
 secret: ThisTokenIsNotSoSecretChangeIt

and my config.yml:

doctrine:
    dbal:
        driver:   pdo_pgsql
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8

I've run the console commands to create the tables from the entity classes and it worked, but creating an object and ->flush seems the problem... don't know if its some server configuration or I've done something wrong.

Thank you

calculate sum of variables in a loop

I have the following task:

I have many equal tables of different people (>500) which contain working hours. The following is a sample:

"table01"

date | hours

"table02"

date | hours "table03"

date | hours .....

I have one table with relationship between tables to "cost-Center":

"table_cost-center"

table01 | 0010

table02 | 0030

table03 | 0020

table04 | 0040

table05 | 0060

......

I have to calculate the sum of hours between date 1 and date 2 of each cost-center in a loop. I need to display each sum of every single cost-center and calculate the total sum of all cost-centers together.

My Idea:

$whours= mysql_query ("SELECT sum(hours) FROM `$cost-center_tabelle[$z]` WHERE `$cost-center_table[$z]`.date BETWEEN '$date2' AND '$date1'

Assigning ID's to fields that are echoed using PHP inside a while loop

I currently have two dropdown menus that a user will select the course and a golfer which will load a scorecard.

What I am trying to do now is when a user enters a value into the "Score" field I want the "points" to be automatically shown ("Points" is a read only input field). To do this I am assuming that I will have to give each table row for score and points a specific ID.

echo "<div class='scorecardTable'>
<table 'id=scorecardTable'>
<tr>
<th>HoleNumber</th>
<th>Par</th>
<th>Stroke Index</th>
<th>Score</th>
<th>Points</th>
</tr>'";

while($row = mysqli_fetch_array($result)) { 
    echo "<tr>";
    echo "<td>" . $row['holeNumber'] . "</td>";
    echo "<td>" . $row['par'] . "</td>";
    echo "<td>" . $row['strokeIndex'] . "</td>";
    echo "<td> <input type='text' maxlength='2' id='score' /></td>";
    echo "<td> <input type='text' id='points' readonly></td>";
    echo "</tr>";
}
echo "</table>";

From the above code I am using PHP to print the information from my database but I was just wondering if anyone would know how to assign a unique ID to each of the score and points input fields so I can apply the calculation to each user input.

utf8 characters wrongly displayed as question marks after conversion to mysqli_query()

My database is latin1_swedish_ci but all the tables which contain foreign characters (german, turkish...) are utf8_general_ci.

Before the upgrade to php 5.6, I used mysql_query("SET CHARACTER SET utf8;");mysql_query("SET NAMES utf8"); before mysql_query() and everything was displayed correctly in my page ( in page header).

After the conversion of all mysql_query(...) to mysqli_query(id,...) and running under php 5.6, all the foreign languages are now scrambled with ? and �. Switching back to php 5.4 does not help. phpMyAdmin displays the mysql database (which has not changed) correctly.

I have looked around for a solution but nothing works... am I missing something?

What do I need to change in my code to work properly?

looping through xpath results

  1. I have gone to the db and created an array of url's.
  2. Then I go through the array and use xpath to tell me how many links there are per url.
  3. This is where my head hurts.

I have a count for each url of the no of objects in each url. So I'm now trying to collect each of the nodevalues from part 2.

I'm obviously doing something wrong but need some guidence please

 $items = array();
$query = "SELECT * FROM `urls`";
if( $result = mysqli_query($sql,$query));

  {
   // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);
 while ($row = $result->fetch_assoc()) {
   $items[] = $row;

 }

 }
    echo '<pre>';
    print_r($items);
  //  $product = array();
  echo $rowcount;

for ($x=0; $x<$rowcount; $x++){

  $scrapeurl[$x] = $items[$x][url];

   echo $scrapeurl[$x];

   $xpath[$x] = new XPATH($scrapeurl[$x]);


     $urls[$x] = $xpath[$x]->query("//div[@class='infodata']/strong/a[contains(@id,'test_title')]/@href");
$count[$x] = $urls[$x]->length;


   $data = array();
 for ($i=0; $i<$count[$x]; $i++){
  $data[$i]['url'] = $urls[$x]->item($i)->nodeValue;
    $data[] =  $data[$i]['url'];

   }

    echo '<pre>'; 
   print_r($data);

Why doesn't my submit button work?

The form is available when the user clicks a modal. When I click the submit button in the modal, it button does not work.

foreach ($posts as $post) { echo '
    <td>
      <button type="button" class="btn btn-success" data-toggle="modal" data-target="#$id_user">Validasi</button>
    </td>
  </tr>
</tbody>
';
}

Here is the modal:

echo '
<div id="$id_user" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content" id="registerContent">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <div class="modal-text-header text-center">Validasi</div>
      </div>
      <div class="modal-body">
        <div class="container-fluid">'; echo '
          <form class="form col-md-12 center-block" action="http://localhost/MMM/admin/validasi/'.$id_user.'" method="POST" enctype=\ "multipart/form-data\">
            <div class="form-group">
              <input class="form-control input" placeholder="Dana awal (RP.1.000.000,-)" type="text" name="dana">
            </div>
            <div class="form-group">
              <input type="submit" class="btn btn-primary btn btn-block" name="submit" value="Submit">
            </div>
          </form>
        </div>
      </div>
      <div class="modal-footer">
        <div class="col-md-12">
          <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
        </div>
      </div>
    </div>
  </div>
</div>' ;

Yahoo Callback Domain Issue

While creating a new app on Yahoo Developers Network the field (i.e. Callback Domain) is not accepting any URL having slash ('/') in it, but previously it is taking the URLs with slashes.

Error thrown:

Application Create failed. Scopes creation failed when creating App: 507 - {"domain_name":{"errors":[{"code":2402,"message":"Invalid domain name: mobile.local.com/"}]}}

My redirect URL contains path for a sub-page and it is not possible for me to remove all the slashes from my callback domain URL.

What can I do in such case?

Please help.

adding image to an array and submit it via curl

I've trouble sending image from url to remote host using curl. Everything else works.

// assemble full image path

foreach ( $respArr[ 'imgs' ] as $k => $v) {

    $car[ 'photos' ][ $k ] = file_get_contents( 'http://' . $v[ 'ipt' ] . '/im/im-' . $v[ 'ikey' ] ); // full url?

}

The issue is that I don't understand how browser sends images, it creates array, than this array content is invisible to me when I try to dump the $_POST.

Any clarification in this area is welcome :)

Cron php5 too many processes

I have a cron:

* * * * php5 /home/update_tunein.php
* * * * sleep 15; php5 /home/update_tunein.php
* * * * sleep 30; php5 /home/update_tunein.php
* * * * sleep 45; php5 /home/update_tunein.php

Every time cron makes a new proccess. These proccesses makes CPU usage 100%. How to make cron do only 1 proccess? Or maybe how to kill proccess after work?

... && killall php5

isn't working. Help me please

Global variable in object created from other object (PHP)

There are two classes, each one in its own file:

<?php
namespace test;

class calledClass {
    private $Variable;

    function __construct() {
        global $testVar;
        require_once 'config.php';
        $this->Variable = $testVar;
        echo "test var: ".$this->Variable;        
    }
}
?>

and

<?php
namespace test;

class callingClass {
    function __construct() {                
        require_once 'config.php';
        require_once 'calledClass.php';
        new calledClass();
    }
}

new callingClass();
?>

and simple config.php:

<?php
namespace test;
$testVar = 'there is a test content';
?>

When I start callingClass.php (which creates object calledClass), the property $Variable in calledClass is empty. But when I start calledClass.php manually, it reads meaning $testVar from config.php, and assumes it to $Variable. If I declare $testVar as global in callingClass, it helps - calledClass can read $testVar from config.php.

Can somebody tell me, why object, created from another object, can't declare vars as global, and use it?

P.S. Excuse my bad English.