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

samedi 25 avril 2015

pear BBCodeParser2 couldn't parse WysiBB links


i used pear BBCodeParser2 with Wysibb editor,it works good for most bbcodes like bold,italic,images....etc

the problem only in links,it can't parse urls in the topic,and when i look at db table, i found the url bbcode unchanged.... i checked all links and files included,and the problem still the same:

php:

       $config = parse_ini_file('HTML/BBCodeParser2.ini',true);
        $options = $config['HTML_BBCodeParser2'];
        $parser = new HTML_BBCodeParser2($options);
        $parser->setText($this->db->real_escape_string($_POST['t_body'])); 
        $parser->parse(); 
        $t_body= $parser->getParsed();

img from db: enter image description here


Is it possible use a custom 'select' template for bunlded products in Magento?


I'm creating a specific bundled product, which needs a few custom changes to the select and checkbox templates.

Supposedly I could just add a custom update layout in the product, but nothing I do seems to be able to target a new select.phtml template.

<reference name="product.info.options.wrapper">
 <!-- THIS WORKS -->
 <block type="bundle/catalog_product_view_type_bundle" name="product.info.bundle.options" as="type_bundle_options" template="bundle/catalog/product/view/type/bundle/*custom*.phtml">
  <action method="addRenderer">
    <type>select</type>
    <block>bundle/catalog_product_view_type_bundle_option_select</block>  
    <!-- THIS DOESN'T WORK -->
    <template>*custom_folder*/bundle/catalog/product/view/type/bundle/option/*custom*-select.phtml</template>
  </action>
 </block>
 <action method="insert"><block>product.info.bundle.options</block></action>
</reference>

Looking at the catalog.xml, it looks like the checkboxes, and selects, etc ... point to a template, but not in bundle.xml.

And, I can of course overwrite the default templates in theme/template/bundle/catalog/...etc../option/select.phtml ... but I really need a specific template for one product ... not all of them.

I'm hoping somebody has some insight into this? Maybe I'm going about this the wrong way?

Thanks!


php mysql fetch two table


i have two table from mysql.

1, photo (url_link)

2, video(url_link)

i wanna fetch only 1 table (video url) if both table aren't empty.. Is there anyways? am using code below:

<--photo -->
    <?php       
$query_img = mysql_query("SELECT `url` FROM `photos_news` WHERE title='{$thumn_content['titles']}' LIMIT 0,1");
while($img = mysql_fetch_array($query_img)){ ?>
<img src="<?php echo $img['url'];?>" class="img-responsive img-rounded"/>
<?php }?>


<!-- vdo -->
<?php
$query_vdo = mysql_query("SELECT `url` FROM `video_news` WHERE title='{$thumn_content['titles']}' LIMIT 0,1");
while($vdo = mysql_fetch_array($query_vdo)){ ?>
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="<?php echo $vdo['url']?>?modestbranding=1&showinfo=0&fs=0"></iframe>
</div>

<?php }?>

thank you sir,


Send data sensitive data to javascript


I have this code:

<input type="button" value="Delete Group" class="followbt" name="delete" onclick="deleteGroupDialog(' . $group_row['ngroup'] . ');">

The field 'ngroup' is the group number that i want to delete, and i am passing it to a javascript function that opens an jquery dialog window in order to ask if the user is certain of what is doing, the problem is that anyone can go on the browser and edit that number and go delete any group (that belongs to him).

I have already made a search about this but i didn't find anything, is there a way to pass the argument more securely?

PS: When i show the dialog window i don't want to reload the page a make a server request.


Compare data from two tables and check the same data


Hello I have two tables in my database.

The first one is table disease which look like the above...

enter image description here

And the second is table patient which look like this ...

enter image description here

And I have an edit page where I want to give the user the ability to update his/her diseases. An example is the below..

enter image description here

What I want to do is to check the disease column from the table patient with the column name from the table disease and check that if a data from the table patient is the same with the data from the table disease then check from the checkboxes the same disease.

I tried to find a way to do it by I couldnt Here is my code...

<?php
$sql = "SELECT name FROM disease UNION SELECT disease FROM patient WHERE username='$username'";
$query_resource = mysql_query($sql);

  while( $name = mysql_fetch_assoc($query_resource) ):
?>
    <span><?php echo $name['name']; ?></span>
    <input type="checkbox" name="disease[]" value="<?php echo $name['name']; ?>" /><br />


<?php endwhile; ?>

The way I store the diseases in my database is this...

$disease = implode(",",$_POST["disease"]);

Because a user might have many diseases


need help how do i get response from php just like this?


It's my wishes { "worldpopulation": [ { "rank":1,"country":"China", "population":"1,354,040,000", "flag":"http://ift.tt/1k4xoyg" },

     {
     "rank":2,"country":"India",
     "population":"1,210,193,422",
     "flag":"http://ift.tt/1kKjA0k"
     }, 

     {
     "rank":3,"country":"United States",
     "population":"315,761,000",
     "flag":"http://www.androidbegin.com/tutorial/flag/unitedstates.png"
     }, 

     {
     "rank":4,"country":"Indonesia",
     "population":"237,641,326",
     "flag":"http://ift.tt/1gnVIs0"
     }, 

     {
     "rank":5,"country":"Brazil",
     "population":"193,946,886",
     "flag":"http://ift.tt/1kKjxlh"
     }, 

     {
     "rank":6,"country":"Pakistan",
     "population":"182,912,000",
     "flag":"http://ift.tt/1kKjxlj"
     }, 

     {
     "rank":7,"country":"Nigeria",
     "population":"170,901,000",
     "flag":"http://ift.tt/1gnVIIk"
     }, 

     {
     "rank":8,"country":"Bangladesh",
     "population":"152,518,015",
     "flag":"http://ift.tt/1kKjA0v"
     }, 

     {
     "rank":9,"country":"Russia",
     "population":"143,369,806",
     "flag":"http://ift.tt/1o2k91J"
     }, 

     {
     "rank":10,"country":"Japan",
     "population":"127,360,000",
     "flag":"http://ift.tt/1kKjxBB"
     } 
] 

} http://ift.tt/LA6KRN


Yii2 Getting user input from a form


I am making a Search query for a user to find a property within a price range. I do not know how Yii2 gets the user input. Here is my code for the form:

  <?php $form = ActiveForm::begin([
    'action' => ['index'],
    'method' => 'get',
]); ?>

<?= $form->field($model, 'address') ?>

<?= $form->field($model, 'minprice')->dropDownList(['£100' => '£100','£200' => '£200','£300' => '£300']) ?>

 <?= $form->field($model, 'maxprice')->dropDownList(['£100' => '£100','£200' => '£200','£300' => '£300']) ?>

<div class="form-group">
    <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
    <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>

<?php ActiveForm::end(); ?>    

And here is my model:

class PropertiesSearch extends Properties
{

 public $minprice;
 public $maxprice;

public function search($params)
{
    $query = Properties::find();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $this->load($params);

    if (!$this->validate()) {
        return $dataProvider;
    }

    $query->andFilterWhere([
        'id' => $this->id,
        'NoofBedrooms' => $this->NoofBedrooms,
        'type_id' => $this->type_id,
    ]);

    $query->andFilterWhere(['like', 'address', $this->address])
        ->andFilterWhere(['like', 'city', $this->city])
        ->andFilterWhere(['like', 'Postcode', $this->Postcode])
        ->andFilterWhere(['>=', 'price', $this->minprice])
        ->andFilterWhere(['<=', 'price', $this->maxprice])
        ->andFilterWhere(['=', 'option', $this->option])
        ->andFilterWhere(['like', 'description', $this->description]);
   return $dataProvider;
}
}

I added the public $minprice and $maxprice as I was receiving this error:

Getting unknown property: app\models\PropertiesSearch::minprice

However, the query doesn't work, in my URL it shows the user input but the query isn't following through. I would have thought that ($model, 'minprice') gives the field a name and that $this-minprice gets that value. It works when I make public $minprice = '$100' and $maxprice = '$300', so they must be overwriting the users input, but if I remove them I get the previous error again, what am I doing wrong?


Php code to import excel file to database


I want to import Excel data to my database using PHPExcel. Below is my code.

When I upload the excel file and submit the form, I can echo out the table but no data is being stored in the database, Can anyone please help me with this.

<?php

# Database Connection
$dbc = mysqli_connect('localhost', 'root', 'ron143', 'tcc') OR die('Error: '.mysqli_connect_error());

/** Include path **/
#set_include_path(get_include_path() . PATH_SEPARATOR . 'PHPExcel/Classes/');

/** PHPExcel_IOFactory */
include 'PHPExcel/Classes/PHPExcel.php';

/** PHPExcel_IOFactory */
include 'PHPExcel/Classes/PHPExcel/IOFactory.php';

# Upload the file to server
$file = $_FILES["file"]["name"];
$target_dir = "../../temp/";
$target_file = $target_dir . basename($file);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
$xls_url = "$target_dir$file";

$inputFileName = $xls_url;
$inputFileType = $_POST['file_type'];
$sheetname = '0'; /** input the worksheet number to read. 0 for first and 1 for second worksheet */

/**  Create a new Reader of the type defined in $inputFileType  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);

/**  Advise the Reader that we only want to load cell data and not its formating or any formula set on it **/
$objReader->setReadDataOnly(true);

/**  Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);

//  Get worksheet dimensions
$objWorksheet = $objPHPExcel->getSheet($sheetname);
$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'

$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5

echo '<table>' . "\n";
for ($row = 2; $row <= $highestRow; ++$row) {
    echo '<tr>' . "\n";

for ($col = 0; $col <= $highestColumnIndex; ++$col) {

    echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";

  }
  echo '</tr>' . "\n";
}
  echo '</tr>' . "\n";

#$q = "INSERT INTO products (product_name, product_code, category1, category1_id, category2, category2_id, stylename, grams, thickness, width, length, color_ground, color_border, material, backing, reed, weave, ply, pile, care, precaution, use, tag, image, link) VALUES(`".$val[0]."`, `".$val[1]."`, `".$val[2]."`, `".$val[3]."`, `".$val[4]."`, `".$val[5]."`, `".$val[6]."`, `".$val[7]."`, `".$val[8]."`, `".$val[9]."`, `".$val[10]."`, `".$val[11]."`, `".$val[12]."`, `".$val[13]."`, `".$val[14]."`, `".$val[15]."`, `".$val[16]."`, `".$val[17]."`, `".$val[18]."`, `".$val[19]."`, `".$val[20]."`, `".$val[21]."`, `".$val[22]."`, `".$val[23]."`, `".$val[24]."`)";
#$r = mysqli_query($dbc, $q);

if($q!='') $q.=',';
$q.='(\''.mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colproduct_name, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colproduct_code, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colcategory1, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colcategory1_id, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colcategory2, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colcategory2_id, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colstylename, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colgrams, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colthickness, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colwidth, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($collength, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colcolor_ground, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colcolor_border, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colmaterial, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colbacking, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colreed, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colweave, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colply, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colpile, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colcare, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colprecaution, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($coluse, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($coltag, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colimage, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($collink, $row)->getValue()).'\')';

if($q!='') {
    $q='INSERT INTO products (product_name, product_code, category1, category1_id, category2, category2_id, stylename, grams, thickness, width, length, color_ground, color_border, material, backing, reed, weave, ply, pile, care, precaution, use, tag, image, link) VALUES '.$q;
    $r=mysqli_query($dbc, $q);
    }


?>


PHP - How to get images from Instagram for more then 1 tag


Guys i'm working on PHP script which is getting all images for a specific tag in Instagram.

Here is my code:

<?PHP
 function callInstagram($url)
    {
    $ch = curl_init();
    curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 2
    ));

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
    }

    $tag = "sweden";
    $client_id = "1e0f576fbdb44e299924a93cace24507";
    $Next_URL = $_GET["nexturl"];
    if($Next_URL == ""){
    $url = 'http://ift.tt/SUv5zZ'.$tag.'/media/recent?client_id='.$client_id.'&count=24';
    } else {
    $url =  $Next_URL;
    }
    $inst_stream = callInstagram($url);
    $results = json_decode($inst_stream, true);
    $maxid = $results['pagination']['next_max_id'];
    $nexturl = $results['pagination']['next_url'];
    //Now parse through the $results array to display your results... 
    ?>
    <div class="holder" style="display:block;margin-left:70px;">
    <?PHP
    foreach($results['data'] as $item){
        $image_link = $item['images']['thumbnail']['url'];
        $big_image = $item['images']['standard_resolution']['url'];
    echo "Image: $image_link";
    }

This script is getting information about only one tag - sweden.

How i can make this code get all the information about more then one tag, for example let's say for another two tags - england and germany ?

Thanks in advance!


header redirect with include file


I've looked around on here and couldn't locate any solution for my little problem.

I currently have this following IF statment

if($page==1) {
    $sql = "UPDATE page SET page='1' WHERE id=1";
          INCLUDE 'month.php';
          header("Refresh: 10; url=http://XXXXX.co.uk/?p=2");           
    }

Which currently updates a database according to what page it is on and then includes the current month calendar file and I hoped I could redirect it to page number 2 which is very much similar but loads another calendar and the SQL adds +2 to the database.

In essence it's just a loop I've made and it just reads a SQL database to see what page it needs to load next< I know there's better ways to create a loop (just to scroll through 3 PHP pages) but I'm not that great at PHP..

So i'm just wondering really, could anybody help me to have that include statement along with the header refresh?

Like said the purpose is so that the pages rolls a loop, I've managed to get it all to work with an iframe (instead of the header) but it takes a few seconds longer for the frame window to load.


How can i use PHP break condition with yii2?


How can i use PHP break condition with yii2? Please help me.

echo implode(PHP_EOL, str_split($string, $break));


Merge Dependency Injection Parameters by key


I am new to Symfony. I need to create likely 2 or 3 separate bundles. Each bundle extends DependencyInjection providing an array typed parameter with key:navigations but with different values.

nav.xml on bundle page:

<parameters>
    <parameter key="navigations" type="collection">
        <parameter key="page" type="collection">
            <parameter key="label">Page</parameter>
            <parameter key="url">%admin%/page</parameter>
        </parameter>
    </parameter>
</parameters>

nav.xml on bundle blog:

<parameters>
    <parameter key="navigations" type="collection">
        <parameter key="blog" type="collection">
            <parameter key="label">Blog</parameter>
            <parameter key="url">page</parameter>
        </parameter>
    </parameter>
</parameters>

when I do:

$nav = $this->container->getParameter('navigations');
dump($nav);

I only get last defined parameters. How should I merge them ?


Posting to a Facebook page is showing on the "POSTS TO PAGE" panel


I got the code below from another website which seems to be working fine. The only problem is that posts appear on the "POSTS TO PAGE" section of the Facebook page instead of appearing on the page timeline directly.

Any idea why?

Also, the code works when I use the access token, not the app access token. When using app access token, I get an error message saying: "(#200) The user hasn't authorized the application to perform this action"

<?php
// require Facebook PHP SDK
// see: http://ift.tt/1fCaYUH
require_once("/YOUR_PATH_TO/facebook_php_sdk/facebook.php");

// initialize Facebook class using your own Facebook App credentials
// see: http://ift.tt/1n65vdg
$config = array();
$config['appId'] = 'YOUR_APP_ID';
$config['secret'] = 'YOUR_APP_SECRET';
$config['fileUpload'] = false; // optional

$fb = new Facebook($config);

// define your POST parameters (replace with your own values)
$params = array(
  "access_token" => "YOUR_ACCESS_TOKEN", // see: http://ift.tt/L1kwN8
  "message" => "Here is a blog post about auto posting on Facebook using PHP #php #facebook",
  "link" => "http://ift.tt/1hBHVQg",
  "picture" => "http://ift.tt/1hBHVQj",
  "name" => "How to Auto Post on Facebook with PHP",
  "caption" => "www.pontikis.net",
  "description" => "Automatically post on Facebook with PHP using Facebook PHP SDK. How to create a Facebook app. Obtain and extend Facebook access tokens. Cron automation."
);

// post to Facebook
// see: http://ift.tt/1p38EHk
try {
  $ret = $fb->api('/YOUR_FACEBOOK_ID/feed', 'POST', $params);
  echo 'Successfully posted to Facebook';
} catch(Exception $e) {
  echo $e->getMessage();
}
?>


Post and Get value by jquery ajax


How can I add my values owdid and visited id after clicking below link by ajax?

<a href="index.php" onclick="insertvisit(<?php echo $interestid;?>)">member1</a>

Below is my insertvisit function. I have defined owdid and interestid

function insertvisit(visitedid) {
  $.ajax({
       type: "POST",
       url: 'insertvisit.php',
       data:{'field1' : owdid, 'field2' : visitedid},
       success:function(html) {
       }
  });
}

and below is insertvisit.php

global $pdo;
$ownid = $_GET['field1'];
$interestid =$_GET['field2'];

$query = $pdo->prepare("UPDATE tablem SET field1= ? WHERE field2= ?");
$query -> bindValue(1, $ownid);
$query -> bindValue(2, $interestid);
$query -> execute();

Please help thanks.


How to get a table class which is being displayed through ajax


I have a main page which has a div with the id of displayTable. In that a table GETs loaded through AJAX from another php page.

The table is laid out like this:

<div class="table-responsive">
      <table class="table table-bordered table table-condensed">
        <thead>
          <tr>
            <td>Name</td>
            <td>Blah Blah</td>
            <td>Blah Blah</td>
            <td>Blah Blah</td>
            <td>Total</td>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Dilbert</td>
            <td>Rob</td>
            <td>Blah</td>
            <td>Blah</td>
            <td>Blah Blah Blah</td>
          </tr>
        </tbody>
      </table>
    </div>

I am attempting at using this jquery code to make the first tr fixed. So, in the example above, Dilbert and Name would be fixed and the rest is scrollable. However, I cannot seem to get to the table and it doesn't seem to affect it or do anything.

    var $table = $('#displayTable .table');
    var $fixedColumn = $table.clone().insertBefore($table).addClass('my-sticky-col');

    $fixedColumn.find('th:not(:first-child),td:not(:first-child)').remove();

    $fixedColumn.find('tr').each(function (i, elem) {
    $(this).height($table.find('tr:eq(' + i + ')').height());
    });


Relative path to sub-directory in PHP and Apache's htaccess file


I am working on my own PHP Framework. I am currently developing it on localhost and everything related to project is in subfolder called RuddyPhpFramework, so the path look like this:

localhost/RuddyPhpFramework/

In that folder, I do have index.php, the init point of whole Framework. I am currently working on my own router, but I have a two problems. First, in Apache's htaccess file a have this:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) RuddyPhpFramework/index.php [L]

So whenever someone acces a page like this:

localhost/RuddyPhpFramework/something/smtelse/

The index.php will init the application and echo a path for me, which is:

[path] => /RuddyPhpFramework/something/smtelse/

But that is not excatly what I want. What I want is to get a relative path to subfolder (I don't know if I am explaining this correctly), for example:

[path] => /something/smtelse/

And another problem is that I want to setup the htacces so the last line would look something like this:

RewriteRule (.*) index.php [L]

So it will go for the index.php in the folder where is the htaccess file (/RuddyPhpFramework/index.php) and not /index.php, without specifying the foler, because if someone else will be using the framework, he might have it in a folder with different name.


Codeigniter Form Validation Callback Function


I'm trying to create a form validation callback function but I'm having a little trouble getting my head around it.

What I am trying to do is create a contact form where with a join the mailing list option. If the option to join the mailing list is checked I want the name and email of the person to be added to the mailing list database. This part works perfectly however I also want the function to check the database to ensure that the email address being added is unique and this is the bit that I just can't get my head around.

Controller:

public function contact()
{
    $this->load->helper('form');
    $this->load->library('form_validation');

    $this->form_validation->set_rules('name', 'your name', 'required', array('required'=>"<p class='required'>Please provide %s</p><br>"));
    $this->form_validation->set_rules('email', 'your email address', 'required', array('required'=>"<p class='required'>Please provide %s</p><br>"));

    if($this->form_validation->run() == FALSE)
    {
        $this->load->view('templates/headder');
        $this->load->view('contact');
        $this->load->view('templates/footer');
    }
    else
    {
        $this->load->library('email');

        $name = $this->input->post('name');
        $email = $this->input->post('email');
        $phone = $this->input->post('phone');
        $message = $this->input->post('message');
        $list = $this->input->post('mailing_list');

        $email_message = "Name: $name<br>Email: $email<br>Phone: $phone<br>Message:<br>$message";

        $this->email->initialize();
        $this->email->from($email, $name);
        $this->email->to('myaddress@mydomain.co.uk');
        $this->email->subject('New Query');
        $this->email->message($email_message);
        $this->email->send();

        if($this->email->send()){
        $this->load->view('send_error');
        }
        else
        {
            if($list == 'no')
            {
            $this->load->view('sent');
            }
            else
            {
                $this->form_validation->set_rules('email', 'Email', 'is_unique[mail_list, email]');


                if($this->form_validation->run() == FALSE)
                {

                $this->load->model('mailing_listm');
                $this->mailing_listm->add_name();
                $this->load->view('sent'); 
                }
                else
                {
                $this->load->view('contact');
                }

            }
        }
    }
}

Error Message:

A Database Error Occurred

Error Number: 1064

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 ' email 'myaddress@mydomain.co.uk' LIMIT 1' at line 3

SELECT * FROM `mail_list`, `email` WHERE mail_list, email 'myaddress@mydomain.co.uk' LIMIT 1

Filename: libraries/Form_validation.php

Line Number: 1134

Hopefully someone will be able to let me know what daft thing I've done this time.

Also, This function is turning into a bit of a monster, it's the most complicated thing I've every tried to write. Is there any way that I can split it out so that it is made up of several smaller functions instead of one gargantuan one?

Thanks,

EDIT I have updated my code in line with the comment below about using is_unique however now I am receiving an error message.


Using Laravel Eloquents HasManyThrough relation with multiple relations through polymorphism


I got a rather simple application where a user can report other users comments and recipes. I use a polymorphic relation to store the reports. This all works fine, however I am now trying to get the offenses that a user has made.

Getting his own reports is not a problem, this can be done simply using user->reports() but I would very much like to get the reports in which other people has reported said user. I can get this to work using either the hasManyThrough relation or queries BUT only on one model at a time.

ex.

public function offenses() {
    return $this->hasManyThrough('Recipe', 'Reports');
}

Or

->with('user.recipe.reports')

The problem is that my reportable object is not just recipes, it could be comments, images etc. So instead of having to use multiple functions, the logical way would be to somehow parse the relationship of hasManyThrough multiple parameters.

Theoretically looking like this:

public function offenses() {
    return $this->hasManyThrough(['Recipe', 'RecipeComments'], 'Reports');
}

Is this in any way possible? With some undocumented syntax? If not is there any clever work-arounds/hacks?

Possible solution?

Would an acceptable solution be to add another column on my report table and simply add offender_id like this?

ID | User_id | Offender_id | Reportable_type | Reportable_id

This would mean I could simply make a relation on my user model that connects offenses through that column. But would this be considered redundant? Since I already have the offender through the reportable model?


Models

Polymorphic Model

class Report extends Model {
    public function reportable() {
        return $this->morphTo();
    }

    public function User() {
        return $this->belongsTo('App\User');
    }
}

Recipe Model

class Recipe extends Model {
    public function user() {
        return $this->belongsTo('App\User');
    }

    public function reports() {
        return $this->morphMany('App\Report', 'reportable');
    }
}

Comment Model

class RecipeComment extends Model {   
    public function user() {
        return $this->belongsTo('App\User');
    }

    public function reports() {
        return $this->morphMany('App\Report', 'reportable');
    }
}


I have the same error message when i put any error in the file


when I submit this form i have the same error message all the time . even if i put right or wrong password or don't put password or i write the name of the data base wrong . all of this wrongs i have the same error message : Please enter a username and password . so what is the problem . and i am sure about my fields on data base .

    <?

    session_start();
    $username = $_POST['username'];
    $password = $_POST['password'];


    if ($username && $password)
    {

        $connect = mysql_connect("localhsost","root","adminffpass") or die("Couldent connet to database ");
        mysql_select_db("login") or die("No data base found ");

        $query = mysql_query("SELECT * FROM users WHERE username='$username'");

        $numrows = mysql_num_rows($query);

        if ($numrows !=0)
        {

            while ($row= mysql_fetch_array($query)) 
            {

                $dbusername = $row['username'];
                $dbpassword = $row['password'];

            }

            if ($username == $dbusername && $password==$dbpassword)
            {
                echo "Login successul .<a href='memeberarea.php'>Click to enter member area</a>";
                $_SESSION['username'] = $dbusername;
            }
            else
                echo "incorrect  password  ";

        }
        else
           die ("That user name dosent exist");

   }
   else
     die ("Please enter a username and password");


    ?>


convert csv file to csv UTF8 by php


I got .csv file from client but when I read it with PHP, it show some text can't read. I try to upload and open with google sheet and then export .csv again with google. it work perfect when I read it with php.

Are there any way to convert .csv to .csv UTF8 without using google ? because client will send .csv to server everyday automatic. and then my php script will read and import .csv data into database. please help

Thanks


IFRAME Outlook Calendar (Office365)


I'm building a script which jumps around to index.php?p=1 - 3 which loads the calendars in what I hoped would be an iframe however Ive just found out that they are blocked.

Is there any alternative?


404 Error on ZF2 skeleton application on all tutorials


I am trying to learn Zend Framework 2. I have followed both the tutorial found in the ZF2 user guide at http://ift.tt/1zNXHOx and the book Learn ZF2: Learning by example. I've also tried a few other tutorials. I feel like I have wasted so much time and money trying to learn Zend Framework, and can't even get started because I can't even get the welcome screen to load. I have tried so many different things and can not even get the Framework to work. I can get the files to download with Git and Composer (just like in the tutorials). I go to pull up the welcome page and I get the same thing on every tutorial. The header and footer load, but the page is just a 404 error. I wish I could load a picture, but I'm new to Stack Overflow and don't have enough reputation points to do so. You can see an image of what I am getting here: http://ift.tt/1Gt0CTe I am using the PHP server, included with PHP5, and have made no changes at all to any of the Zend Framework file.