Quantcast
Channel: PHP Freaks: PHP Help
Viewing all 13200 articles
Browse latest View live

A little help with setting up cookies

$
0
0

Here's a scenario.

 

I am setting up a sponsor referral link. If any user signs up on the site through that referral link, they will be matched with the sponsor of that referral link. Normally I can do this using a simple GET method but I want to use cookies so that the referral link will be valid for 30 days. So if a user decides to come back to the site  a week later, they will still be matched with that sponsor assuming they haven't deleted their cookies.

 

For eg.

// referral link
mysite.com/signup?sponsor=john 

Here is my cookie code. The issue i am having is that if I go to a different page on the site and come back to the signup page, the cookie gets reset or becomes invalid.  Can you tell me what i'm doing wrong? Do I have to use the database to store the cookies or what?

  $get_user = $_GET['sponsor'];

  $number_of_days = 30 ;
  $date_of_expiry = time() + 60 * 60 * 24 * $number_of_days ;
  setcookie( "sponsor", $get_user, $date_of_expiry);

  if(isset($_COOKIE['sponsor'])) {
      echo 'set';
  } else {
      echo 'not set';
  }

Namespace and PSR-4 Autoloader

$
0
0

The following example is from http://www.php-fig.org/psr/psr-4/examples/

 

<?php
/**
 * An example of a project-specific implementation.
 *
 * After registering this autoload function with SPL, the following line
 * would cause the function to attempt to load the \Foo\Bar\Baz\Qux class
 * from /path/to/project/src/Baz/Qux.php:
 *
 *      new \Foo\Bar\Baz\Qux;
 *
 * @param string $class The fully-qualified class name.
 * @return void
 */
spl_autoload_register(function ($class) {


    // project-specific namespace prefix
    $prefix = 'Foo\\Bar\\';


    // base directory for the namespace prefix
    $base_dir = __DIR__ . '/src/';


    // does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        return;
    }


    // get the relative class name
    $relative_class = substr($class, $len);


    // replace the namespace prefix with the base directory, replace namespace
    // separators with directory separators in the relative class name, append
    // with .php
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';


    // if the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});
  1. In $prefix, is the only reason to use double backslashes to prevent escaping trailing single or double quotes or other special characters if using double quotes?
  2. Can/should multiple spl autoloaders be registered in the same file?  If so, please give an example.
  3. Let's say I had the following index.php and MyClass.php file with locations as shown.
    1. If I as a vendor wanted "Michael" to be included in all the script I wrote, it would be considered the top-level namespace name (AKA “vendor namespace”), right?
    2. Is my assignment of $prefix correct?
    3. Assuming I don't wish to modify its source code, where should pimple.php be located and how should spl_autoload_register be set up.
    4. Could/should the magic constant __NAMESPACE__ be used in this autoloader?
    5. Is constant __NAMESPACE__ and keyword namespace basically to means to accomplish the same objective?  Since already in that namespace, won't the same class be evoked and using them provides no new outcome?

file: /var/www/public/index.php

<?php
namespace Michael\MyProject;

spl_autoload_register(function ($class) {
    // project-specific namespace prefix
    $prefix = 'Michael\\';   //Is this correct?

    // base directory for the namespace prefix
    $base_dir = __DIR__ . '/../src/';

    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }
    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    if (file_exists($file)) {
        require $file;
    }
});

$myClass=new MyClass();
$pimple = new \Pimple(); //Old version 1 which doesn't use namespace

$classname='mine()';
$a = __NAMESPACE__ . '\\' . $classname;
$aObj = new $a;

namespace\blah\mine();

file: /var/www/src/Bar/MyClass.php

<?php
namespace Foo\Bar;

class MyClass{}

 

How to write a function that replaces text

$
0
0

I'd like to know how to go about writing a function that replaces text in a specific way. Below is my sample code.

<?php
$arrayOfSingleWords = array("Cats", "Dogs", "Horses", "Lions");
$arrayOfDoubleWords = array("blue Cats", "red Dogs", "green Horses", "Lions Nest");
$arrayOfTripleWords = array("blue coller Cats", "Dogs eating food", "green Horses riding", "Yellow Lions roaring");
$arrayOfQuadrupleWords = array("Blue cats napping nearby", "brown Dogs jumping around", "Blue dog Horses standing", "Lions den is blue");

$description = "There once was a dog named sue that lived with some horses and red dogs. The dogs eating food were the " +
				"most like green horses riding. Blue coller cats were also very similar to brown dogs jumping around " +
				"beside the blue cats napping nearby";
?>

I would like to write a function that takes in the $description variable and changes all phrases found in the arrays to links that link somewhere. Perhaps I need an associative array instead to do this, but i'm not sure.

 

I would like the function to start with the longest phrases first(from the $arrayOfQuadrupleWords) and work it's way back to the arrayOfSingleWords. I think some loops are involved but i'm not sure which php built in functions would accomplish this task.

 

The final output should look similar to the following.

 

"There once was a <a href="linksomewhere.php">dog</a> named sue that live with some <a href="linksomewhereelse.php">horses</a> and <a href="linksomewhereyetagain.php">red dogs</a>"

 

and so on.

 

can anyone help me out here on this one? The arrays of words will be pulled from a database, perhaps they would be associative arrays that also include which link to link to,(I think that's how it should work, but not sure, any help appreciated)

New alt tag problem

$
0
0

Hi Guys can anyone please help me with this alt tag problem I have please.

 

I have 12 auction on my site and each picture as no alt tag showing

 

 

Code:

 

<div class="auction_slot">

        <div class="pos" id="so_auction_<?=$rows->auc_id?>">

            <div class="auction_name"><a href="<?=site_url('auctions/'.url_title($rows->auc_id.'-'.$rows->product_name))?>" class="auction_name" title='<?=$rows->product_name?>'><?=$rows->product_name?></a></div>

            <a href="<?=site_url('auctions/'.url_title($rows->auc_id.'-'.$rows->product_name))?>" class="auction_img"><img src="<?=base_url()?>auction_images/<?=$rows->feat_pic?>" width="110" height="90" alt="<?=$rows->feat_pic?>"><?php //AUCTION_IMG_SRC($rows->feat_pic,'AUCTION');?></a>

 

This section is what I thought I would need to change  feat_pic

 

My database column name is alt_tag

 

Thanking ever one in advance

Starting numbers in for loop in php with 00 characters

$
0
0

I need for loop to display images..
..
but image name must start with 00... like 001.jpg, 002.jpg
.
I write my code like this..
for ($i = 001; $i <= 10; $i++) {

echo "<img src='Ony/Ony-Small/'.str_pad($i, 3, '0', STR_PAD_LEFT);.'.jpg' class='img-responsive mx-auto d-block center-block img-thumbnail'>";

}
..
but this is not working
..
can anybody suggest me the right way

 

implementing php long polling

$
0
0

I want to use php-long polling in my php script to get the instant display of data when admin changes anything from backend.

I have browsed for solutions, But could not find any.

I have downloaded php-long-polling- master from github. There , i have a file server.php.

There the code is like this

 // PHP caches file data, like requesting the size of a file, by default. clearstatcache() clears that cache
    clearstatcache();
    // get timestamp of when file has been changed the last time
    $last_change_in_data_file = filemtime($data_source_file);

    // if no timestamp delivered via ajax or data.txt has been changed SINCE last ajax timestamp
    if ($last_ajax_call == null || $last_change_in_data_file > $last_ajax_call) {

        // get content of data.txt
        $data = file_get_contents($data_source_file);

        // put data.txt's content and timestamp of last data.txt change into array
        $result = array(
            'data_from_file' => $data,
            'timestamp' => $last_change_in_data_file
        );

        // encode to JSON, render the result (for AJAX)
        $json = json_encode($result);
        echo $json;

        // leave this loop step
        break;

    } else {
        // wait for 1 sec (not very sexy as this blocks the PHP/Apache process, but that's how it goes)
        sleep( 1 );
        continue;
    }
}

If anything we change in data.txt, it displays as and when in real time. But i am not getting how and where i can add the query or how do i include it in my file.

in server.php, it is there like

// where does the data come from ? In real world this would be a SQL query or something
    $data_source_file = 'data.txt';

but where and how can i add sql query?

can somebody help me how can i start with or how can i add sql query

Search sidebar in php

$
0
0

I want to develop left side bar to display all categories links as list items and sub categories as sub list items links in vertical sidebar navigation 

Sorting data by smallest distance first from Distance Matrix service

$
0
0

Hi, I'm using Google's distance matrix service to calculate the distance between a user-submitted postcode and the postcodes of members in a mySQL database. Which works fine except for one thing, it shows the members in a random order, I need them to be displayed in order of closest (smallest distance) first. (Nothing in the API documentation about doing this). Code is below:

if($_POST['find-by-postcode'])
{
    $postcode_input = $_POST['_Postcode'];
    
    $getmembers = $mysqli->query("SELECT * FROM members WHERE Postcode NOT LIKE ''");
        
    while ($row = $getmembers->fetch_assoc()) {  
      $memberid = $row["MemberID"];
  $firstname = $row["FirstName"];
  $surname = $row["Surname"];
  $email = $row["Email"];
  $addressline1 = $row["AddressLine1"];
  $addressline2 = $row["AddressLine2"];
  $town = $row["Town"];
  $dateadded = $row["DateAdded"];
  $formatteddate = date("F j, Y", strtotime($dateadded) );
  $clientele = $row["Clientele"];
  $photo = $row["Photo"];
  $county = $row["County"];
  $postcode_member = $row["Postcode"];
        
    $postcode2 = str_replace(' ', '', $postcode_input);
    $postcode1 = str_replace(' ', '', $postcode_member);
 
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$postcode2&destinations=$postcode1&mode=driving&language=en-EN&sensor=false";
 
$data = @file_get_contents($url);
 
$result = json_decode($data, true);

?>
<div class="sixteen columns">
<h3><?php echo $firstname.' '.$surname; ?></h3>
<p>Based in <strong><?php echo $town; ?></strong></p>
<p><strong>Email: </strong><?php echo '<a href="mailto:'.$email.'">'.$email.'</a>'; ?></p>
<p><strong>Address: </strong><?php echo $addressline1.','.$addressline2.','.$town.','.$postcode; ?></p>
<p><strong>Clientele: </strong><?php echo $clientele; ?></p>

<?php //This is the bit that outputs the distance between the 2 postcodes
foreach($result['rows'] as $distance) {
    echo '<p><span class="boldgreen" style="color:#090; font-weight:bold;">Distance from you: ' . $distance['elements'][0]['distance']['text'] . ' (' . $distance['elements'][0]['duration']['text'] . ')</span></p>';
}
?>

The problem of course is that the distance data doesn't come from the mySQL database but from Google's API. So I've tried creating a new variable from the foreach loop just above, as follows:

$calculateddistance = $distance['elements'][0]['distance']['text'];

And then put this into the db query, i.e: ORDER BY $calculateddistance ASC - but that didn't work, I created a second while loop that included this (I had to create the first one in order to extract the member's postcode to make the comparison) but no joy. Also tried using fetch_array instead of fetch_assoc but that didn't work.

Anyone know how I can get this to sort by smallest distance first? Thanks!

Session_start(): Failed

$
0
0

Hello guys
I got this error  Warning: session_start(): Failed to read session data: user (path: C:\app\php7.1\tmp) in C:\app\Apache2.4.29\htdocs\PhpMyAdmin\www\konference\libraries\joomla\session\handler\native.php on line 260 Error displaying the error page: Application Instantiation Error: Failed to start the session. 
Here is native.php https://pastebin.com/HjYGPvjr

Can someone help me ? 
 

Creating an object using another class's method

$
0
0

Is this a bad idea?  It works, but that doesn't mean it is a good idea.  If not a bad idea, is it possible to implement using the alias class name ($router->getObj('Controllers\Test1')->getSomething();)?  Ideally, the script to deal with the alias would be in Router and not the first file.

<?php
use Michael\SimpleRouter;
use Michael\EmbeddedWebserver\Controllers;

spl_autoload_register(function ($class) {
    $prefix = 'Michael\\';
    $base_dir = __DIR__ . '/../src/';
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) return;
    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    if (file_exists($file))  require $file;
});

$router = new SimpleRouter\Router();
$test1=$router->getObj('Michael\EmbeddedWebserver\Controllers\Test1')->getSomething();
$test2=$router->getObj('Michael\EmbeddedWebserver\Controllers\Test2',1,2,3)->getSomething();
<?php
namespace Michael\SimpleRouter;
class Router implements RouterInterface {

    public function getObj($class) {
        $args=func_get_args();
        unset($args[0]);
        $o = new \ReflectionClass($class);
        return $args?$o->newInstanceArgs($args):$o->newInstanceArgs($args);
    }
    public function otherMethodsAsAppropriate();


 }
<?php
namespace Michael\EmbeddedWebserver\Controllers;
class Test1 {

    public function getSomething()
    {
        return 10;
    }
}
<?php
namespace Michael\EmbeddedWebserver\Controllers;
class Test2 {

    public function __construct($one, $two, $three)
    {
        $this->one=$one;
        $this->two=$two;
        $this->three=$three;
    }

    public function getSomething()
    {
        return 10*$this->one*$this->two*$this->three;
    }
}

 

Holding values in textarea PHP

$
0
0

HI All,

 

How to hold the values in text area using PHP validation.

Can anyone please help?

 

Thanks!

Problem with notifications sent out when data added

$
0
0

Having an odd issue with an internal messaging system which sends a message to a member messages table (it also sends a message to the sender, so they're basically cc'd and have a copy). The messages themselves are simply copied to a mySQL table rather than sent out, users have to log in to see them. However the client also wanted a notification sent out via email to the members' email accounts, so that they are alerted when they have an internal message, and can then log into the system.

The problem is, although it works- messages are added to the db table and notifications are being sent out- rather than the notifications going ONLY to recipient and sender, they are being sent to EVERY member. So if Member 1 sends a message to Member 2, Members 1 and 2 get their notification (great) but Members 3, 4, 5, 6 etc. also get notifications even though there isn't a message waiting for them when they log in.

Checking in the db, only sender and recipient have the message logged for their user ID, so that works fine.

Any ideas as to why it's sending out notifications to all members and how I can stop it?

<?php
if($_POST['sendmessage'])
{
        foreach ($_POST['_RecipientID'] as $key => $recipientid)
            {
                $recipients .= "$recipientid, ";

            $recipientemail = $mysqli->real_escape_string($_POST['_RecipientEmail']);    
            $messagetext = $mysqli->real_escape_string($_POST['_MessageText']);    
            $sender = $mysqli->real_escape_string($_POST['_Sender']);    
            $dateadded = date('Y-m-d H:i:s');
                for ($i=0; $i<count($recipientid); $i++)
        $addmessagetotable = $mysqli->query("INSERT INTO messages (RecipientID, MessageText, Sender, DateSent) VALUES ('$recipientid','$messagetext','$sender','$dateadded')");
            }

            foreach ($_POST['_RecipientEmail'] as $key => $recipientemail)
            {
                for ($i=0; $i<count($recipientemail); $i++)
                $to = $recipientemail;
                    
$from = "noreply@domain";
$subject = 'You have a new message waiting in the Members Area.';
$separator = md5(time());
$eol = PHP_EOL;

// main header
$headers  = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";

$body = 'You have a new message waiting in the Members Area.'.$eol;
$body .= 'Log in at login.html to retrieve your message.'.$eol;

// send message
mail($to, $subject, $body, $headers);
//echo '<p>Message was successfully sent to '.$firstname.' '.$surname.'</p>';
                        }
echo '<p>Message was added to the system successfully.</p>';
}
?>

How to include files in other folders?

$
0
0

Hi,

As beginner to PHP, I tried everything I know to include a php file which is in another folder, but I had no success. So the folder structure I use is as following:

 

MyFolder (folder)
|
|--- phpseclib (folder)
|     |
|     |--- Crypt (folder)
|           |
|           |--- RSA.php
|
|--- foo.php
 
 
In foo.php, which its contents is listed below, I need to include RSA.php, which resides in MyFolder/phpseclib/Crypt/
but it just doesn't work. What am I doing wrong?
 
<?php
    namespace MyOwnNamespace;
    
    include('phpseclib/Crypt/RSA.php');
    // require_once 'phpseclib/Crypt/RSA.php'; // even this doesn't work
    
    class MyClass
    {
        public function MyFunction() {
            $rsa = new \Crypt_RSA();
            $rsa->setHash("sha256");
            ...
        }
    }
?>

 

How to execute a mySQL subquery in php?

$
0
0

PROBLEM: php returns null even though the SQL executes correctly in mySQL

As an example, I have here 2 tables and I want the student's latest grades from XS_Course:

  •  Student (SID, Name) pk is SID
  •  XS_Course (SID, CID, Date, Grade) pk is (SID+CID) and Date is in Datetime format

I constructed a SQL statement like this (the real SQL works well in mySQL):

SELECT s.Name, sc.CID, sc.Grade
FROM Student s RIGHT JOIN XS_Course sc ON s.SID=sc.SID
WHERE sc.CID LIKE 'IT%' AND sc.Date>= ("select date(max(sc2.Date)) from XS_Course sc2;")
ORDER BY s.Name;

If I take out the subquery, PHP returns a result set, so it is the subquery that is truipping up php...

 

Then I the wrapped the SQL in PHP, like this:

<?php
$con = mysqli_connect("localhost", "username", "password", "dbname");
/* check connection */
if (!$con) {
    die("Connection failed: ".mysqli_connect_error());
}

$sql = "SELECT s.Name, sc.CID, sc.Grade
FROM Student s RIGHT JOIN XS_Course sc ON s.SID=sc.SID
WHERE sc.CID LIKE 'IT%' AND sc.Date>= ("select date(max(sc2.Date)) from XS_Course sc2;")";

$result = mysqli_query($con, $sql);

/* instantiate an array to hold the JSON name-value pairs */
$response = array();

/* In the loop, put the "name" and data into array's name-value pair */
while($row=mysqli_fetch_array($result)){
    array_push($response, array("studentname"=>$row[0], "coursecode" =>$row[1], "recentgrade"=>$row[2]);}

/* encode the data inside a JSON-array */
echo json_encode(array("db_response"=>$response));

/* close connection */
mysqli_close($con);
?>

PROBLEM: PHP returns nothing when I run it in browser.

Would it be better if I execute 2 SQL stmts in php, the first to get the max(Date) into a php-variable and them use the variable to filter the result set in WHERE clause, like this:

$maxdate = "SELECT max(Date) FROM XS_Course;";
$sql = "SELECT s.Name, sc.CID, sc.Grade
FROM Student s RIGHT JOIN XS_Course sc ON s.SID=sc.SID
WHERE sc.CID LIKE 'IT%' AND sc.Date>= $maddate
ORDER BY s.Name;";

Didn't work either, tried a few variations...

 

Some help please :(
 

display text details and images of specific category id href link clicked from menu

$
0
0
echo '<li ><a href="sidebar.php?category='.$row["cid"].'">'.$row2["csname"].'</a></li>
 
<?php
$query3="SELECT * FROM items where category='sidebar.php?category'";

 I want to use this id of href in the query to display text and image of that category id

 


Critique script

$
0
0

I've used some libraries before and there always seems to be some magic under the hood.  My intent of this project was not to build a better framework than others out there (it isn't!), but to understand each line of code (I mostly do!).

 

I hope I am not asking too much, but would like a high level critique of my attempt to put together various concepts.  I am by no means expecting a line by line review, but feedback that I am basically "doing it right".  If there is also any constructive criticism you would like to give regarding any of the details, I will surely accept that as well.

 

A few specific topics I would like to here your opinions on are:

  1. My use of interfaces.
  2. Namespace and autoloading.
  3. Dependency injection and the use of pimple.  I may need to get rid of pimple and implement this scope myself to ensure I truly understand dependency injection.
  4. Whether I am applying the controller concept correctly.  I still question whether a controller should be passed to a router or the reverse or neither.
  5. My use of the request and response classes.  I might be confused between a response and a view.
  6. My approach to routes.
  7. How I deal with error handling.  I think this portion surely could be improved.
  8. My approach to authentication.
  9. Whether there are any common programming concepts which should be used in an application such as this one but are not being used.

 

Thank you in advance for any comments you are willing to give.

<?php
//namespace Michael\SimpleRouter;
use Michael\SimpleRouter;
use Michael\SimpleRouter\Request;
use Michael\SimpleRouter\Response;
use Michael\EmbeddedWebserver\Controllers;


session_start();
error_reporting(E_ALL);
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);


spl_autoload_register(function ($class) {
    $prefix = 'Michael\\';
    $base_dir = __DIR__ . '/../src/';
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }
    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    if (file_exists($file)) {
        require $file;
    }
});


// TBD whether default routes should be added by extending Pimple or in router (which is defined after user defined routes are set so much check them)
// Should I even bother using pimple?
require_once('../src/SimpleRouter/Pimple.php');
$c = new \Pimple();
//$c = new Container();


//Originally, I was planning on passing the view to pimple, but why bother?
//$c['view'] = function ($c) {return new SimpleRouter\View(__DIR__.'/../src/EmbeddedWebserver/templates');};
$c['template']=__DIR__.'/../src/EmbeddedWebserver/templates';


//Authority not sent to constructor thus use default 0 required authority
$router = new SimpleRouter\Router($c);


$auth=(new Controllers\Logon)->getAuthorityLevel();
$router->setAuthUser($auth);


//Routes are regex.  # Deliminator to be applied by router and # are not allowed in regex pattern.
$router->get('^/logon$', function(Request $request, Response $response){
    return($response->html('logon.html',[]));
});
$router->post('^/logon$', function(Request $request, Response $response){
    $controller=new Controllers\Logon();
    if($controller->validCredentials()) {
        $controller->setAuthorityLevel(1);
        return $response
        ->html('page.html',(new Controllers\Page)->getData($request))
        ->redirect('/page1');
    }
    else {
        return($response->html('logon.html',[]));
    }
});


$router->setAuthRequired(1,'/logon');    //subqential routes require authority value of 1


$router->delete('^/logon$', function(Request $request, Response $response){
    (new Controllers\Logon)->setAuthorityLevel(0);
    return($response->json(['success']));
});


$router->get('^/$|^/page1$', function(Request $request, Response $response){    //Both / and /page1
    return($response->html('page.html',array_merge((new Controllers\Page)->getData($request),['page'=>'Page 1'])));
});
$router->get('^/page2$', function(Request $request, Response $response){
    return($response->html('page.html',array_merge((new Controllers\Page)->getData($request),['page'=>'Page 2'])));
});
$router->get('^/page3$', function(Request $request, Response $response){
    return($response->html('page.html',array_merge((new Controllers\Page)->getData($request),['page'=>'Page 3'])));
});


$router->all('^/test$', function(Request $request, Response $response){
    return($response->json((new Controllers\Page)->getData($request)));
});
$router->all('^/test/(\w+)$', function(Request $request, Response $response){
    return($response->json((new Controllers\Page)->getData($request)));
});
$router->all('^/test/(\w+)/(\d+)$', function(Request $request, Response $response){
    return($response->json((new Controllers\Page)->getData($request)));
});


echo $router->run(); //Headers will be set in View if appropriate.
<?php
namespace Michael\SimpleRouter;
interface RouterInterface
{
    // Should _constructor be included? public function __construct($c, array $auth=[]);


    //Add callback for given HTTP method (all adds for each).  $auth overrides the required authority for the given route
    public function get($pattern, $callback, array $auth=[]);
    public function post($pattern, $callback, array $auth=[]);
    public function put($pattern, $callback, array $auth=[]);
    public function delete($pattern, $callback, array $auth=[]);
    public function all($pattern, $callback, array $auth=[]);


    //Updates the default authority
    public function setAuthRequired($authRequiredLevel,$unauthUrl,$unauthMethod=NULL);
    //Gets authority values
    public function getAuthRequired();


    //Sets users authority
    public function setAuthUser($auth);
    //Gets users authority
    public function getAuthUser();


    //Execute the route, set any headers, and return the results
    public function run();


}
<?php
namespace Michael\SimpleRouter;
interface RequestInterface
{
    public function getMethod();
    public function getUri();
    //Returns an unassociated array in the same order as the pattern
    public function getParams();
    //Return $_GET, $_POST, or PUT/DELETE data
    public function getData();
    //public function isAjax(); //Currently private
}
<?php
namespace Michael\SimpleRouter;
interface ResponseInterface
{
    //Should this class really have view functionallity or should view be injected?
    //All methods except for render() and error() return $this to allow chaining


    // Redirect browser
    public function redirect($location);
    // Create HTML or JSON
    public function html($template, $arr, $code=200);
    public function json($data, $code=200);
    // Display error in HTML or JSON as appropriate
    public function error($msg,$code);
    // Return created HTML or JSON
    public function render();
}
<?php
namespace Michael\SimpleRouter;
class Router implements RouterInterface {


    private $routes     =   ['GET'=>[],'POST'=>[],'PUT'=>[],'DELETE'=>[]];
    private $uri;
    private $method;
    private $lastEndpoint=[false,false];    //Error if repeating recursive endpoint
    private $authValue=0;           //The users authority
    private $authRequiredLevel=0;   //0 is unrestricted, and incrementing higher values require higher authority
    private $unauthUrl='/';         //URL to utilize if unathorized access level
    private $unauthMethod='GET';
    public $container  =   [];


    public function __construct($c, array $auth=[])
    {
        $this->container=$c;


        //remove query (duplicated in $_GET), index.php (just case), and then trailing backslash
        $this->uri = preg_replace('/index.php$/', '', explode('?', strtolower($_SERVER['REQUEST_URI']))[0]);
        if(strlen($this->uri)>1)  $this->uri=rtrim($this->uri,'/'); //uri will be: /foo/bar


        $this->method=$_SERVER['REQUEST_METHOD'];
        syslog(LOG_INFO,"Router Constructor: $this->uri $this->method");


        //$auth defines the default authority requirements and default fallback page
        if(isset($auth['authRequiredLevel'])) $this->authRequiredLevel=$auth['authRequiredLevel'];
        if(isset($auth['unauthUrl'])) $this->unauthUrl=$auth['unauthUrl'];
        if(isset($auth['unauthMethod'])) $this->unauthMethod=strtoupper($auth['unauthMethod']);
        if(isset($auth['authValue'])) $this->authValue=$auth['authValue'];   //Users authority level


        set_exception_handler(function($exception) use ($c){
            //Nothing to return to, so echo results?
            exit($c['phpErrorHandler'](new Request(), new Response($this->container['template']), $exception));
        });
        set_error_handler(function($errno, $errmsg, $filename, $linenum) {
            if (!(error_reporting() & $errno)) {
                return;
            }
            throw new \ErrorException($errmsg, 0, $errno, $filename, $linenum);
        });


        //Add default services.  TBD whether it would be more appopriate to extend Pimple to add these.  Is this the correct way to do this?
        $this->addToContainer('missingErrorHandler',function($c){
            return function ($request, $response) {
                return $response->error($request->getUri().' with method '.$request->getMethod().' does not exist on this server.',404);
            };
        });
        $this->addToContainer('phpErrorHandler',function($c){
            return function ($request, $response, $e) {
                return $response->error($e->getFile()." (".$e->getline().'): '.$e->getMessage(),400);
            };
        });
    }


    //Add to container with default option not to override (used by route constructor to add default services).
    private function addToContainer($name, $callback, $override=false) {
        if($override || empty($this->container[$name])) {
            $this->container[$name] = $callback;
        }
    }


    /* Add route pattern, callback, and auth for each method.
    Auth is an array specifing the required user authority to access the route and the url and http method to respond with if not authorized
    */
    public function get($pattern, $callback, array $auth=[]) {
        $this->setRoute('GET', $pattern, $callback, $auth);
    }
    public function post($pattern, $callback, array $auth=[]) {
        $this->setRoute('POST', $pattern, $callback, $auth);
    }
    public function put($pattern, $callback, array $auth=[]) {
        $this->setRoute('PUT', $pattern, $callback, $auth);
    }
    public function delete($pattern, $callback, array $auth=[]) {
        $this->setRoute('DELETE', $pattern, $callback, $auth);
    }
    public function all($pattern, $callback, array $auth=[]) {
        $this->setRoute(['GET','POST','PUT','DELETE'], $pattern, $callback, $auth);
    }
    private function setRoute($methods, $pattern, $callback, $auth) {
        if(strpos($pattern, '#')!==FALSE) {
            //trigger_error('"#" are not allowed in route pattern regex.');
            throw new \ErrorException('"#" are not allowed in route pattern regex.');
        }
        $authRequiredLevel=isset($auth['authRequiredLevel'])?$auth['authRequiredLevel']:$this->authRequiredLevel;
        $unauthUrl=isset($auth['unauthUrl'])?$auth['unauthUrl']:$this->unauthUrl;
        $unauthMethod=isset($auth['unauthMethod'])?$auth['unauthMethod']:$this->unauthMethod;
        foreach((array)$methods as $method) {
            $this->routes[$method][$pattern] = ['callback'=>$callback,'authRequiredLevel'=>$authRequiredLevel,'unauthUrl'=>$unauthUrl,'unauthMethod'=>$unauthMethod];
        }
    }


    /* USER ACCESS
    All routes have a given authority integer which is required to access.
    setAuthRequired() or in the constructor will set the required authority (default of 0) as well as the url and http method if user isn't authorized.
    After being set, it will be applied to all routes created after being setting.
    Users also have a given integer authority level which must be equal or greater than the route authority
    */
    public function setAuthRequired($authRequiredLevel,$unauthUrl,$unauthMethod=NULL) {
        if($authRequiredLevel)$this->authRequiredLevel=$authRequiredLevel;
        if($unauthUrl)$this->unauthUrl=$unauthUrl;
        if($unauthMethod)$this->unauthMethod=strtoupper($unauthMethod);
    }
    public function getAuthRequired() {
        return ['authRequiredLevel'=>$this->authRequiredLevel,'unauthUrl'=>$this->unauthUrl,'unauthMethod'=>$this->unauthMethod];
    }
    public function setAuthUser($auth) {
        $this->authValue=$auth;
    }
    public function getAuthUser() {
        return $this->authValue;
    }


    public function run() {
        if($this->lastEndpoint[0] && $this->lastEndpoint[0]===$this->uri && $this->lastEndpoint[1]===$this->method) {
            throw \ErrorException("Recursive call to same endpoint");
        }
        foreach ($this->routes[$this->method] as $pattern => $settings) {
            $pattern="#$pattern#";
            if (preg_match($pattern, $this->uri, $params) === 1) {
                syslog(LOG_INFO,"Router Run Match: $params[0] $this->method");
                if($this->authValue<$settings['authRequiredLevel']) {
                    $this->lastEndpoint=[$this->uri,$this->method];
                    $this->uri=$settings['unauthUrl'];
                    $this->method=$settings['unauthMethod'];
                    syslog(LOG_INFO,"Unauthorized.  Instead do: $this->method $this->uri");
                    return $this->run();
                }
                return call_user_func($settings['callback'], new Request($params), new Response($this->container['template']))->render();
            }
        }
        return $this->container['missingErrorHandler'](new Request(), new Response($this->container['template']));
    }


}
<?php
namespace Michael\SimpleRouter;
class Request implements RequestInterface {


    private $params  =   [];
    private $data=false;
    private $uri, $method;


    public function __construct(array $params=null)
    {
        if(is_null($params)) $params=[$_SERVER['REQUEST_URI']];
        $this->uri=$params[0];
        array_shift($params);
        $this->params=array_values($params);
        $this->method=$_SERVER['REQUEST_METHOD'];
    }


    public function getMethod() {
        return $this->method;
    }
    public function getUri() {
        return $this->uri;
    }
    public function getParams() {
        return $this->params;
    }
    public function getData() {
        if ($this->data!==false) return $this->data;
        switch($this->method){
            case 'GET':$this->data=$_GET;break;
            case 'POST':$this->data=$_POST;break;
            case 'PUT':
            case 'DELETE':  //Can a delete method have data?  Is it the same as $_GET or PUT?
                parse_str(file_get_contents("php://input"),$this->data);
                /*
                //Or do it per http://php.net/manual/en/features.file-upload.put-method.php?
                $putdata = fopen("php://input", "r");
                // Read the data 1 KB at a time and write to a stream
                while ($data = fread($putdata, 1024)) {
                fwrite($fp, $data);
                }
                fclose($fp);
                */
                break;
        }
        return $this->data;
    }
}
<?php
namespace Michael\SimpleRouter;
class Response implements ResponseInterface {
    private $folder;
    private $buffer=null;


    public function __construct($folder)
    {
        $this->folder=$folder;
    }


    public function render() {
        return $this->buffer;
    }


    public function html($template, $arr, $code=200) {
        if($code!==200) http_response_code($code);
        $template=file_get_contents("$this->folder/$template");
        $this->buffer=$arr?$this->substitute($template,$arr):$template;
        //or $this->buffer=$this->parse($template,$arr);
        return $this;
    }


    public function json($data, $code=200) {
        header('Content-Type: application/json');
        http_response_code($code);
        $this->buffer=$data?json_encode($data):null;
        return $this;
    }


    public function error($msg,$code)
    {
        return $this->isAjax()
        ?$this->json(['error'=>$msg],404)->render()
        :$this->html('error.html',['errorMessage'=>$msg],404)->render();
    }


    public function redirect($location)
    {
        header("Location: $location");
        return $this;
    }


    private function isAjax()
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }


    private function substitute($template, $values, $deliminator='{{}}',$preface=null) {
        $length=strlen($deliminator)/2;
        $open  = substr($deliminator, 0, $length);
        $close = substr($deliminator, $length);
        foreach ($values as $key => $data) {
            if(is_array($data)){
                $template=$this->substitute($template,$data,$deliminator,$key.'.');
            }
            else {
                $template = str_replace($open.$preface.$key.$close, $data, $template);
            }
        }
        return $template;
    }
    private function parse($template, $values) {
        ob_start();
        require("$this->folder/$template.html");
        $template = ob_get_contents();
        ob_end_clean();
        return $template;
    }


}
<?php
namespace Michael\EmbeddedWebserver\Controllers;
class Logon implements LogonInterface {


    public function validCredentials()
    {
        return isset($_POST['username'],$_POST['password']) && $_POST['username']=='michael' && $_POST['password']=='mypassword';
    }


    public function setAuthorityLevel($auth)
    {
        $_SESSION['authorized']=$auth;
    }


    public function getAuthorityLevel()
    {
        return isset($_SESSION['authorized'])?$_SESSION['authorized']:0;
    }
}
<?php
namespace Michael\EmbeddedWebserver\Controllers;
class Page implements PageInterface {


    public function getData($request)
    {
        return [
            'method'=>$request->getMethod(),
            'uri'=>$request->getUri(),
            'params'=>json_encode($request->getParams()),
            'data'=>json_encode($request->getData()),
        ];
    }
}

 

Message -- Warning: file_get_contents --

$
0
0

I am getting the Warning and not sure what my problem is. As you can see I am getting address data from a SQL Server and then trying to get the "lat" and "lng" information using a Google API and put that in an array that  I can use later to create a google road map. I will have about 200 locations in the array but it errors out on the first one. I have tried a different address but get the same error.Below is my data from the   echo $url ."<br>"; Thank You.

 

{ "results" : [ { "address_components" : [ { "long_name" : "1401", "short_name" : "1401", "types" : [ "subpremise" ] }, { "long_name" : "1000", "short_name" : "1000", "types" : [ "street_number" ] }, { "long_name" : "Rivergate Parkway", "short_name" : "Rivergate Pkwy", "types" : [ "route" ] }, { "long_name" : "Goodlettsville", "short_name" : "Goodlettsville", "types" : [ "locality", "political" ] }, { "long_name" : "Davidson County", "short_name" : "Davidson County", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "Tennessee", "short_name" : "TN", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United States", "short_name" : "US", "types" : [ "country", "political" ] }, { "long_name" : "37072", "short_name" : "37072", "types" : [ "postal_code" ] } ], "formatted_address" : "1000 Rivergate Pkwy #1401, Goodlettsville, TN 37072, USA", "geometry" : { "location" : { "lat" : 36.302848, "lng" : -86.69994199999999 }, "location_type" : "ROOFTOP", "viewport" : { "northeast" : { "lat" : 36.30419698029149, "lng" : -86.69859301970848 }, "southwest" : { "lat" : 36.30149901970849, "lng" : -86.70129098029149 } } }, "place_id" : "EjgxMDAwIFJpdmVyZ2F0ZSBQa3d5ICMxNDAxLCBHb29kbGV0dHN2aWxsZSwgVE4gMzcwNzIsIFVTQQ", "types" : [ "subpremise" ] } ], "status" : "OK" } 

 

 

and this is what I get from the warning.

 

Warning: file_get_contents({ "results" : [ { "address_components" : [ { "long_name" : "1401", "short_name" : "1401", "types" : [ "subpremise" ] }, { "long_name" : "1000", "short_name" : "1000", "types" : [ "street_number" ] }, { "long_name" : "Rivergate Parkway", "short_name" : "Rivergate Pkwy", "types" : [ "route" ] }, { "long_name" : "Goodlettsville", "short_name" : "Goodlettsville", "types" : [ "locality", "political" ] }, { "long in /var/www/html/chartjs/phpgeo.php on line 44

 

 

 

<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

$connect =odbc_connect("removed");
if(!$connect) {
exit("Connection Failed: " . $connect);
}
$gr_total = 0;
$sql="
select distinct
ltrim(rtrim(cmoAddressLine2)) as Street
,ltrim(rtrim(cmoCity)) as City
,ltrim(rtrim(cmoState)) as State
 ,RIGHT( '00000' + LTRIM( RTRIM( [cmoPostCode] ) ), 5 ) as ZipCode

 from m1_kf.dbo.SalesOrders
left join m1_kf.dbo.Organizations on cmoOrganizationID=ompCustomerOrganizationID

 where ompRequestedShipDate >'11-01-17' and ompClosed !=-1

" ;
$result =odbc_exec($connect,$sql);
if(!$result){
exit("Error in SQL");
}
$json =array();
//****************************************************************
 while ($row = odbc_fetch_array($result))
{
$text = $row;
$address  = implode(", ", $text);
//echo $address ."<br>";

   $url = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&key=removed');
  echo $url ."<br>";


    $resp = file_get_contents($url);


        $lati = $resp['results'][0]['geometry']['location']['lat'];
        $longi = $resp['results'][0]['geometry']['location']['lng'];
        $formatted_address = $resp['results'][0]['formatted_address'];
        if($lati && $longi && $formatted_address){
            $data_arr = array();
            array_push(
                $data_arr,
                    $lati,
                    $longi,
                    $formatted_address
                );


            return $data_arr;
            echo $data_arr ."<br>";
        }else{
            return false;
        }
    }

odbc_close($connect);

?>
 

Need to try and simplify my code possibly into two functions and I want to be able to use substr and strpos and store them into an array?

$
0
0
Here's the code so far, essentially I want to. E able to take the text file that has numbers and commas and remove the commas, not happy with it would rather it be simpler in a away but with out the use of explode. Any help would be brilliant. Thank you




<?php
//linking table to form
$studentid=$_POST["id"];

//To print out student ID
echo "You have selected Student ID: $studentid <br />";


//define what the file equals to which is the students ID
$file = "$studentid.txt";

//Opening the selected files
$fileopen = fopen($file,'r') or die("Sorry, cannot open $file");
if($fileopen){

while (($buffer=fgets($fileopen,4096))!==false){
// echo $buffer."<br/>";
}
if(!feof($fileopen)){
echo "Error:unexpected fgets() fail\n";

}
fclose($fileopen);
}

//remove all commas from txt file
$filearray=file("$studentid.txt");
$count=count($filearray);

for($i=0; $i<$count; $i++){

$startnum=0;
$stringlength = strlen($filearray[$i]);
$comma = strpos($filearray[$i], ",", $startnum);
$array[$i][0] = substr($filearray[$i], $startnum, $comma);
$j=1;

while ($j<$count-1){
$comma = strpos($filearray[$i], ",", $startnum);
$comma2 = strpos($filearray[$i], ",", $comma+1);
$sub = $comma2-$comma;
$num = substr($filearray[$i], $comma+1, $sub -1);
$startnum = $comma2;
$array[$i][$j]= $num;

$j++;
}
$stop = $stringlength - $comma2;
$array[$i][$j] = substr ($filearray[$i], $comma2 + 1, $stop);
}

function array_transpose($filearray)
{
array_unshift($filearray, NULL);
return call_user_func_array('array_map', $filearray);
}

//table heading
echo"<h1>The Table</h1>";

//creating the rows and columns for the txt file
echo "<table border = 1 >";
for($row=0; $row<$count; $row++){
print "<tr>";

for($col=0; $col<$count; $col++){
print "<td>".$array[$row][$col]."</td>";
}
}
echo "</table>";



//table heading
echo"<h1>Transpose</h1>";

?>

server logs: PHP Warning: session_start(): Cannot find save handler 'mm'

$
0
0

good evening dear experts, hello dear PHP-Freaks,

 

 

i have got some issues with a server where a wordpress - installation runs.

 

 

if i have a closer look at the error-logs i see a lot of :

 server logs: PHP Warning:  session_start(): Cannot find save handler 'mm'

any idea what i can  do here  note : i am on PHP version 5xy

 

 

love to hear from you:

 

 

Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR

$
0
0

Hi

 

I encountered issue when running billing of of our sugar crm application. Pleae help me Thanks

 

Here is the error message.:

 

Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://portal.layer2.co.nz/voip/api/voipwebservice.php?WSDL' : Premature end of data in tag html line 2 in C:\xampp\htdocs\omnicrm\outbox\class.vibe.php:9 Stack trace: #0 C:\xampp\htdocs\omnicrm\outbox\class.vibe.php(9): SoapClient->SoapClient('http://portal.l...') #1 C:\xampp\htdocs\omnicrm\outbox\class.vibe.php(42): Vibe->vibe_api_voipwebservice() #2 C:\xampp\htdocs\omnicrm\outbox\callingdata.php(88): Vibe->getNumList('2017/11/01', '2017/11/30', 'nca', '', 'yes') #3 C:\xampp\htdocs\omnicrm\outbox\index.php(20): include('C:\xampp\htdocs...') #4 {main} thrown in  C:\xampp\htdocs\omnicrm\outbox\class.vibe.php on line 9

 

 

My Code

<?php
include("config.php");
class Vibe
{

	function vibe_api_voipwebservice()
	{
 		ini_set('soap.wsdl_cache_enabled',0);   // Disable caching in PHP
		$client = new SoapClient("http://portal.layer2.co.nz/voip/api/voipwebservice.php?WSDL");
		return $client;
	}
	function vibe_radius_api()
	{
		ini_set('soap.wsdl_cache_enabled',0);   // Disable caching in PHP
		$client = new SoapClient("http://portal.layer2.co.nz/api/radiuswebservice.php?WSDL");
		return $client;
	}
	function vibe_information()
	{
		ini_set('soap.wsdl_cache_enabled',0);   // Disable caching in PHP
		$client = new SoapClient("http://portal.layer2.co.nz/api/informationwebservice.php?WSDL");
		return $client;
	}
	function db_conn()
	{
		$db_conn=mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
		// Check connection
		if (mysqli_connect_errno())
		 {
		  echo "Failed to connect to MySQL: " . mysqli_connect_error();
		 }
		 return $db_conn;
	}
	function directURL($url)
	{
		echo '<script> window.location="'.$url.'"; </script> ';
	}

	function getNumList($start,$end,$numType,$savecsv,$savedb)
	{

		$conn=$this->vibe_api_voipwebservice();
    //echo "REQUEST:\n" . $conn ->__getLastRequest() . "\n" ;
		$search = array();
		$type='detail';
		if(isset($type))
		{
			if($numType=="nca")
			{
				$getNumList = $conn->GetNCANumbersList(USERNAME, PASSWORD, $type, $search);
			}
			if($numType=="voip")
			{
				$getNumList = $conn->GetNumbersList(USERNAME, PASSWORD, $type, $search);
			}
		}
		if($savecsv=="yes")
		{
			$fp = fopen('csv/'.date("Ymdhis").'_a.csv', 'w')or die("can't open file");
		}
Viewing all 13200 articles
Browse latest View live