mercredi 5 août 2015

how to configure .htaccess to such that I can have access to subfolders and subdomains in a Laravel project


I currently build most of my apps with Laravel 5.1 and host them on share hosting. The major challenge I have come across is that I cannot have access to sub folders e.g. http://ift.tt/1DpxEGu, also when I try to access a sub-domain for example admins.mydomain, I keep having Internal server error(error 500).
I need help to get over this, thanks.



via Chebli Mohamed

Using foreach with form submit


I am trying to submit multiple rows using the foreach loop in my method. However when I press submit I am getting this array to string error. How do I fix this error?

Error

Array to string conversion

HTML

{!! Form::open(array('id'=> 'form1')) !!}
    <div class = "form-group">
        <div class="col-md-6">
            {!! Form::label('title','Title:', ['class' => 'col-md-4 control-label']) !!}
            {!! Form::checkbox('interest_id', '1', ['class' => 'formclick submit']) !!}
        </div>
    </div>

    <div class = "form-group">
        <div class="col-md-6">
            {!! Form::label('title','Title:', ['class' => 'col-md-4 control-label']) !!}
            {!! Form::checkbox('interest_id', '2',['class' => 'formclick submit']) !!}
        </div>
    </div>
    <input id = "submit_me" type="button" value="Click Me!"  />
{!! Form::close() !!}

Controller

public function store(InterestRequest $interest) {

    $interests = Request::all();
    $interests = Request::all();

    foreach ($interest-> $interests as $inter) {
        $interest = new Follower(array(
            'user_id' => $interest->get('interest_id'),
            'follower_id'  => Auth::id()
        ));

        $inter->save();

    }
}



via Chebli Mohamed

How to update the cache value when database has change value of same data which is stored in cache


If i am using laravel 4.2 caching mechanism like bellow.

$users = DB::table('users')->remember(10)->get();

As i understand cache mechanism query execute one's and story it's value to cache and return data from cache upto 10 minutes.

But my problem is one's query will be executed and data stored it's cache inbetween user table updates it's value then how may i check and update cache value so i can get updated data.

Any one have idea any suggestion please let me know...?



via Chebli Mohamed

Generate a date schedule that executes only on weekdays


I have a date schedule function in PHP which aims to execute only on working days. The code I have at the moment is generating the schedule for all days of the week so the while statement doesn't seem to working and I'm not sure why.

I'm a student, so I'm not very experienced with this kind of thing. Here is the code I have so far:

public static function generate_date_schedule($tasksperdayschedule, $startdate) {
    $schedule = [];

    $date = clone $startdate;

    foreach ($tasksperdayschedule as $numberoftasks) {
        $day = (int)$date->format('N');

        // Skip weekend days.
        while ($day > 5) {
            $date->add(new DateInterval('P1D'));
            $day = (int)$date->format('N');
        }

        $schedule[$date->format(self::DATE_FORMAT)] = $numberoftasks;

        $date->add(new DateInterval('P1D'));
    }

   return $schedule;

It is probably something very small I am missing, but any help would be appreciated! Thanks



via Chebli Mohamed

Should I use Postgres's roles system for a web app's user management?


Postgres already has fully featured user management system. Why should I duplicate this functionality and use another one on top of that? And I think this is the right place to manage users & groups as it allows fine-grained control. Am I wrong? Is there some php libraries that already have done that?



via Chebli Mohamed

Select box doesn't work


So I have a select box built with :

$form->addElement(new Element\Select("Existing projects:", "Existing_Projects", $options, array("onchange"=>"this.form.submit()")));

And here is the code to get the projects.But somehow it doesn't work.When I click on 'option2' option,it gets back to 'option1'.

$projects = get_projects();
$options = array();
foreach ($projects as $project){
    if ( $project[2] == $Existing_Projects )
        $option = $project ; break ;
    array_push($options, $project[1]);
    }
$options = array(10=>"option1",5=>"option2", "value"=>"selected", 6=>"option3");
//print_r($options);
$form = new Form("project-form");//"prevent" => array("bootstrap", "jQuery"),
$form->configure(array(
    "action" => "right.php?target=management/platform"
));

What is wrong?



via Chebli Mohamed

Match exact word with any character regex


How to match exact word contains any special character ?

$string = 'Fall in love with #PepsiMoji! Celebrate #WorldEmojiDay by downloading our keyboard @ http://bit.ly/pepsiKB & take your text game up a notch. - teacher';

preg_match("/\b#worldemojiday\b/i",$string); //false

I want to match exact word containing any character. Like if I want to match word 'download' in this string, It should return false

preg_match("/\bdownload\b/i",$string); //false

But when I search for downloading, It should return true.

Thanks



via Chebli Mohamed

Google Maps: Multiple dynamic Markers and One Static Marker on the same map?


to keep the story short, I am currently displaying Multiple dynamic markers on google maps and one Static Marker.

The Dynamic markers are being moved around on the map using AJAX/PHP.

The Static marker gets it Position from the PHP $_GET.

So far everything works fine.

But the issue that I am facing is that when Dynamic Markers move on the map (AJAX execution), this will cause the Static Marker (the single Marker) to disappear!

This is my entire code:

<script type="text/javascript">



  $(function() {


    var locations = {};//A repository for markers (and the data from which they were constructed).

    //initial dataset for markers
    var locs = {
        /*1: { info:'Rooz', lat:-37.8139, lng:144.9634, icon:'carIconr.png'},
        2: { info:'Michele', lat:46.0553, lng:14.5144, icon:'carIconr.png' }*/
        0: { info:'You', lat:<?php echo $ulat; ?>, lng:<?php echo $ulng; ?>, icon:'meicon.png'},

        <?php echo $vehilcles; ?>

    };
    var map = new google.maps.Map(document.getElementById('map_2385853'), {
        zoom: 16,
        streetViewControl: true,



        center: new google.maps.LatLng(<?php echo $ulat; ?>, <?php echo $ulng; ?>),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });


    var infowindow = new google.maps.InfoWindow();

var auto_remove = true;//When true, markers for all unreported locs will be removed.

function setMarkers(locObj) {
    if(auto_remove) {
        //Remove markers for all unreported locs, and the corrsponding locations entry.
        $.each(locations, function(key) {
            if(!locObj[key]) {
                if(locations[key].marker) {
                    locations[key].marker.setMap(null);
                }
                delete locations[key];
            }
        });
    }

        $.each(locObj, function(key, loc) {
            if(!locations[key] && loc.lat!==undefined && loc.lng!==undefined && loc.icon!==undefined) {
                //Marker has not yet been made (and there's enough data to create one).

                //Create marker
                loc.marker = new google.maps.Marker({
                    position: new google.maps.LatLng(loc.lat, loc.lng , loc.icon),
                    map: map,
                    icon: loc.icon,
                });

                //Attach click listener to marker
                google.maps.event.addListener(loc.marker, 'click', (function(key) {
                    return function() {
                        infowindow.setContent(locations[key].info);
                        infowindow.open(map, locations[key].marker);
                    }
                })(key));

                //Remember loc in the `locations` so its info can be displayed and so its marker can be deleted.
                locations[key] = loc;
            }
            else if(locations[key] && loc.remove) {
                //Remove marker from map
                if(locations[key].marker) {
                    locations[key].marker.setMap(null);
                }
                //Remove element from `locations`
                delete locations[key];
            }
            else if(locations[key]) {
                //Update the previous data object with the latest data.
                $.extend(locations[key], loc);
                if(loc.lat!==undefined && loc.lng!==undefined) {
                    //Update marker position (maybe not necessary but doesn't hurt).
                    locations[key].marker.setPosition(
                        new google.maps.LatLng(loc.lat, loc.lng)
                    );
                }
                //locations[key].info looks after itself.
            }
        });
    }

    var ajaxObj = {//Object to save cluttering the namespace.
        options: {
            url: "ve.php",//The resource that delivers loc data.
            dataType: "json"//The type of data tp be returned by the server.
        },
        delay: 10000,//(milliseconds) the interval between successive gets.
        errorCount: 0,//running total of ajax errors.
        errorThreshold: 5,//the number of ajax errors beyond which the get cycle should cease.
        ticker: null,//setTimeout reference - allows the get cycle to be cancelled with clearTimeout(ajaxObj.ticker);
        get: function() { //a function which initiates 
            if(ajaxObj.errorCount < ajaxObj.errorThreshold) {
                ajaxObj.ticker = setTimeout(getMarkerData, ajaxObj.delay);
            }
        },
        fail: function(jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
            ajaxObj.errorCount++;
        }
    };

    //Ajax master routine
    function getMarkerData() {
        $.ajax(ajaxObj.options)
          .done(setMarkers) //fires when ajax returns successfully
          .fail(ajaxObj.fail) //fires when an ajax error occurs
          .always(ajaxObj.get); //fires after ajax success or ajax error
    }

    setMarkers(locs);//Create markers from the initial dataset served with the document.
    ajaxObj.get();//Start the get cycle.

    // *******************
    //test: simulated ajax
    /*
    var testLocs = {
        1: { info:'1. New Random info and new position', lat:-37, lng:124.9634 },//update info and position and 
        2: { lat:70, lng:14.5144 },//update position
        3: { info:'3. New Random info' },//update info
        4: { remove: true },//remove marker
        5: { info:'55555. Added', lat:-37, lng:0 }//add new marker
    };
    setTimeout(function() {
        setMarkers(testLocs);
    }, ajaxObj.delay);
    */
    // *******************
});
</script>

This is the Single Static Marker:

    0: { info:'You', lat:<?php echo $ulat; ?>, lng:<?php echo $ulng; ?>, icon:'meicon.png'},

and this is the List of dynamic Markers:

<?php echo $vehilcles; ?>

and its output looks like this:

1: { info:'Rooz', lat:-37.8139, lng:144.9634, icon:'carIconr.png'},
            2: { info:'Michele', lat:46.0553, lng:14.5144, icon:'carIconr.png' }
....

could someone please advice on how to keep the Static Marker on the map and just let the Dynamic Markers to move around on the map?

any help would be appreciated.



via Chebli Mohamed

Laravel 5.1 - How to use Model in Global function file


I created a common.php for my all the global function. When I run my first function {{Common::test()}}

It's working fine But I can not use model in it.

namespace App\library;
{
    class Common {

            public static function test()
            {
                echo "Yes";
                return "This comes from Common File";
            }
            public static function getCmsBlocks()
            {
                $model = Modelname::all();
                if($model){
                    echo "asdad";
                }else
                {
                    echo "sadasd";
                }
            }

    }
}

I don't get my output when I run {{Common::getCmsBlocks()}}



via Chebli Mohamed

PHP ignores an invalid php.ini on the production server, but PHP refuses to work completely with the same INI on a Vagrant machine


I have a stupid problem that is driving me nuts at the moment.

Our web apps are pretty small so we run them on a shared hosting environment. Therefore I don't have a lot of possibilities to change the server configuration. The only thing I can do is edit the php.ini that is used for our domain. Configuration of everything else is out of my reach.

That's why I wanted to set up a local Vagrant server that is as close to the production server as possible by installing the same PHP Version (almost! in Vagrant it is PHP 5.4.43, the production server however runs PHP 5.4.16) and using the same php.ini that is also used online.

Both servers are running Apache 2.4 and PHP via FastCGI using PHP-FPM.

However, when I try to start up PHP-FPM in the Vagrant machine with the php.ini that I have downloaded from the administration panel of our hosting provider, it exits with some fatal errors because some of the directives in the given php.ini are deprecated and have been removed. That made me wonder why the same php.ini refuses to work in Vagrant, but works online without problem.

As phpinfo() on the production server tells me, the downloaded ini file is the only php.ini that is being loaded. However, the file seems to be ignored and instead the default values are applied.

So I figure that particular ini file is a hangover from ancient times of our production server, and it is just as invalid on the production server as it is on my Vagrant machine - the error handling is just different! The production server handles the error gracefully, ignoring the invalid ini file silently, but my Vagrant machine refuses to work.

Ignoring the invalid ini file is obviously no solution to the root of the problem, but curiosity struck me. I thought this should be easy, but after googling for a while, I am still stuck. How and where can I configure PHP-FPM to ignore invalid ini files, instead of exiting with a fatal error?



via Chebli Mohamed

how to change the value of a specific key in short words in php


Array of title to be replaced with words temporary
Array ( [title] => LED Flash Macro Ring Light (48 X LED) with 6 Adapter Rings for For Canon/Sony/Nikon/Sigma Lenses [manufacturer] => Neewer Electronics Accessories [currency] => CAD [price] => 35.99 )

convert the title values to have less words temporary to compare with another key Array ( [title] => LED Flash Macro Ring [manufacturer] => Neewer Electronics Accessories [currency] => CAD [price] => 35.99 )



via Chebli Mohamed

Lost data while converting image png to base64 string


I have an image.png which is generated dynamically (barcode) and which is returned to html as

<img src="data:image/png;base64,B64STR" />

but it sometimes get defects (white dots).

To convert image to base64 string I use this code:

    ob_start();
    imagepng($img);
    $contents = ob_get_contents();
    ob_end_clean();

    return base64_encode($contents);

Can be the output buffer be the cause of lost data? Can I convert the image to base64 some other way?



via Chebli Mohamed

Class 'Mage' not found in Controller.php on line 835


Struggled fo serveral days, but not solved.

I get error when clicking magento connect manager in backend

PHP Fatal error: Class 'Mage' not found in "/abc/downloader/Maged/Controller.php on line 835"

The error also ocurred when just access http://domainname/downloader   The same code works for another host with OS Ubuntu.  The error host is CentOS release 6.5   It is not a privilege problem. I run chmod -R a+rwx * to change privilege of all folders in testing environment, but error still exist.

By tracing /abc/downloader/Maged/Controller.php on line 835

It is invoking Mage::setIsDownloader();

Before that line is include_once $this->getMageFilename();

Controller.php works. I add a line of output of the variable $this->getMageFilename();, it shows /abc/app/Mage.php"

And I write a test php and put it in downloader folder. It works:

echo "hi";
include_once('/abc/app/Mage.php');
 
echo Mage::getVersion();

The test php works. When accessed by http://.../downloader/test.php It can output   hi1.7.0.2 

I also tried to add include_once('/abc/app/Mage.php'); manually in index.php of downloader folder, but fails.

Cache and session are removed from both /abc/var and /tmp/magento

Any hint to further trace the problem?



via Chebli Mohamed

Google Search console API mistery


i'm trying to solve a mistery :) I'm trying to add a property url to my Google search console using php script through command line. The site seems to be adding correctly, as IU can list it using the list method, but I'm unable to find on which account it's being added :(

Here's the code i'm using to add a site

    $client_email = '12345-blablablabla@developer.gserviceaccount.com';
    $private_key = file_get_contents('mykey.p12');
    $scopes = array('http://ift.tt/13R7CuS');

    $credentials = new Google_Auth_AssertionCredentials(

        $client_email,
        $scopes,
        $private_key
    );
    $client = new Google_Client();
    $client->setAssertionCredentials($credentials);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion();
    }
    $webmastersService = new Google_Service_Webmasters($client);
    $webmastersService->sites->add($url);

And if i call the method $webmastersService->sites->listSites()

I'm being returned the property I added just before.

But on which google account is this added ? This is a mystery :)

Thanks for your help



via Chebli Mohamed

Counting IP addresses in PHP with MySQL


I want to count unique visits to a php file. I currently have following code. Could you expain why it doesnt work?

$ip = $_SERVER['REMOTE_ADDR'];
$geo_url = "http://ift.tt/1esFEZI".$ip."";

$data = file_get_contents($geo_url);
$visitor_location = json_decode($data, true);

$visitorcount = mycustomdb()->query("SELECT ipa FROM visits WHERE ipa = '".$visitor_location['ip']."' LIMIT 1");

if(!empty($visitorcount) {

$filedlupdate = mycustomdb()->query("SOME QUERRY THAT SETS uniquevisits=uniquevisits+1");
$visit = mycustomdb()->query("INSERT INTO visits (ipa) VALUES ('".$ip."')");

}

Basically the idea is to check if the IP is unique. If it is unique then uniquevisits gets a +1 and the ip is added to "ipa". If the ip is present in ipa, then the next check is ignored and nothing is being done. filedlupdate exists and works standalone, but not combined with all the code. Im not sure if I wrote it correctly. Can you spot an error?



via Chebli Mohamed

Web app comunicate with cash register


I'm working on a web app on localhost . A management application . I have a form of sale, add products and the completion want it to communicate with a cash register . I know I have to install a specific driver that cash and configured. What else should I do? The application is created in HTML , CSS, JS , PHP , MySQL.

From what I know , I had to create an executable after the operation is finished . Then the file executable to be picked up driver.

Can someone help me clarify ? :D



via Chebli Mohamed

Query would run directly on MySQL but not through PHP


I have a simple MySQL query

select * from tutor where verified = 0 and alert_by < '2015-08-05' LIMIT 0,1

Now, running this directly through phpMyAdmin provides the desired results, however, when this query is being executed through a set of PHP statements, it doesn't return anything. Below is my code in PHP

$this_date = date("Y-m-d");

$query = "select * from tutor where verified = 0 and alert_by < '$this_date' LIMIT 0,1";

$contact = mysqli_query($conn, $query);
$row = $contact->fetch_array(MYSQLI_ASSOC);

However, the $row is empty, I can't seem to figure this out. I know this seems trivial, but its a little annoying.



via Chebli Mohamed

Performance comparision: PHP&Json&Database - PHP&Json&Text File - PHP&Json&Parsing


I have a general question about what is faster between different options.

I have a site that works like this.

When the user fill the form, a PHP file (included) receive the selected option and parse multiple json file resident on another server.

The problem is that this operation is quite slow (there will be a part with database and cronjobs for automated updates and so obtain fast query) so I was wandering what may it be the fast way to retrive data and show on page.

The option I thought are: 1) PHP - JSON - NORMAL PARSE (the way I've used right now); 2) PHP - JSON - DATABASE (save everything on database and make multiple query); 3) PHP - JSON - TEXT (save every file I recover in a txt file so I have a rapid access to data?).

If you need I can be much more specific but maybe the answer is so simple that you don't need to read 200 rows of explanations.

Thx.

Alberto



via Chebli Mohamed

Sweet Alert Yii


I am trying to use sweet alert in yii in place on the confirmation option.

I have an ajax button and I would like the sweet alert to pop up, once the user has chosen confirm or cancel I can then either continue with the ajax request or stop.

'ajax' => array(

'url'=>CController::createUrl('items/delete'),
'type'=>'POST',
'async'=>true,
'data'=>array('Item'=>$item['Item_id']),
'dataType'=>'json',
'enctype'=>'multipart/form-data',
'cache'=>false,
'beforeSend'=>'js:function(data)
 {
    var x = sweetalertDelete();
    if(x){alert("aaaaaaa"); return true;} 
    else {alert("bbbbb"); return false;} 
 }',
'success'=>'function(data)
{

I am using beforesend in order to display the sweet alert box. The issue is that as soon as the the box appears, x is returned and the alerts seen later are then shown. Here is my sweet alert code:

function sweetalertDelete(){
         swal({
                title: "<?php echo Yii::t('app','misc.order_delete'); ?>",
                text: "You will not be able to recover this imaginary file!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Yes, delete it!",
                closeOnConfirm: false,
                closeOnCancel: false
            }, 
             function (isConfirm) {
                //swal("Deleted!", "Your imaginary file has been deleted.", "success");

                if (isConfirm) {
                    alert("true");
                                  return true;
                                }
                                else
                                { 
                                    alert("false");
                                    return false;
                                }
            });




    } 

My question is how I can make it so that the value of isconfirm is returned and until the confirm/cancel button is clicked, the ajax request will not be sent.



via Chebli Mohamed

php imagettfbbox cuts embedded padding present in font


I have some padding(top and left) in my font library now when i use imagettfbbox function of PHP it do not considers that padding while returning co-ordinates, is there any way of getting that padding from font library or any other function which can be used.

LINK



via Chebli Mohamed

same date to be one date and want to be average temperature @one day in php


Following is my php code:

<?php 
  echo "<h1>test</h1>";
  echo "<table border = '1' width = '50%'>\n";
  echo "<tr>";
  echo "<th>date</th>";
  echo "<th>temperature</th>";


  //get data from file
  $fileName = 'sensor.csv';
  $file = fopen($fileName,"r");


  //while not to end of file
  while (!feof($file) ) 
  {

    while (($csv_line = fgetcsv($file)) !== FALSE)
    {

      $date_format = strtotime($csv_line[0]);
      //print_r($csv_line);
      echo "<tr>";    //beginning new row of record
      echo "<td>" . date("Y-m-d", $date_format)."</td>";  
      echo "<td>" . $csv_line[2]."</td>";  
      echo "</tr>"; //new row

    }
    echo "</table>\n";
  }

?>


The following is the current output

date        temperature
2015-07-20  22.7
2015-07-20  22.7
2015-07-20  22.8
2015-07-19  32.8
2015-07-19  31.9
2015-07-19  32.8
2015-07-19  32.8
2015-07-18  29.1
2015-07-18  28.8
2015-07-18  29.7
2015-07-18  29.9
2015-07-18  29.4
2015-07-18  29.8
2015-07-16  26.4
2015-07-16  25.9
2015-07-16  24.7
2015-07-16  24.9
2015-07-16  25
2015-07-16  26.4
2015-07-16  27
2015-07-16  26.1
2015-07-16  26

I want it to be like this:

date        temperature
2015-07-20  average temperature of each day
2015-07-19  average temperature of each day
2015-07-18  average temperature of each day
2015-07-16  average temperature of each day



via Chebli Mohamed

How to set email to be expired?


I want to know about PHPMailer function. Is it possible to make email link to be expired?

I have case like this, when user click link that send from mobile apps or other to set their new password. After they created new password, then they will login again with the new password. what if click the link again, it will repeating the process again. I want to make the link will be expired if they are already create new password.

CMIIW



via Chebli Mohamed

Displaying page specific content [on hold]


I am making a website with PHP and have encountered an issue.

  • All my webpages include a footer, and I want to display data in the footer depending on the opened webpage, I found a very non-robust way of doing this.

    if( $CU == 'http://www.example.com' 
         || $CU == 'http://example/index.php'     
         || $CU == 'http://example/index.php/'    
         || $CU == 'http://example/')
    { 
    $display = "<p>Already registered? <a href='login.php'>Sign in</a></p>";
    }
    
    elseif( $CU == 'http://ift.tt/1IGJxDG' 
         || $CU == 'http://ift.tt/1mNFg9X' )
     { 
     $display = "<p>Forgotten your password? <a href='reset_password.php'>Reset</a> your password!</p>";
     }
    
    

Question (edited): What is a robust method of dynamically loading content based on the current file?



via Chebli Mohamed

Checking array sibling values


I am working on a calendar in PHP and I have an array of all of the days in a month with their availability status. This data is coming from an external XML file which is being parsed and converted into a PHP array for processing. The array looks something like this;

$days = array(
     '30-Oct-2015' => array(
         'available' => true
     ),
     '29-Oct-2015' => array(
         'available' => false
     ),
     '28-Oct-2015' => array(
         'available' => false
     ),
     '27-Oct-2015' => array(
         'available' => false
     ),
     '26-Oct-2015' => array(
         'available' => true
     ),
     '25-Oct-2015' => array(
         'available' => true
     ),
);

And I want to add an additional key, alongside available, to indicate how far away the next true value is. e.g

$days = array(
     '30-Oct-2015' => array(
         'available' => true,
         'daysUntilAvailable' => 3,
     ),
     '29-Oct-2015' => array(
         'available' => false
         'daysUntilAvailable' => 2,
     ),
     '28-Oct-2015' => array(
         'available' => false,
         'daysUntilAvailable' => 1,
     ),
     '27-Oct-2015' => array(
         'available' => false,
         'daysUntilAvailable' => 0,
     ),
     '26-Oct-2015' => array(
         'available' => true,
         'daysUntilAvailable' => 0,
     ),
     '25-Oct-2015' => array(
         'available' => true,
         'daysUntilAvailable' => 0,
     ),
);

How would I go about doing something like this in PHP?



via Chebli Mohamed

Symfony ignore AppleDouble


I have a development server where I log in to (through ssh). Apple automatically creates the AppleDouble files/directories, which doesn't work well with Symfony. Every time I want to use a command (mostly doctrine:schema:update). I get AppleDouble errors about classes that don't exist.

Is there any way to tell Symfony to ignore those AppleDouble files?

I saw this issue on GitHub, but it's closed in favor of other issues, but I don't really know how to implement it. (http://ift.tt/1MMneDM)



via Chebli Mohamed

Send multiple chekbox items to Angular Controller


I'm trying to make a view wich allow me to send invitation via email to google contacts using google contacts api & javascript

for (var index = 0; index < result.length ; index++){
  var name= result[index];
  $(".email").append('<div><span class="part left">'+result[index]+'</span><span class="part right">


What i need is to send the values of the selected checkboxs to angular controller

in my controller when i var_dump the ng-model it always says undefined. Any suggestions ?

 var emails = [];
  emails.push(checkboxModel.name);
  $scope.data = emails;
  console.log(emails);



via Chebli Mohamed

proxy multiple xhr request send


Im using Php proxy (poxy-0.5b2).

My project is sending multiple xhr requests without waiting for response of the first one. Everything works fine. But when I'm trying to reach my project via proxy I see that my requests issint reaching destination until I get response from the first request.

How can I solve this problem?



via Chebli Mohamed

Convert laravel object to js array


i am new in laravel. how to convert laravel object into js array. my coce is below..

$customer = new Customer();             
        $result = $customer->where('client_state','like', '%'.$statename.'%')->get(array('client_state'));

        echo $result;

result is...

[{"client_state":"Gujarat1"},{"client_state":"Gujarat"}]

but i need like this..

["Gujarat1","Gujarat"]

how it is possible?



via Chebli Mohamed

Function name must be a string fatal error


I have this Fatal error, I've been staring at my code for hours.. I think it has nothing to do with the name of the function action_send, it must be some silly 'missing parenthesis' or something...

can you help me please ?

if (...) {}
else if (!historic_exist($id)) {
                action_send($req, '0', (strpos($req['TAG'], 'ADMD') !== false) ? $req['ID_ACT'] : '');
//the error is in this line : 
                    if ((strpos($req['WF'],'Install') !== false) && $req('ID_EQU') !== '')
                action_send($req, '', '0');
                    }



via Chebli Mohamed

Paypal pro UK direct payment


I am having issue with paypal pro direct UK payment method. I am sending below request but not getting any response from paypal server.

<?xml version="1.0" encoding="UTF-8"?> 
<XMLPayRequest Timeout="60" version = "2.0" xmlns="http://ift.tt/1gJEEEb" request_id="20150805021629930714">
    <RequestData> 
        <Vendor>Vendor</Vendor> 
        <Partner>PayPalUK</Partner>
        <Transactions> 
            <Transaction>
                <Sale> 
                    <PayData> 
                        <Invoice> 
                            <CustIP>127.0.0.1</CustIP> 
                            <MerchantDescription>TSTSTOR*FLOWERS4YOU</MerchantDescription> 
                            <BillTo> 
                                <Name>Mytest</Name> 
                                <Address> 
                                    <Street>1135 in</Street> 
                                    <City>Houston</City> 
                                    <State>TX</State> 
                                    <Zip>77037</Zip> 
                                    <Country>223</Country> 
                                </Address> 
                                <EMail>email@gmail.com</EMail> 
                                <Phone>911223121231</Phone> 
                            </BillTo> 
                            <ShipTo> 
                                <Name>mytest</Name> 
                                <Address> 
                                    <Street>1135 in</Street> 
                                    <City>Houston</City> 
                                    <State>TX</State> 
                                    <Zip>77037</Zip> 
                                    <Country>US</Country>
                                </Address> 
                                <EMail>email@gmail.com</EMail> 
                                <Phone>911223121231</Phone> 
                            </ShipTo> 
                            <Items>
                                <Item Number="1"> 
                                    <SKU>T-Shirt-1</SKU> 
                                    <Description>Custom T-Shirt (Upload your own design!)</Description>
                                    <Quantity>1</Quantity> 
                                    <UnitPrice>25.99</UnitPrice>
                                </Item> 
                            </Items> 
                            <TotalAmt Currency="USD">26.77</TotalAmt> 
                            <Comment></Comment>
                        </Invoice> 
                        <Tender>
                            <Card> 
                                <CardNum>XXXXXXXXXXXXXXXX</CardNum> 
                                <ExpDate>XXXXXX</ExpDate> 
                                <CVNum>XXX</CVNum>
                                <ExtData Name='CardIssue' Value=''/> 
                                <ExtData Name='CardStart' Value=''/> 
                            </Card> 
                        </Tender>
                    </PayData> 
                </Sale> 
            </Transaction> 
        </Transactions> 
    </RequestData> 
    <RequestAuth> 
        <UserPass> 
            <User>uername</User> 
            <Password>pswd</Password> 
        </UserPass> 
    </RequestAuth> 
</XMLPayRequest>



via Chebli Mohamed

PHP/cURL post, just returns the page as if no post was made


My goal is to get the prices from this site: http://ift.tt/1wP9mvM.

There is a price field on the site that is edited once a user selects a certain option

Option code:

<form action="10530943.html" method="post" class="field">
   <fieldset>
   <legend>Hoeveelheid</legend>
   <label for="opts-7" class="">Hoeveelheid</label>
   <select name="option" id="opts-7">
      <option value="5859" selected>1 kg</option>
      <option value="5913">2.5 kg</option>
      <option value="5935">5 kg</option>
   </select>
   <input type="hidden" name="variation" value="7"/>
   </fieldset>
</form>

This is the area where the price is updated once a selection box has been chosen:

<h2 class="price">
<span itemprop="price">&euro;15,99</span>
</h2>

Im using cURL to post the form to the aforementioned URL with this PHP code:

$URL = "http://ift.tt/1wP9mvM";

$c = curl_init();
$agent = 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0';
curl_setopt($c, CURLOPT_USERAGENT, $agent);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
curl_setopt($c, CURLOPT_POST, true);

$data = array(
'option' => '5935',
'variation' => '7'
);

curl_setopt($c, CURLOPT_POSTFIELDS, $data);

$contents = curl_exec($c);
$info = curl_getinfo($c);
curl_close($c);

The website just responds as if no post was made. The first option is selected regardless of my input. How is this possible? Obviously something is wrong here. Is it because the way they handle the postdata am I missing something here?



via Chebli Mohamed

How To Fix Error Pagination with Search Data Using session


i have a problem pagination with search data using session. if i am not using search data using session, pagination will be work. but when i am using search data. pagination could not be work. when i click on a pagination link, The requested address '/..../..../page:2' was not found on this server. so i need help to fix error the pagination.

public function index($id=null) {
    if($id='flush'){
        $this->Session->delete('inboxes_index.date_start');
        $this->Session->delete('inboxes_index.date_end');
    }

    $this->loadModel('Product');
    $this->LoadModel('ResponseStats')  ;
    $this->ResponseStats->reqursive = -1;
    $this->Product->recursive = -1;


    if($this->request->data['Inbox']['date_start']){
        $conditions["Inbox.create_date >="] = date("d-M-Y", strtotime($this->request->data['Inbox']['date_start']))." 00:00:00";
        $this->Session->write('inboxes_index.date_start', $conditions["Inbox.create_date >="]);
    }else{
        $conditions["Inbox.create_date >="] = date("d-M-Y")." 00:00:00";
        $this->request->data['Inbox']['date_start'] = date("d-M-Y", strtotime($this->request->data['Inbox']['date_start']." 00:00:00"));
    }

    if($this->request->data['Inbox']['date_end']){
        $conditions["Inbox.create_date <="] = date("d-M-Y", strtotime($this->request->data['Inbox']['date_end']))." 23:59:59";
        $this->Session->write('inboxes_index.date_end', $conditions["Inbox.create_date <="]);
    }else{
        $conditions["Inbox.create_date <="] = date("d-M-Y")." 23:59:59";
        $this->request->data['Inbox']['date_end'] = date("d-M-Y", strtotime($this->request->data['Inbox']['date_end']."23:59:59"));
    }


    //read session date start
    if($this->Session->read('inboxes_index.date_start')!=NULL) {
        $conditions["Inbox.create_date >="] = $this->Session->read('inboxes_index.date_start');
        $this->request->data['Inbox']['date_start'] = date("d-M-Y", strtotime($this->Session->read('inboxes_index.date_start')));
    }

    //read session date end
    if($this->Session->read('inboxes_index.date_end')!=NULL) {
        $conditions["Inbox.create_date <="] = $this->Session->read('inboxes_index.date_end');
        $this->request->data['Inbox']['date_end'] = date("d-M-Y", strtotime($this->Session->read('inboxes_index.date_end')));
    }


    $this->Inbox->recursive = -1 ;
    $this->paginate = array(
    //$report_inbox = $this->Inbox->find('all', array(
                                'conditions'=> array_merge($conditions),
                                'joins' => array(
                                    array(
                                        'table' => 'users',
                                        'alias' => 'User',
                                        'type' => 'INNER',
                                        'conditions' => array('User.id = Inbox.user_id')
                                    ),
                                    array(
                                        'table' => 'response_stats',
                                        'alias' => 'Respon',
                                        'type' => 'inner',
                                        'conditions' => array('Respon.code::int4 = Inbox.status')
                                    )
                                ),
                                'fields' => array(
                                    'User.username', 
                                    'User.company', 
                                    'User.cid', 
                                    'Inbox.idpel', 
                                    'Inbox.status', 
                                    'Inbox.trx_type',
                                    'Respon.name',
                                    'Inbox.trxid', 
                                    'date(Inbox.create_date)'
                                ),
    );


    $this->set('report_inbox', $this->paginate());



via Chebli Mohamed

PHP Memcache extension won't register as a save handler


I'm developing with PHP 5.5.25 and Apache 2.4.16 on a Windows machine. I'd like to use a Memcached server to manage Sessions, and the memcache (not Memcached) PHP extension to interact with the server. The problem is that when I try to start a session I get error Cannot find save handler 'memcache' - session startup failed

I have installed the Memacached server and believe it is running properly: in PHP, I can interact with it by saving to and retrieving data from the cache, querying the version number etc... My Firewall also shows that memcached.exe is listening on port 11211. So far so good.

php.ini

; the DLL is present in the extensions directory
extension=php_memcache.dll

; commented out to avoid having 2 session.save_handlers
; session.save_handler = files

; this is correct. I am using memcache, not memcached extension
session.save_handler = memcache 

; the protocol tcp:// is required for memcache
session.save_path = "tcp://127.0.0.1:11211" 

Searching around the web, I've seen the following solutions:

  • Use session.save_handler = memcached. This does not work; my extension is memcache
  • Remove tcp:// from the save path. This is good for memcached, but I'm using memcache

In phpinfo's session section, the value of Registered save handlers is files user when it should really be files user memcache. I can't figure out why the memcache extension is not listed here even though phpinfo shows that session.save_handler has Local value memcache and Master value memcache.
phpinfo: memcache fails to register as a save handler

Please remember that:

  • although session start fails, I can interact with the Memcached server in PHP so I know that memcache extension can communicate with Memcached server, and that the memcache class methods are recognized by the PHP parser.
  • I'm working on Windows, and am not using WAMP, MAMP or the like. Just plain Apache with a reference to the PHP binary


via Chebli Mohamed

Implement LTI tool in php


I am developing a Learning Management System in PHP and I am willing to integrate LTI tools like Questionmark(http://ift.tt/1Hq0qBR) in this application but I am very new to LTI and even do'nt know from where and how I should start.

So, please share any demo application if there or any better tutorial for it if anyone has. Thanks in advance.



via Chebli Mohamed

apache cross domain configuration


I am trying to setup this application on my server openspeedtest.com self-hosted app they provided Nginx configuration. how can i make this work on my apache shared hosting server?

fastcgi_read_timeout 360;
client_max_body_size 2000M;
location / {
    if ($http_origin) {
        add_header 'Access-Control-Allow-Origin' 'http://ift.tt/1n0OH3l';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

          }
if ($request_method = OPTIONS ) {
        add_header Access-Control-Allow-Credentials "true";
        add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';
        add_header Access-Control-Allow-Origin "http://ift.tt/1n0OH3l";        
        add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
        return 204;
            }
        }



via Chebli Mohamed

How to convert strings from Cyrillic_General_CI_AS to utf8_general_ci in PHP


I need to import some data from MSSQL to MYSQL and I do this programmatically using PHP and PDO. The final lines of code that fetch one last field to be inserted to MYSQL look like this:

$s = $db->prepare("SELECT id FROM object_70912_ 
                         WHERE attr_76453_ = :num AND attr_70954_ = :attr_70954_");
$s->bindParam(':num', $row['building'], PDO::PARAM_STR); 
$s->bindParam(':attr_70954_', $row2['id'], PDO::PARAM_INT);

In this code $row['building'] comes from MSSQL and have this character set - Cyrillic_General_CI_AS, whereas attr_76453_ has this character set in MYSQL - utf8_general_ci. As a result, parameter binding does not work - I can not find appropriate values and this SELECT query allways returns an empty result set - and it is not right, since I checked it. So, I guess that to solve the problem I need to somehow convert data from Cyrillic_General_CI_AS to utf8_general_ci (or it may sound different in terms of PHP).



via Chebli Mohamed

How do I know which file to edit in wordpress?


I have a website in wordpress and I've noticed in some points i want to change a piece of text or something similar, I don't know which file to edit.

How do i locate the file that I want to edit in Filezilla using FTP in order to change the website detail that I want to?



via Chebli Mohamed

mysql start error on Yosemite, but sqlpro is reading a db


I have several websites, which use PHP and MySQL, these run with no problems as does SQL Pro.

However I have just written a PHP script which runs from the command line and connects to a MySQL database, but I get the following error when trying to run it:

PHP Warning:  mysqli_connect(): (HY000/2002): No such file or directory

I tried restarting MySQL (on the command line and through System Prefs), on the command line I get his error:

ERROR! The server quit without updating PID file

I think the problem is I have 2 MySQL servers installed: /usr/local/mysql/ /usr/local/mysql-5.6.24-osx10.8-x86_64/

My question is, am I correct in thinking that Apache is using one version of MySQL, but PHP on the command line is using another?

How do I find which versions are being used by Apache, MySQL Pro, PHP?



via Chebli Mohamed

Code igniter- 500 Internal server Error


I have downloaded Gocar3 codeigniter e-commerce.. and installed to my local server(xampp).. after installation the index page comes with 404 error message with header menu and i tried ti click on login page link the the url goes correctly but the page shows Internal server error.. I searched and tried it by .htaccess issues and Apace rewrite_mod enable..I did all these.. but still th site shows the "Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at postmaster@localhost to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request. Apache/2.4.2 (Win32) OpenSSL/1.0.1c PHP/5.4.4 Server at localhost Port 80"

Please Guys.. do u have any solution for this??



via Chebli Mohamed

How to dump PHP backtrace on live running script in lldb?


I'm playing around with LLDB (debugger) and I did the following experiment.

  1. Run PHP script as:

    php -r "sleep(1000);"
    
    
  2. On another console, I've called directly zif_debug_backtrace() from lldb:

    echo 'call (void)zif_debug_backtrace()' | lldb -p $(pgrep -fn php)
    
    

Above worked, however the process stopped with the following warning:

Warning: sleep() expects at most 2 parameters, 1606408648 given in Command line code on line 1
Call Stack:
    0.0016     235152   1. {main}() Command line code:0
    0.0021     235248   2. sleep(1000) Command line code:1

I'm not quite sure why the script had to stop and what I need to do to achieve transparency (without affecting the script)?

P.S. The same happening when calling zif_debug_print_backtrace() and when calling custom_backtrace() it is showing: Backtrace null function called. I'm using xdebug if that change anything.

Maybe I need to call a different function like zend_fetch_debug_backtrace (see: image dump symtab)? Or use the right arguments, if so, which one?

I'm only interested in lldb/gdb solutions in order to print the backtrace.



via Chebli Mohamed

PHP mysql to mysqli migration issues (custom functions, procedural style)


Goodmorning

I'm planning to migrate a whole application I made from mysql extension to mysqli, due to next PHP version will not support mysql anymore and I don't want to go fool in the last minutes.

At the moment all page have 2 main inclusions: 1) dbdata.inc.php which contains database connection data 2) function.inc.php which contains most used functions

I'd like to mantain the procedural style also using mysqli extension, but I read that all mysqli functions must receive the connection link as a parameter.

I'm asking for suggestion on the best way (i.e. the most painless solution) to migrate without going mad and without radically rewrite all my php pages.

Actual content of dbdata.inc.php:

$yare_db = mysql_connect($yaredb_host,$yaredb_user,$yaredb_pass) or die("some error warning<br>"); 
mysql_select_db($yaredb_conn); 
mysql_query("SET NAMES 'utf8'");

Most used functions defined in functions.inc.php:

function YQUERY($query) {
    $res = mysql_query($query) or die(mysql_error());
    return $res;
}

function FETCHA($res) {
    $rs = mysql_fetch_array($res);
    return $rs;
}

function NUMROWS($res) {
    $num = mysql_num_rows($res);
    return $num;
}

function AFFROWS() {
    $num = mysql_affected_rows();
    return $num;
}

/* an important function filtering user input texts before passing them to queries */

function msg_safe($string) {
    // some regex and \n to "<br>" substitutions...
    $string = mysql_real_escape($string);
    return $string;
}

Well, the question now is how to migrate:

1) Should i pass the db connection as a function parameter? I.e. something like:

function YQUERY($link,$query) {
    $res = mysqli_query($link,$query);
    return $res;
}

?

2) Should I, instead, define the db connection (defined into included dbdata.inc.php at page start) as GLOBAL variable, inside the function? I.e. something like:

function YQUERY($query) {
     global $link;
     $res = mysqli_query($link,$query);
     return $res;
}

?

3) Should I (it sounds terrific) explicitly declare a new connection inside any custom function? I.e. something like:

function YQUERY($query) {
     $link = mysqli_connect("host","user","pass","db") or die("Error " . mysqli_error($link)); 
     $res = mysqli_query($link,$query);
     return $res;
}

?

4) Other suggestions?

Thanks in advance



via Chebli Mohamed

Implementation of ZendTwitter Service


 $config = array(
            'access_token' => array(
            'token'  => 'twitter-access-token-here',
    'secret' => 'twitter-access-secret-here',
),
'oauth_options' => array(
    'consumerKey' => 'twitter-consumer-key-here',
    'consumerSecret' => 'twitter-consumer-secret-here',
),
'http_client_options' => array(
    'adapter' => 'Zend\Http\Client\Adapter\Curl',
    'curloptions' => array(
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_SSL_VERIFYPEER => false,
    ),
),
);

$twitter = new Twitter($config);

In which file I need to write this code in Zend Studio to implement twitter Service. Please help. I am new to zend. I have got this code in this link - http://ift.tt/1KPY1oF



via Chebli Mohamed

Does rehashing a randomly salted password at login increase security?


Hello fellow programmers,

I am currently working on a project in php, and am wondering how to make my system as secure as currently possible. I am currently using password_hash to hash my passwords and then store them in my database. What I was wondering: Does rehashing and re-saving the new salted hash to the database increase security, or is that just an illusion?

Thank you for any input.



via Chebli Mohamed

How to fetch div data from remote website page and store it as a variable? [duplicate]


This question already has an answer here:

Suppose a website site.com has a div element <div class="abc">Some Texts</div> in each page where "Some Texts" varies in each page, how do I fetch the data "Some Texts" and store it in a PHP variable? I use the following code to replace all the contents up to <div class ="abc"> I want to store The values in the div which has class abc.

<?php
$file=curl_get('http://ift.tt/1Hq0qll'.$_SERVER['QUERY_STRING']);

$file=preg_replace('|<!DOCTYP(.*?)<div class="abc">|is', '<div class="abc">',$file);

echo $file;
?>



via Chebli Mohamed

PDO - How to avoid "General error: 2014" when using prepared statements executed in a while loop?


The following code block is a PDO select statement, using try and catch and looping the results out with a while loop. I then prepare a few select queries before the while loop so that I can use rows from the first select statement to loop through and execute the prepared ones with changing variables with each loop. I have found that this works for me up to 3 prepared statements and as soon as I go up to 4 it gives me this error:

General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

I have researched this problem and have tried PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute with no joy. I have tried fetchAll() and that didn't work. I have tried using the $conn->closeCursor(); and that also does not work. I have also tried to unset(); the prepared variable and that also does not work. I have also tried putting the prepared select statements in one query and looping through it using nextRowset() and that also did not work. I have also tried combinations of the above.

So the only way I have got this to work is by putting the prepared variables inside the loop therefore preparing them within each loop. So although this works and without much lag to the response time of the script, it's not ideal. So how do I fix this? Or is the way I fixed it the only way? My hunch is that I need to use a combination of the above listed techniques and I haven't gotten it correct. So in your answers please give a code example showing where to put what. Thank You.

try{
    $select_result = $conn->prepare("SELECT * FROM table WHERE id= ?");
    $select_result->execute(array($id));
    // Prepare Statements //
    $second_result = $conn->prepare("SELECT * FROM second_table WHERE id= ? AND status = ?");
    $third_result = $conn->prepare("SELECT * FROM third_table WHERE id= ? AND another_field= ? AND status= ?");
    $forth_result = $conn->prepare("SELECT * FROM forth_table WHERE id= ? AND another_field= ? AND status= ?");
    $fifth_result = $conn->prepare("SELECT * FROM fifth_table WHERE id= ? AND another_field= ? AND status= ?");
    $sixth_result = $conn->prepare("SELECT * FROM sixth_table WHERE id= ? AND another_field= ? AND status= ?");
    while($select_row = $select_result->fetch())
    {
        if($select_row['row1'] == 1){
            try{
                $second_result->execute(array($id, $select_row['field']));
                $second_row = $second_result->fetch();
            }
            catch(PDOException $e){}
        }
        else{
            try{
                $third_result->execute(array($id, $select_row['field1'], $select_row['field2']));
                $third_row = $third_result->fetch();
            }
            catch(PDOException $e){}
        }

        if($select_row['row2'] == 1){
            try{
                $forth_result->execute(array($id, $select_row['field1'], $select_row['field2']));
                $forth_row = $forth_result->fetch();
            }
            catch(PDOException $e){}
        }

        if($select_row['row3'] == 1){
            try{
                $fifth_result->execute(array($id, $select_row['field1'], $select_row['field2']));
                $fifth_row = $fifth_result->fetch();
            }
            catch(PDOException $e){}
        }

        if($select_row['row4'] == 1){
            try{
                $sixth_result->execute(array($id, $select_row['field1'], $select_row['field2']));
                $sixth_row = $sixth_result->fetch();
            }
            catch(PDOException $e){}
        }
    }
}
catch(PDOException $e){}



via Chebli Mohamed

Get month name in Symfony


Is it possible to get somehow name of given month (by its number) in Symfony's controller. And in current locale.

Form's date widget translates month to current locale automatically. I would like do the same but in my controller.

I know how get country translated but didn't found the same funtionality for month.

Thanks



via Chebli Mohamed

How to make preg_match PHP function match domain in email address format?


Below is the part of the script that needs modifying. Currently it will match any word directly after the @ in the email address supplied by the user. I need it to be able to match any word either directly after the @ or with another word and dot (.) preceding, example: user@domain.com should match domain, user@someword.domain.com should also match domain regardless of the .someword in front (which changes user to user and is there for some but not others.

PHP CODE:

preg_match('|@([0-9a-zA-Z]+)\.|i', $username, $match);



via Chebli Mohamed

How to add Different type of language pack for whole website


I have one website, for that whole website i need to add language pack dynamically. Is there any way to do that???

I am using Laravel PHP.

Thanks in advance Hemanth



via Chebli Mohamed

PHP xPath not returning all matches with correct xPath Expression


I am using the following xPath expression:

//div[@id='col_izq']//div[starts-with(@id,'col_izq_tit')]//h1/a |
//div[@id='col_izq']//div[@id='caja_nacional']//h2/a

On this HTML file: http://ift.tt/1MNNxsn

Via PHP, as follows:

$xpath=new DOMXPath($domdoc);
$ALL=$xpath->query($xpathqry);

And it returns an array with ONE single match.

But when testing my xPath in the same site, via FirePath (fierfox addon to test xpath) it returns 9 matches. (See attached screenshot)

Screenshot

The interesting thing here is that it has always been working in my previous cases. I wonder if I am doing something wrong with my xPath query, or maybe I am loading the HTML file in the wrong way:

This is the part in my PHP class, that fetches the HTML and makes sure it is UTF-8 encoded.

$opts = array('http' => array('header' => 'Accept-Charset: UTF-8, *;q=0'));
$context = stream_context_create($opts);
$html=file_get_contents('http://'.$this->motorConfig['domain'].'/'.$seccion,false,$context);
$html=mb_convert_encoding($html, 'UTF-8', mb_detect_encoding($html, 'UTF-8, ISO-8859-1', true));
//$html=str_replace("\0", '', $html); //Avoid PHP BUG http://ift.tt/1HmjQe4
$this->dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath=new DOMXPath($this->dom); //her cuz must be set after loading HTML into DOM



via Chebli Mohamed

How do I use multiple versions of Laravel on the same machine?


After that I had to contribute to one of Laravel 4 projects, I pulled it and just ran blindly composer install, to get the dependencies of 4...

However when I came back to projects of laravel 5, I had to re-run the command to continue working on them too..

So instead of re-running composer all the time, is there a neater alternative to have multiple versions of laravel on the same machine on the same user?

I am using Ubuntu 14.04 LTS



via Chebli Mohamed