Affichage des articles dont le libellé est Active questions tagged php - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged php - Stack Overflow. Afficher tous les articles

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