Jump to content

maxudaskin

Members
  • Posts

    628
  • Joined

  • Last visited

Posts posted by maxudaskin

  1. Hello all and happy holidays!

    I am having a brain fart with my regex and cannot seem to wrap my head around what I am doing wrong.

    $regex = '/(?:<thead><tr>)(<th>(.*)<\/th>)+(?:<\/tr><\/thead>)/';
    
    $subject = '<thead><tr><th>Day</th><th>Date</th><th>Duty</th><th>From</th><th>Report</th><th>To</th><th>Release</th><th>Flight Time</th><th>Duty Time</th><th>TAFB Time</th><th>Rest Time</th><th>Sector(s)/Event(s)</th></tr></thead><tbody>...more string';

    What I am hoping to get out of this is

    ['Day', 'Duty', 'From', 'Report',] // ... and so on

    But I'm getting this instead

    Array(
      '<thead><tr><th>Day</th><th>Date</th><th>Duty</th><th>From</th><th>Report</th><th>To</th><th>Release</th><th>Flight Time</th><th>Duty Time</th><th>TAFB Time</th><th>Rest Time</th><th>Sector(s)/Event(s)</th></tr></thead>',
    
      '<th>Day</th><th>Date</th><th>Duty</th><th>From</th><th>Report</th><th>To</th><th>Release</th><th>Flight Time</th><th>Duty Time</th><th>TAFB Time</th><th>Rest Time</th><th>Sector(s)/Event(s)</th>',
    
      'Day</th><th>Date</th><th>Duty</th><th>From</th><th>Report</th><th>To</th><th>Release</th><th>Flight Time</th><th>Duty Time</th><th>TAFB Time</th><th>Rest Time</th><th>Sector(s)/Event(s)',
    )

     

  2. <?php
    // FlightEntryController.php
    
    ...
    
    class FlightEntryController extends Controller
    {
        public function __construct()
        {
            $this->authorizeResource(FlightEntry::class);
        }
    
        /**
         * Display the specified resource.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
        public function show(FlightEntry $flight)
        {
            dd($flight);
        }
    ...
    }
    
    // FlightEntryPolicy.php
    
    class FlightEntryPolicy
    {
        use HandlesAuthorization;
      
      	...
          
        
    
        /**
         * Determine whether the user can view the model.
         *
         * @param  \App\Models\User  $user
         * @param  \App\Models\FlightEntry  $flightEntry
         * @return \Illuminate\Auth\Access\Response|bool
         */
        public function view(User $user, FlightEntry $flightEntry)
        {
            dd($user);
            if($user->hasPermissionTo('view flights not owned')) { // Spatie
                return Response::allow();
            }
    
            if($user->id === $flightEntry->user_id) {
                return Response::allow();
            }
    
            return Response::deny(null, 404);
        }
      ...
    }
    
    // AuthServiceProvider.php
    
    class AuthServiceProvider extends ServiceProvider
    {
        /**
         * The policy mappings for the application.
         *
         * @var array
         */
        protected $policies = [
             App\Models\FlightEntry::class => App\Policies\FlightEntryPolicy::class,
        ];
    ...
    }
    
    // routes/web.php
    Route::resource('/flights', FlightEntryController::class)->middleware('auth');
        

    With the policy not attached, everything works fine.

    When I attach the policy, index (viewAny) works, but show (view) does not. It throws a 403 and does not run the dd inside.

     

    I'm going crazy. Any suggestions?

  3. Hi guys,

    I'm customizing an OpenCart template that is riddled with programming bugs. It is MVC and I am having a really odd issue with a controller file.

     

    The template that I want to use is not loading. I have edited the one in the selected template and also the default, but no avail. I was troubleshooting why it wasn't working and I came to the conclusion that either I am completely blind or stupid, or PHP is all of a sudden a troll.

     

    Please let me know if you need more context, but here is a snippet of the code and the result. I am really at a loss right now.

     

    Result:

    14
    

    Code:

    echo "1";
    
    if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/category.tpl')) {
    	echo "2";die();
    	$this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/product/category.tpl', $data));
    } else {
    	echo "3";die();
    	$this->response->setOutput($this->load->view('default/template/product/category.tpl', $data));
    }
    echo "4";die();
    
  4. My suggestion is to seperate the active users data from the users themselves.

     

    Have a second table that is queried to find the last page load activity. This way you can, if you want, log all of the user's actions, login's, or none of them at all.

  5. You have to link to the image relative to the file that the user first loaded.

     

    If they loaded http : //www . example . com/dir/abcd/efg/index.php, and the image was in /dir/upload, you would have to either call the image relatively, ../../upload/image.jpg or absolutely, http : //www . example . com/dir/upload/image.jpg.

  6. I would create a cron job running once a day, calling a php script.

     

    The php script would get the rows from the table from x days ago and would loop through and send a follow up email.

     

    Have each email template in it's own file.

     

    Let's say, initial_email.php and followup_email.php.

     

    <?php
    /**
    * initial_email.php
    */
    $message = <<<EOD
    Hi {$name},
    Thank you for submitting your information.
    You will receive an email in about seven days.
    ---
    This is an automated email. Replies will not be received.
    EOD;
    

    <?php
    /**
    * followup_email.php
    */
    $message = <<<EOD
    Hi {$name},
    About a week ago, you entered your information into our system.
    This is the follow up email.
    ---
    This is an automated email. Replies will not be received.
    EOD;
    

  7. Thankyou for the replies.

    By doing

    
    $send = mail($to, $subject, $body, $headers); 
      $send2 = mail($from, $subject2, $autoreply, $headers2); 
      if($send) {
        header( "Location: http://www.websites.cx/indextest.html" );
        exit();

     

    then surely im outputting html, before the header?  please excuse me if im being silly.

     

    The best way to prevent header errors is to, instead of putting php in the middle of html code, separate your code into three main catagories

    • Models
    • Views
    • Controllers

     

    Models are the liaisons between your code and databases, xml files, ect. Use functions such as get_posts, save_post, remove_post.

     

    Views are the files containing the HTML code. The only php on the page should be to output data.

    <h1>Posts</h1>
    <?php foreach($posts as $post): ?>
    <div>
    <?=$post?>
    </div>
    <?php endforeach; ?>

     

    Controllers control the data that is being sent to the views.


    Let's say that a user wants to view a post.

     

    Controller is activated.

    Controller gets the id of the post from the URI, $_GET['id']

    Controller asks the Model for the post from the database. $model->get_post($id);

    Model runs get_post. Queries the database for a post with a 'post_id' of $id

    Model either returns the post data, or false if it didn't find anything

    Controller gets the post data. Checks if false. If false, returns a 'Post Not Found' error.

    Controller sends the post data to the View file.

    View echoes the post data.

    User reads the article and goes about the rest of their day, none the wiser.

     

    mvc_diagram.png

     

    Here's some reading material. It is a bit lengthy.

  8. I already had this snippet code in adding users

     

    	if(isset($_POST['add_user'])){
    	$passw = trim(htmlentities($_POST['password']));
    
    	$encrypted = enc_salt($passw);
    
    	$con = "true";
    		$sql = "SELECT * FROM users WHERE username='".$_POST['user_name']."'";
    		$result = $database->query($sql);
    		$row = $database->fetch_array($result);
    
    		if($row!=""){
    			$con="false";
    		}
    
    	if($con!="false"){	
    	 $sql  = "INSERT INTO photo_gallery.users (username, password, first_name, last_name)";
    	$sql .= " VALUES ('".trim(htmlentities($_POST['user_name']))."','".$encrypted."', '".trim(htmlentities($_POST['first_name']))."', '".trim(htmlentities($_POST['last_name']))."')";
    
    	$result_set = $database->query($sql);
    
    	echo '<script type="text/javascript">alert("Account Created!");</script>';}
    	else{
    		echo '<script type="text/javascript">alert("This username already exist!");</script>';
    	}
    }

     

    where my function enc_salt is:

    function enc_salt($string){
    //encrypting
    $pass_word = sha1($string);
    $salt = md5("user");
    $pepper = "cxlkdawpoalsk";
    
    $pass_encrypted = $salt.$pass_word.$pepper;
    return $pass_encrypted;
    }

     

    my problem right now is when it's time the user login to the website.

     

    Very ineffective salting method.

     

    Try this:

    function enc_salt($password) {
        $salt = 'somerandomecharacters1646#s@0-2 da2e/5ad+';
        return md5($password . $salt);
    }

  9. The problem is I do not know how to do it.  I wish I did.  If you know, I will compensate you accordingly.

     

    Real quick, I'm going to show you something to save your butt, then I'll try to explain how to do this.

    Forum Rules

    ----

    12. All request for code to be written for you should be posted under the freelance section. No exceptions.

     

    What is it exactly is it that you need help with?

    If you're looking to get code written for you, then you'll have to go to the Freelance Section.

    If you're looking for assistance with code that you're writing, you'll have to let us know what you need help with.

  10. I would highly suggest checking out PHPMailer.

     

    $mail             = new PHPMailer(); // defaults to using php "mail()"
    
    $body             = file_get_contents('contents.html');
    $body             = preg_replace('/[\]/i','',$body);
    
    $mail->SetFrom('name@yourdomain.com', 'First Last');
    
    $mail->AddReplyTo("name@yourdomain.com","First Last");
    
    $address = "whoto@otherdomain.com";
    $mail->AddAddress($address, "John Doe");
    
    $mail->Subject    = "PHPMailer Test Subject via mail(), basic";
    
    $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
    
    $mail->MsgHTML($body);
    
    $mail->AddAttachment("images/phpmailer.gif");      // attachment
    $mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
    
    if(!$mail->Send()) {
      echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
      echo "Message sent!";
    }

  11. @Maxudaskin

     

    foreach ($myarray as $key=>$player) {
    
    
    
    echo 'Player ' . $key . ': ';
    echo 'color: ' . $player['color'] . ', ';
    echo 'animal: ' . $player['animal'] . ', ';
    echo 'state: ' . $player['state'] . ', ';
    echo 'food: ' . $player['food'];
    echo '<hr />';
    }

     

    Why are you echoing "state", "food" etc as literal strings when they are the key values?

     

    foreach ($myarray as $data) {
        foreach ($data as $k => $v) {       // apply foreach to inner array
            echo "$k : $v, ";
        }
        echo '<br />';
    }

     

    I used the literal string keys because it's doubtful that the keys will change.

    I think that he's trying to find a way to use the array, not just output everything in it.

  12. If you've read the PHP manual page on foreach () you'd notice that all it does is to take the elements of an array, and save them into a variable (as $variable). In the case of a multi-dimensional array, the new variable would become an array in itself.

    Printing out the contents of an array, a one-dimensional one in this case, is straight forward. And explained thoroughly in the manual as well.

     

    What he said.

     

    But just in case you want code to learn from, here you go :)

     

    The two output the exact same thing, but the method is different. First one answers your question directly.

     

    <?php
    $myarray = array(
    array(
    	'color'  => 'black',
    	'animal' => 'cat',
    	'state'  => 'Wyoming',
    	'food'   => 'Lasanga'),
    array(
    	'color'  => 'yellow',
    	'animal' => 'lion',
    	'state'  => 'Winnipeg', // I'm Canadian. Got a prooblem?
    	'food'   => 'Pizza'),
    array(
    	'color'  => 'green',
    	'animal' => 'Giraffe',
    	'state'  => 'New York',
    	'food'   => 'Potatoes'));
    
    // Let's output this data... simply.
    foreach ($myarray as $key=>$player) {
    echo 'Player ' . $key . ': ';
    echo 'color: ' . $player['color'] . ', ';
    echo 'animal: ' . $player['animal'] . ', ';
    echo 'state: ' . $player['state'] . ', ';
    echo 'food: ' . $player['food'];
    echo '<hr />';
    }
    
    ////////
    // The break between outputs... no significance in the code
    echo '<br /><br /><br /><br />';
    ////////
    
    // What if you wanted something a little more... in depth?
    class Player // Player class... indivdual player
    {
    private $number;
    private $color;
    private $animal;
    private $state;
    private $food;
    
    function __construct($arr, $num) // The constructor
    {
    	$this->number = $num;
    	$this->color  = $arr['color'];
    	$this->animal = $arr['animal'];
    	$this->state  = $arr['state'];
    	$this->food   = $arr['food'];
    }
    
    function getAll() // Return all of the variables, parsed, as a string
    {
    	$out = 'Player ' . $this->number . ': ';
    	$out .= 'color: ' . $this->color . ', ';
    	$out .= 'animal: ' . $this->animal . ', ';
    	$out .= 'state: ' . $this->state . ', ';
    	$out .= 'food: ' . $this->food;
    
    	return $out;
    }
    }
    
    class Player_Roster // Player_Roster class
    {
    private $players; // List of player objects
    
    function __construct($players) // Constructor
    {
    	foreach($players as $key=>$player) { // Create a list of Player objects
    		$this->players[] = new Player($player, $key);
    	}
    }
    
    function getAllToString() // Return all of the player objects, as a string
    {
    	$out = '';
    
    	foreach($this->players as $player) {
    		$out .= $player->getAll();
    		$out .= '<hr />';
    	}
    
    	return $out;
    }
    }
    
    $players = new Player_Roster($myarray); // Create the new roster
    
    echo $players->getAllToString(); // Echo the list of players

  13. speed wise:

     

    Using "===NULL" is 30x quicker than is_null

     

     

     

    however empty is a bit faster than than comparison operator or is_null

     

     

     

    You missed this part:

     

    Micro optimization isn't worth it.

     

    You had to do it ten million times to notice a difference, a little more than 2 seconds

     

    $a===NULL; Took: 1.2424390316s

    is_null($a); Took: 3.70693397522s

     

    difference = 2.46449494362

    difference/10,000,000 = 0.000000246449494362

     

    The execution time difference between ===NULL and is_null is less than 250 nanoseconds.

     

    You are correct. Most of us will likely never need to optimize such small numbers, but to teach good habit is crucial to, let's say, Facebook using 100,000,000 hours of processing time per year vs. 95,000,000 per year. Yes, those numbers are fictional, and yes, the statistics say that it's only 5%, but when you are talking about 5% over 100,000,000 hours, it's still 5,000,000 hours. 5,000,000 dollars. 5,000,000 starving children dead. 5,000,000 something.

  14. If you want one SQL, try this.

     

    <?php
    $beginning = true;
    $sql_where = '';
    foreach($results_done as $key => $val) {
    switch($key) {
        case 1:
            $q_cat = 4;
            break; // Without this statement, the page would continue checking the other cases, albeit, they would all get evaluated as false
        case 2:
            $q_cat = 1;
            break;
        case 3:
            $q_cat = 11;
            break;
        case 4:
            $q_cat = 2;
            break;
        case 5:
            $q_cat = 10;
            break;
        case 6:
            $q_cat = 9;
            break;
        default: // If the key is not 1-6, have a fallout. You can log the error, or do whatever you want.
            $q_cat = -1;
    }
    
    if(!$beginning) {
    	$sql_where .= ' OR';
    } else {
    	$beginning = false;
    }
    
    $sql_where .= ' WHERE tbl_components.ID = \'' . $val . '\'';
    }
    
    $sql = 'SELECT
    		`tbl_component_categories.ID`,
    		`tbl_component_categories.folder_path`,
    		`tbl_component_categories.comp_cat_name`,
    		`tbl_components.component_name`
    	FROM
    		`tbl_components`
    	JOIN `tbl_component_categories` on $q_cat = tbl_component_categories.ID';
    $sql .= $sql_where;
    
    $query_cats = mysql_query($sql);
    
    if (!$query_cats) {
      $message  = 'Invalid query: ' . mysql_error() . "\n";
      $message .= 'Whole query: ' . $query_cats;
      die($message);
    }
    
    
    while ($row = mysql_fetch_array($query_cats)) { 
    echo $row['comp_cat_name'].": ".$row['component_name']."<br />";
    }
    

     

    That will result in malformed SQL; WHERE tbl_components.ID = '1'  WHERE tbl_components.ID = '2'  WHERE tbl_components.ID = '3'

     

    selection, the page reloads and $results_done = Array ( [0] => [1] => 34 )

     

    Well, that's your problem. $val is going to be an Array.

     

    I can't really help because I still don't have any idea what you're trying to do. I don't know where $results_done is coming from, and I don't know what method you are using to get data to your script.

     

    if(!$beginning) {
    	$sql_where .= ' OR';
    } else {
    	$beginning = false;
    }

  15. If you want one SQL, try this.

     

    <?php
    $beginning = true;
    $sql_where = '';
    foreach($results_done as $key => $val) {
    switch($key) {
        case 1:
            $q_cat = 4;
            break; // Without this statement, the page would continue checking the other cases, albeit, they would all get evaluated as false
        case 2:
            $q_cat = 1;
            break;
        case 3:
            $q_cat = 11;
            break;
        case 4:
            $q_cat = 2;
            break;
        case 5:
            $q_cat = 10;
            break;
        case 6:
            $q_cat = 9;
            break;
        default: // If the key is not 1-6, have a fallout. You can log the error, or do whatever you want.
            $q_cat = -1;
    }
    
    if(!$beginning) {
    	$sql_where .= ' OR';
    } else {
    	$beginning = false;
    }
    
    $sql_where .= ' WHERE tbl_components.ID = \'' . $val . '\'';
    }
    
    $sql = 'SELECT
    		`tbl_component_categories.ID`,
    		`tbl_component_categories.folder_path`,
    		`tbl_component_categories.comp_cat_name`,
    		`tbl_components.component_name`
    	FROM
    		`tbl_components`
    	JOIN `tbl_component_categories` on $q_cat = tbl_component_categories.ID';
    $sql .= $sql_where;
    
    $query_cats = mysql_query($sql);
    
    if (!$query_cats) {
      $message  = 'Invalid query: ' . mysql_error() . "\n";
      $message .= 'Whole query: ' . $query_cats;
      die($message);
    }
    
    
    while ($row = mysql_fetch_array($query_cats)) { 
    echo $row['comp_cat_name'].": ".$row['component_name']."<br />";
    }
    

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.