Jump to content

Search the Community

Showing results for tags 'php'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. Hello I am receiving a huge amount of spam emails, now I am trying to implement Google Recaptcha V3 in my custom PHP From, I implemented all the steps for G-Recaptcha, but I receive error invalid-input-secret And I am sure that the secret code shout be copied right I added the below to the head tag <script src="https://www.google.com/recaptcha/api.js?render=6LfyPF0pAAAAAHLxp3315RTN7jrRvBe6kLdHGAiT"></script> <script> grecaptcha.ready(function() { grecaptcha.execute('6LfyPF0pAAAAAHLxp3315RTN7jrRvBe6kLdHGAiT', {action: 'submit'}).then(function(token) { let recaptchaResponse = document.getElementById("recaptchaResponse"); console.log(recaptchaResponse); recaptchaResponse.value = token; }); }); </script> Then added hidden input before the submit button in the Form <input type="hidden" name="recaptcha_response" id="recaptchaResponse"> <input class="contactInput no-border cursorPointer buttonStyle" name="submitContact" value="Submit" type="submit"> And finally, I implemented the PHP code if(isset($_POST['submitContact']) && $_SERVER['REQUEST_METHOD'] == 'POST'){ $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify'; $recaptcha_secret = '6LfyPF0pAAAAAEsS5lfN_WL3wKHh1XfGo0oE_PYU'; $recaptcha_response = $_POST['recaptcha_response']; $recaptcha = file_get_contents($recaptcha_url."?secret=".$recaptcha_secret."?response=".$recaptcha_response); $recaptcha = json_decode($recaptcha); if($recaptcha->success ==true){ if($recaptcha->score >= 0.5){ echo "Recaptcha Success"; }else{ echo"<pre>"; print_r("Recaptcha Not Verified"); echo"</pre>"; } }else{ echo"<pre>"; print_r($recaptcha); echo"</pre>"; } } But receiving the below error stdClass Object ( [success] => [error-codes] => Array ( [0] => invalid-input-secret ) )
  2. Hey (again :).. This is the code I'm working on but can't figure out to the heck of me how to remove these duplicate "words"/strings... A small sample of the output is added to the upload so you can see what I mean.. HELP! ps: a few comments have been left there for testing. $stmt = $pdo->prepare("select DISTINCT terms from links WHERE terms LIKE ? GROUP BY terms"); $stmt->execute(array("$alpha%")); // fetching rows into array $data = $stmt->fetchAll(); //echo gettype($data); foreach($data as $result_tag) { $one = implode(', ',$result_tag) . ""; $two = strtok($one, ',')."<br>"; //echo gettype($two); //echo strtolower($two); $three = strtolower($two); //print_r($three); $string = implode(" ", array_unique(explode(" ", $three))); //echo gettype($string); echo $string; } exit();
  3. I have a DataTables table and I have managed to get everything working fine. Within each row i have an action button with either accepts, approves or deletes the row. Like i say everything is working but after the respective button has been clicked I have to load the entire page again to get the table to refresh and it just doesnt look right. Anyway her is the code initial code to load the results into the table $(document).ready(function(){ $("#requests-container").html("<div class=\'col-sm-12 py-5\'><center><i class=\'fas fa-spinner fa-3x fa-spin mb-3 text-muted\'></i><br /></center></div>"); $("#requests-container").load("'.DIR.'admin/dashboard/requests", function(){ $("#project-requests").DataTable({ "order": [[0, "desc"]], "responsive": true, "lengthChange": true, "autoWidth": false, "pageLength": 25, "aLengthMenu": [ [10, 25, 50, -1], [10, 25, 50, "All"] ], "buttons": ["copy","pdf", "print", "colvis"] }).buttons().container().appendTo(\'#project-requests_wrapper .col-md-6:eq(0)\'); $("#project-requests_wrapper").children(":first").addClass("p-2"); $("#project-requests_wrapper").children(":first").next().next().addClass("p-2"); }); }); Then I have this once the link has been clicked $(document).on("click", ".action-requests", function(e){ e.preventDefault(); var Toast = Swal.mixin({ toast: true, position: \'top-end\', showConfirmButton: false, timer: 5000 }); var pageLink = $(this).attr("href"); var requestId = $(this).attr("data-id"); $.post("admin/dashboard/queries/" + pageLink, { id: requestId }, function(data, status){ if(status === "success") { if(pageLink == "approverequest") { Toast.fire({icon: "success",title: data}); $("#requests-container").html("<div class=\'col-sm-12 py-5\'><center><i class=\'fas fa-spinner fa-3x fa-spin mb-3 text-muted\'></i><br /></center></div>"); $("#requests-container").load("'.DIR.'admin/dashboard/requests", function(){ $("#project-requests").DataTable({ "order": [[0, "desc"]], "responsive": true, "lengthChange": true, "autoWidth": false, "pageLength": 25, "aLengthMenu": [ [10, 25, 50, -1], [10, 25, 50, "All"] ], "buttons": ["copy","pdf", "print", "colvis"] }).buttons().container().appendTo(\'#project-requests_wrapper .col-md-6:eq(0)\'); $("#project-requests_wrapper").children(":first").addClass("p-2"); $("#project-requests_wrapper").children(":first").next().next().addClass("p-2"); }); } else { Toast.fire({icon: "success",title: data}); $("#requests-container").html("<div class=\'col-sm-12 py-5\'><center><i class=\'fas fa-spinner fa-3x fa-spin mb-3 text-muted\'></i><br /></center></div>"); $("#requests-container").load("'.DIR.'admin/dashboard/requests", function(){ $("#project-requests").DataTable({ "order": [[0, "desc"]], "responsive": true, "lengthChange": true, "autoWidth": false, "pageLength": 25, "aLengthMenu": [ [10, 25, 50, -1], [10, 25, 50, "All"] ], "buttons": ["copy","pdf", "print", "colvis"] }).buttons().container().appendTo(\'#project-requests_wrapper .col-md-6:eq(0)\'); $("#project-requests_wrapper").children(":first").addClass("p-2"); $("#project-requests_wrapper").children(":first").next().next().addClass("p-2"); }); } } }); }); Like i said its a bit long winded for such a simple action but if its not like this DataTables wont load after the submission I was just wondering if anyone has a simpler idea to shorten the coding Thanks
  4. Hello, I am trying to unset from array using array_search, it's working, except the first array value "a+" is not working $bloodType_list = ['a+','a-','b+','b-','o+','o-','ab+','ab-']; if($key = array_search('a+',$bloodType_list)){ unset($bloodType_list[$key]); } foreach($bloodType_list as $bloodType_lists){ echo $bloodType_lists."<br>"; }
  5. Hello all. please what could be the reason i am not getting the desired result when i do a JOIN. This query gives the desired result //calculate profit $stmt = $pdo->query(" SELECT SUM(total_cost) AS total_cost, SUM(total_sales) AS total_sales FROM tbl_sales WHERE customer_id = 489639 AND status = 0 "); $row = $stmt->fetch(PDO::FETCH_ASSOC); $total_sales = $row['total_sales']; $total_cost = $row['total_cost']; $profit = $total_sales - $total_cost; //calculate balance $stmt = $pdo->query(" SELECT SUM(amt_paid) AS amt_paid FROM tbl_sales_total WHERE customer_id = 489639 AND status = 0 "); $row = $stmt->fetch(PDO::FETCH_ASSOC); $amt_paid = $row['amt_paid']; $balance = $total_sales - $amt_paid; echo "<strong>Total Profit Realised From Customer: ₦".$profit."</strong>"; echo "<br><strong>Total Unpaid Balance: ₦".$unpaid_bal."</strong>"; But when i do a join it gives a wrong result. $stmt = $pdo->query(" SELECT *, SUM(t2.total_price) AS total_sales, SUM(t3.amt_paid) AS amt_paid FROM customers t1 LEFT JOIN tbl_sales t2 ON t1.customer_id = t2.customer_id LEFT JOIN tbl_sales_total t3 ON t1.customer_id = t3.customer_id WHERE t1.customer_id = 489639 AND t3.status = 0 "); WHILE($row = $stmt->fetch(PDO::FETCH_ASSOC)){ echo '<tr> <td>'.$row["customer_name"].'</td> <td>'.$row["total_sales"].'</td> <td>'.$row["amt_paid"].'</td> </td> </tr>'; } Please what did i do wrong and how do i get the desired result. Thanks
  6. Hello, photos do not appear in the following cases 1- inserting photo inside <picture> tag (In Server Side Only), Working normally in local 2- Not Working when site domain only www.mysite.com ,, Working when site domain = www.mysite.com/index.php <picture class="hover1 runHover2"> <img src="assets/img/central-business-district-singapore.jpg"> </picture> Note: -The path is right, and when opening inspect to check the photo, I find it - Tried to change the path to /assets/img/central-business-district-singapore.jpg or www.mysite.com/assets/img/central-business-district-singapore.jpg , but not solved
  7. I am trying to identify the style.css through the config file then bring into the project using the include command. I can get the project to tell me which css style is listed but it is not actually linking the css. Is this possible or am i wasting my time. I want to do it this way so that I can change the style.css if required and it pick up the new details without the need to clear cache to implement changes. ####### CONFIG.PHP <?php //EXTRA PARAMETERS $sitename = "DEMO SITE"; $timezone = "Australia/Brisbane"; //Set for head office location $stylecss = "../include/style.css"; $loginurl = ""; // default landing page for login $logoimg = ""; $logoimg_params = "height='50px', width='100px'"; ?> ####### INDEX.PHP <?php session_start(); include('include/config.php'); include('include/edb.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?php echo $sitename?></title> <link href="<?php echo $stylecss?>" rel="stylesheet" type="text/css" /> </head>
  8. Hello guys. I really don't know what to use as a topic and my question might no be clear enough cos I might lack adequate words to put it together but I will try by using examples anyhow. My question is Like during joomla or WordPress installation, the processes one has to undergo e.g filling the company/application name, database name, admin username and password, color scheme etc. In like manner, one has a web app hosted. How to enable different user create their own account and setup their database etc For example I have a web app hosted at https://myapp.com A user can setup their shop on my app https://myapp.com/shop1 or shop1.myapp.com Hope I tried to make it clear enough Thanks
  9. hello all. i dont know if to post this here or javascript/ajax section. if its not the right place, please let me know so i can ask in the right place. i am trying out saving to db via modal form. i learned the basics of using ajax to save data with the modal. so far, i can perform a CRUD via modal but the problem i am having is displaying duplicate entry error inside the modal. I have tried so many ways and the closest i come is displaying error only if a field is duplicate cos i use same trigger as my validation error notice. I'd be glad if i am shown the way to get it to display the error or a better way of getting it done. PS: I want the errors displayed inside the modal. I want the database query error to display where the success message is displayed (i.e on the modalMessage div) Thanks My Modal <div class="modal fade" id="armsModal" data-bs-backdrop="static" tabindex="-1" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header modal-bg"> <h5 class="modal-title w-100 text-center mb-3" id="exampleModalLabel4">Add School Arms</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <form id="submitForm" class="myForm"> <div class="modal-body"> <div id="modalMessage"></div> <div class="mb-3"> <label for="armsname" class="form-label">Arms FullName:</label> <input type="text" class="form-control" id="arms_long_name" name="arms_long_name" autocomplete="off" value="<?php if(isset($_POST['arms_long_name'])){ echo $_POST['arms_long_name']; } ?>"> <span id="longNameError" class="text-danger"></span> </div> <div class="mb-3"> <label for="armsshort" class="form-label">Arms ShortName:</label> <input type="text" class="form-control" id="arms_short_name" name="arms_short_name" autocomplete="off" value="<?php if(isset($_POST['arms_short_name'])){ echo $_POST['arms_short_name']; } ?>"> <span id="shortNameError" class="text-danger"></span> </div> </div> <div class="modal-footer modal-bg"> <button type="button" class="btn btn-outline-light btn-sm" data-bs-dismiss="modal"> Close </button> <button type="submit" class="btn btn-dark btn-sm">Submit</button> </div> </form> </div> </div> </div> My script <script> //Modal $('#submitForm').submit(function(event) { event.preventDefault(); $("#armsModal").on("hidden.bs.modal", function() { $('#longNameError').text(''); $('#shortNameError').text(''); $("#submitForm")[0].reset(); }); $('#armsModal').on('hidden.bs.modal', function () { // Clear form fields $('#submitForm')[0].reset(); // Clear error messages $('.invalid-feedback').text(''); }); // Get form data var formData = { 'arms_long_name': $('#arms_long_name').val(), 'arms_short_name': $('#arms_short_name').val() }; // AJAX request $.ajax({ type: 'POST', url: 'school-arms-action.php', data: formData, dataType: 'json', encode: true }) .done(function(data) { if (!data.success) { if (data.errors.arms_long_name) { $('#longNameError').text(data.errors.arms_long_name); } if (data.errors.arms_short_name) { $('#shortNameError').text(data.errors.arms_short_name); } }else{ modalMessage.innerHTML = '<div class="alert alert-success text-center text-black">ARMS SAVE SUCCESSFUL!</div>'; setTimeout(function() { window.location.href = 'school-arms'; }, 2000); // 2 seconds delay } }); }); </script> My school-arms-action.php $response = array('success' => false, 'errors' => array()); if ($_SERVER['REQUEST_METHOD'] === 'POST') { $arms_long_name = ucwords($_POST['arms_long_name']); $arms_short_name = strtoupper($_POST['arms_short_name']); $arms_id = mt_rand(100, 999); // Validation if (empty($arms_long_name)) { $response['errors']['arms_long_name'] = 'Arms LongName is Required.'; } if (empty($arms_short_name)) { $response['errors']['arms_short_name'] = 'Arms ShortName is Required.'; } // If no errors, proceed to submission if (empty($response['errors'])) { try { $pdo = new PDO("mysql:host=localhost;dbname=db_name", "username", "password"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $table=$pdo->query("ALTER TABLE tbl_school_arms AUTO_INCREMENT = 1"); $table->execute(); $stmt = $pdo->prepare(" SELECT * FROM tbl_school_arms WHERE arms_name_long = :arms_name_long OR arms_name_short = :arms_name_short "); $stmt->bindParam(':arms_name_long', $arms_long_name, PDO::PARAM_STR); $stmt->bindParam(':arms_name_short', $arms_short_name, PDO::PARAM_STR); $stmt->execute(); $existingEntry = $stmt->fetch(PDO::FETCH_ASSOC); if ($existingEntry) { //This is what i used but not the right thing i want $response['errors']['arms_long_name'] = 'Duplicate Entry'; } else { // Perform database operations using PDO $stmt = $pdo->prepare(" INSERT INTO tbl_school_arms (arms_id, arms_name_long, arms_name_short) VALUES (:arms_id, :arms_name_long, :arms_name_short)"); $stmt->bindParam(":arms_id", $arms_id); $stmt->bindParam(":arms_name_long", $arms_long_name); $stmt->bindParam(":arms_name_short", $arms_short_name); $stmt->execute(); if($stmt->rowCount()){ $response['success'] = true; } } } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } } } echo json_encode($response);
  10. I know it's a piece of cake to use an anchor tag with the target attribute to open a new window for the href referenced. I want to do that using an input/submit tag instead of the anchor but can't remember/figure it out. Am I forgetting something or can it not be done. And if not, how would you accomplish this task?
  11. Hello all, In a column in my table is store an array 58100, 47270, 95437, 52652 which represents in table1 class_id, class_name 58100 JSS 47270 PRY 95437 SSS in table2 subjects, subj_levels English 58100, 47270, 95437 Maths 58100, 47270 Physics 47270, 95437 I have two problems Problem One when i do a select with join, instead of getting JSS, PRY, SSS as result, i am getting only JSS and the other values not showing up. $stmt=$pdo->query(" SELECT t1.subj_name, t1.subj_levels, t2.class_id FROM tbl_school_subjects t1 LEFT JOIN tbl_classes t2 ON t1.subj_levels = t2.class_id "); WHILE($row=$stmt->fetch(PDO::FETCH_ASSOC)){ echo '<tr> <td>'.$row['subj_name'].'</td> <td>'.$row['class_name_small'].'</td> <td>'; } Problem Two when i do a select find_in_set, i get no result. $ids = $_GET['id']; $stmt = $pdo->query(" SELECT * FROM tbl_school_subjects WHERE FIND_IN_SET($ids, subj_levels) > 0 "); what could be the problem? Thanks
  12. I am using osclass Osclass v8.0.2 free classified. I am trying to implement load more i.e infinite scroll facility on homepage page. When user scrolls, listings should be loaded automatically to give users pleasant and engaging experiences. Below is my code: Got from plugin. That I want to directly insert in osclass script. For the learning purpose. I am trying it on my localhost. Please help to achieve this, any help is highly appreciated. Thanks. <?php $content_block = htmlspecialchars_decode(inf_param('#main')); $listings_parent_block = htmlspecialchars_decode(inf_param('#listing-card-list')); $pagination_block = htmlspecialchars_decode(inf_param('.paginate')); $pagination_next = htmlspecialchars_decode(inf_param('a.searchPaginationNext')); $loaded_listings_count = htmlspecialchars_decode(inf_param('loaded_listings_count')); $report_errors = htmlspecialchars_decode(inf_param('report_errors')); ?> <style> <?php echo $pagination_block; ?> {display:none!important;} .inf-loader {display:none;width:100%;padding:25px 5px;margin:20px 0;background:#eee;border-radius:6px;color:#777;font-size:16px;text-align:center;line-height:20px;} .inf-loader > div {display:inline-block;width:auto;position:relative;padding-left:44px;} .inf-loader img {position:absolute;display:inline-block;top:-6px;left:0;width:32px;height:32px;max-height:32px;max-width:32px;} .inf-loader span {display:inline-block;font-weight:bold;line-height:20px;font-size:14px;} <?php echo $content_block; ?>.loading .inf-loader {display:inline-block;} </style> <script async type="text/javascript"> $(document).ready(function() { var currentPag = 1; var isLoading = false; var pagUrl = ''; var newUrl = ''; var oldUrl = ''; // ADD LOADING BLOCK ABOVE PAGINATION var loadingBlock = '<div class="inf-loader"><div><img src="<?php echo osc_base_url(); ?>oc-content/plugins/infinite/img/loader.gif"/><span><?php echo osc_esc_js(__('Loading items...', 'infinite')); ?></span></div></div>'; $(window).scroll(function(e) { var scroll = $(window).scrollTop(); var threshold = $('<?php echo $content_block; ?>').position().top + $('<?php echo $content_block; ?>').innerHeight() - 100; var position = $(window).scrollTop() + $(window).innerHeight(); if($('<?php echo $pagination_next; ?>').length) { pagUrl = $('<?php echo $pagination_next; ?>').attr('href'); } else { pagUrl = ''; } //console.log(oldUrl + '--->' + pagUrl ); // loading block add above pagination now if(!$('<?php echo $content_block; ?>').find('.inf-loader').length) { $(loadingBlock).insertBefore($('<?php echo $pagination_block; ?>')); } if(!$('<?php echo $content_block; ?>').length || !$('<?php echo $listings_parent_block; ?>').length || !$('<?php echo $pagination_block; ?>').length || !$('<?php echo $pagination_next; ?>').length) { infCheckBlocks(); } else if(position > threshold && isLoading == false && pagUrl != oldUrl && pagUrl != '' && pagUrl != '#') { isLoading = true; $('<?php echo $content_block; ?>').addClass('loading'); $.ajax({ url: pagUrl, type: "GET", success: function(response){ var length = response.length; var data = $(response).contents().find('<?php echo $listings_parent_block ; ?>').html(); var pagBlock = $(response).contents().find('<?php echo $pagination_block; ?>'); var currItemCount = $(response).contents().find('<?php echo $loaded_listings_count; ?>').text(); oldUrl = pagUrl; $('<?php echo $pagination_block; ?>').html(pagBlock); $('<?php echo $listings_parent_block; ?>').append(data); if($('<?php echo $loaded_listings_count; ?>').length) { $('<?php echo $loaded_listings_count; ?>').text(currItemCount); } // lazy load if exists if(typeof $.fn.Lazy !== 'undefined') { $('<?php echo $listings_parent_block; ?>').find('img.lazy').Lazy({ appendScroll: window, scrollDirection: 'both', effect: 'fadeIn', effectTime: 300, afterLoad: function(element) { setTimeout(function() { element.css('transition', '0.2s'); }, 300); } }); } isLoading = false; currentPag = currentPag + 1; $('<?php echo $content_block; ?>').removeClass('loading'); }, error: function(response){ hasPag = false; $('<?php echo $content_block; ?>').removeClass('loading'); response = response.responseText; console.log(response); console.log(data); } }); } }); }); function infCheckBlocks() { <?php if($report_errors == 1) { ?> console.log('<?php echo osc_esc_js(__('Infinite scroll failed to load next items, check message bellow!', 'infinite')); ?>'); if(!$('<?php echo $content_block; ?>').length) { console.log('<?php echo osc_esc_js(sprintf(__('Content block does not exists, make sure selector is correct. Current selector: %s', 'infinite'), $content_block)); ?>'); } if(!$('<?php echo $listings_parent_block; ?>').length) { console.log('<?php echo osc_esc_js(sprintf(__('Listing parent block does not exists, make sure selector is correct. Current selector: %s', 'infinite'), $content_block)); ?>'); } if(!$('<?php echo $pagination_block; ?>').length) { console.log('<?php echo osc_esc_js(sprintf(__('Pagination block does not exists, maybe there are no other pages. Make sure selector is correct. Current selector: %s', 'infinite'), $pagination_block)); ?>'); } if(!$('<?php echo $pagination_next; ?>').length) { console.log('<?php echo osc_esc_js(sprintf(__('Pagination next button does not exists, maybe there are no other pages. Make sure selector is correct. Current selector: %s', 'infinite'), $pagination_next)); ?>'); } <?php } ?> } </script>
  13. I did get help from Barand (moderator) It is working, bur what happened if I have two different or more info after my html link In echo I can have last part as /Token or /address How can I get it to see anyone that must be used <?php $domains = [ "BSCSCAN" => "bscscan.com", "TRONSCAN" => "tronscan.org/#", "DGB" => "dgb.com", "HECOINFO" => "heco.com", "POLYGONSCAN" => "polyn.com", "RVN" => "rvn.com", "ETHERSCAN" => "etherscan.io/address", "THUNDERCORE" => "tttn.com", "SOLSCAN" => "solscan.com" ]; $address = strtolower($checkSqlRow["ADDRESS"]); echo "<td><a href='https://{$domains[$checkSqlRow["BLOCKCHAIN"]]}/token/$address 'style='color:lime' target='_blank' >$address</a></td>"; ?>
  14. I'm really sorry for the poor explanation, I am absolutely not familiar with PHP. I would like to get data from my phpmyadmins 2 table, so I can display how many posts have been submitted with the same category type. One is called "posts" and the other one is called "categories". I have attached a picture to see the how it looks like. What I want is to make the category tables "id" equal to the posts tables "catagory_id", and then display how many posts have bben uploaded of each category. Here is how far I went with the coding, which is nowhere close to my expectations: <div class="stats__div"> <p class="stats__text">Categories</p> <p> <?php $all_categories_query = "SELECT * FROM categories ORDER BY title ASC"; $all_categories = mysqli_query($connection, $all_categories_query); while ($category = mysqli_fetch_assoc($all_categories)) : ?> <p><?= $category['title'] ?> <?= $category['id'] ?></p> <?php endwhile ?> <?php $all_posts_query = "SELECT * FROM posts GROUP BY category_id"; $all_posts = mysqli_query($connection, $all_posts_query); while ($posts = mysqli_fetch_assoc($all_posts)) : ?> <p><?= $posts['category_id'] ?></p> <?php endwhile ?> </p> </p> </div> I know, the coding is at the edge of being horrible, I am really sorry for that. I have tried my best. Does anyone know how to do that? I have seen that the right solution is using "array_count_values", but all the examples I have seen were lists. Any kind of help is highly appreciated!
  15. Hello all, I have a video converting script fetch / remote download and then convert using FFMPEG. Recently i had issue with one of the extractor "plugin" when i try to convert i get error in the browser in Virtualmin error log i get [Wed Jul 06 20:30:12.758777 2022] [proxy_fcgi:error] [pid 842:tid 139961936357120] [client 2.xx.xxx.9:56176] AH01071: Got error 'PHP message: PHP Notice: Undefined offset: 2 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 2 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 2 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 2 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 2 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 2 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 2 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 2 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 2 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 2 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 2 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 2 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Warning: A non-numeric value encountered in /home/testdomain/public_html/lib/extractors/yt.php on line 202PHP message: PHP Fatal error: Uncaught Error: Unsupported operand types in /home/testdomain/public_html/lib/extractors/yt.php:202\nStack trace:\n#0 /home/testdomain/public_html/lib/VideoConverter.php(258): YouTubeMp3Converter\\lib\\extractors\\yt->RetrieveVidInfo()\n#1 /home/testdomain/public_html/inc/index_header.php(175): YouTubeMp3Converter\\lib\\VideoConverter->ValidateConversionForm()\n#2 /home/testdomain/public_html/index.php(4): include('/home/testdomai...')\n#3 {main}\n thrown in /home/testdomain/public_html/lib/extractors/yt.php on line 202', referer: http://91.xxx.xxx.xxx/?config=complete [Wed Jul 06 20:36:49.899796 2022] [proxy_fcgi:error] [pid 842:tid 139961886000896] [client 2.xx.xxx.9:56487] AH01071: Got error 'PHP message: PHP Notice: Undefined offset: 1 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 1 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 1 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 1 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 1 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 1 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 1 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 1 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 1 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 1 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 1 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Notice: Undefined offset: 1 in /home/testdomain/public_html/lib/extractors/Extractor.php on line 205PHP message: PHP Warning: A non-numeric value encountered in /home/testdomain/public_html/lib/extractors/yt.php on line 202PHP message: PHP Fatal error: Uncaught Error: Unsupported operand types in /home/testdomain/public_html/lib/extractors/yt.php:202\nStack trace:\n#0 /home/testdomain/public_html/lib/VideoConverter.php(258): YouTubeMp3Converter\\lib\\extractors\\yt->RetrieveVidInfo()\n#1 /home/testdomain/public_html/inc/index_header.php(175): YouTubeMp3Converter\\lib\\VideoConverter->ValidateConversionForm()\n#2 /home/testdomain/public_html/index.php(4): include('/home/testdomai...')\n#3 {main}\n thrown in /home/testdomain/public_html/lib/extractors/yt.php on line 202', referer: http://91.xxx.xxx.xxx/index.php Previously i got it fixed with a help of a developer and everything worked perfectly without any issue on aaPanel but when i test this in Virtualmin i get this error. I will post 4 codes and related to the extractor which is having issue below is the (01) yt.php <?php namespace YouTubeMp3Converter\lib\extractors; use \YouTubeMp3Converter\lib\Config; // hub Extractor Class class yt extends Extractor { // Fields public $_reqHeaders = array( //'Accept-Encoding: gzip, deflate', 'Accept-Language: en-us,en;q=0.5', 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Cookie: age_verified=1; platform=pc' ); protected $_mainUserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.131 Safari/537.36'; private $_platforms = array('pc'/*, 'tv'*/); #region Public Methods function RetrieveVidInfo($vidUrl) { $converter = $this->GetConverter(); $videoInfo = array(); $vidPage = ''; $srcUrl = ''; $vidTitle = 'Unknown'; $vidImage = 'https://img.youtube.com/vi/oops/1.jpg'; $vidDuration = array(); foreach ($this->_platforms as $platform) { $vidPage = $this->FileGetContents($vidUrl, "", $this->_reqHeaders); if (!empty($vidPage)) { $reqCookies = $this->ExtractCookies(); if (empty($srcUrl) && preg_match('/<video[^>]+src="(.+?)"[^>]*><\/video>/is', $vidPage, $matches) == 1) { $srcUrl = preg_replace('/^(\/{2})/', "http://", trim($matches[1])); } if (empty($srcUrl)) { $srcUrls = array(); if (preg_match('/var player_mp4_seek = "[^"]*";\s*(\/\/[^\/]+?\n)*(.+?)\n/is', $vidPage, $matches) == 1) { //die(trim($matches[2])); if (preg_match('/var qualityItems_[a-zA-Z0-9]+\s*=\s*(\[\{.+?\}\]);/is', $matches[2], $qitems) == 1) { $items = json_decode($qitems[1], true); if (json_last_error() == JSON_ERROR_NONE) { //die(print_r($items)); $itemUrls = array(); foreach ($items as $item) { if (isset($item['url']) && !empty($item['url'])) { $srcUrls[] = $item['url']; } } arsort($srcUrls); } } if (empty($srcUrls)) { if (preg_match('/(var\s+(?:(media|quality))_.+)/', $vidPage, $assignments) == 1) { //die(print_r($assignments)); $assignmentsArr = explode(";", $assignments[0]); //die(print_r($assignmentsArr)); $media = array(); array_walk($assignmentsArr, function($val) use(&$media) { if (preg_match('/^(var\s+(media|quality(?!Items))_\d=)/', $val) == 1) $media[] = preg_replace('/\/\*[^\*]*\*\//', "", preg_replace('/^(var\s+(media|quality(?!Items))_\d=)/', "", $val)); }); //die(print_r($media)); $surl = ""; foreach ($media as $medium) { $jsKeys = preg_split('/\s*\+\s*/', $medium, -1, PREG_SPLIT_NO_EMPTY); //die(print_r($jsKeys)); foreach ($jsKeys as $jsKey) { if (preg_match('/var\s+' . preg_quote($jsKey, "/") . '=([^;]+)/', $vidPage, $jsKeyMatch) == 1) { $surl .= preg_replace('/("|\+|\s)/', "", $jsKeyMatch[1]); } } if (!empty($surl)) { //echo $surl . "<br>"; if (preg_match('/get_media/', $surl) == 1) { $this->_reqHeaders[count($this->_reqHeaders) - 1] .= ';' . $reqCookies; //die(print_r($this->_reqHeaders)); $reqTries = 0; do { $mp4Json = $this->FileGetContents($surl, "", $this->_reqHeaders); $mp4Data = json_decode($mp4Json, true); $reqTries++; } while ($reqTries < Config::_MAX_CURL_TRIES && (json_last_error() != JSON_ERROR_NONE || empty($mp4Data))); $mp4Data_pre = array() ; foreach($mp4Data as $k => $v){ if($v['quality'] > 1080) unset($mp4Data[$k]); else if($v['format'] == 'hls') { $mp4Data_pre['ff_pre'] = ' -protocol_whitelist file,tls,tcp,https,crypto -allowed_extensions ALL '; $mp4Data_pre['ff_for'] = true ; } } //die(print_r($mp4Data)); if (isset($mp4Data[count($mp4Data) - 1]['videoUrl'])) { $srcUrls[0] = $mp4Data[count($mp4Data) - 1]['videoUrl']; } } if (empty($srcUrls) && preg_match('/1080P.*?720P.*?480P.*?\.m3u8\?/', $surl) == 1) { $m3u8 = $this->FileGetContents($surl, "", $this->_reqHeaders); if (!empty($m3u8)) { $m3u8Lines = preg_split('/\n|\r/', $m3u8, -1, PREG_SPLIT_NO_EMPTY); $m3u8Lines = preg_grep('/^(#)/', $m3u8Lines, PREG_GREP_INVERT); //die(print_r($m3u8Lines)); if (!empty($m3u8Lines)) { $surl = preg_replace('/(' . preg_quote(strrchr($surl, "/"), "/") . ')$/', "", $surl); $surl = $surl . "/" . current($m3u8Lines); $srcUrls[] = $surl; } } } //if (preg_match('/\.m3u8\?/', $surl) != 1) $srcUrls[] = $surl; } $surl = ""; } //die(print_r($srcUrls)); } } if (empty($srcUrls)) { preg_match_all('/var ([^=]+)="([^"]*)"(\s*\+\s*"([^"]*)")?;/is', trim($matches[2]), $matches2); if (!empty($matches2)) { //die(print_r($matches2)); $urlParts = array(); foreach ($matches2[0] as $k => $m) { $urlParts[$matches2[1][$k]] = $matches2[2][$k] . $matches2[4][$k]; } //die(print_r($urlParts)); if (!empty($urlParts)) { preg_match_all('/var quality_(\d+)p=(.+?);/is', trim($matches[2]), $matches3); if (!empty($matches3)) { //die(print_r($matches3)); foreach ($matches3[0] as $k => $m) { $urlVars = preg_replace('/\/\*[^\*]*\*\//', "", $matches3[2][$k]); $urlVars = preg_split('/\+/', $urlVars, -1, PREG_SPLIT_NO_EMPTY); foreach ($urlVars as $uvar) { $uvar = trim($uvar); $srcUrls[$matches3[1][$k]] .= (isset($urlParts[$uvar])) ? $urlParts[$uvar] : ''; } } arsort($srcUrls); } } } } } //die(print_r($srcUrls)); $srcUrl = (!empty($srcUrls)) ? current($srcUrls) : $srcUrl; } if ($vidTitle == 'Unknown' && preg_match("/('flashvars'\s*:\s*\{(.+?)\},)|(var flashvars\w* = \{(.+?)\};)/is", $vidPage, $matched) == 1) { //die(print_r($matched)); $rawJson = (!empty($matched[2])) ? $matched[2] : $matched[4]; $json = json_decode('{' . $rawJson . '}', true); if (json_last_error() == JSON_ERROR_NONE) { //die(print_r($json)); if (!isset($json['video_title'])) { $json = json_decode('{' . $matched[4] . '}', true); } $vidTitle = (isset($json['video_title'])) ? urldecode($json['video_title']) : $vidTitle; $vidImage = (isset($json['image_url'])) ? urldecode($json['image_url']) : $vidImage; $vidDuration = (isset($json['video_duration'])) ? array('duration' => (int)$json['video_duration']) : $vidDuration; } } } } parse_str(parse_url($vidUrl, PHP_URL_QUERY), $urlVars); if (isset($urlVars['viewkey'])) { $videoInfo = array('id' => $urlVars['viewkey'], 'title' => $vidTitle, 'thumb_preview' => $vidImage, 'src_sd' => $srcUrl, 'src_hd' => $srcUrl, 'cookies' => preg_replace('/^(Cookie: )/', "", $this->_reqHeaders[count($this->_reqHeaders) - 1])) + $vidDuration + $mp4Data_pre; } //die(print_r($videoInfo)); //print_r($videoInfo); return $videoInfo; } function ExtractVidSourceUrls() { // Populate vars required for extraction $converter = $this->GetConverter(); $vidUrls = array(); $ftype = $converter->GetConvertedFileType(); $fcategory = $converter->GetConvertedFileCategory(); $vidHost = $converter->GetCurrentVidHost(); $vidInfo = $converter->GetVidInfo(); $vidHosts = $converter->GetVideoHosts(); $vidQualities = array(); array_walk($vidHosts, function($vh, $key) use(&$vidQualities, $vidHost) {if ($vh['name'] == $vidHost) $vidQualities = $vh['video_qualities'];}); // Start extraction $playUrls = array(); foreach ($vidQualities as $key => $fq) { if (!empty($vidInfo[$fq]) && !in_array($vidInfo[$fq], $playUrls)) { $vidUrls[] = array('mp4', $key, $vidInfo[$fq]); $playUrls[] = $vidInfo[$fq]; } } //die(print_r($vidUrls)); return ($fcategory == 'audio' || $ftype == '3gp') ? array_reverse($vidUrls) : $vidUrls; } #endregion } ?> (02) remote.php <?php namespace YouTubeMp3Converter\lib; use YouTubeMp3Converter\lib\extractors\Extractor; // Remote Download Class class Remote { // Private Fields private static $_converter; private static $_curlResource; private static $_percentVidDownloaded = 0; private static $_fsize; private static $_downloaded; private static $_chunkCount = 0; private static $_prevChunkCount = 0; private static $_isChunkedDload; #region Public Methods public static function Init(VideoConverter $converter) { self::$_converter = $converter; } public static function ChunkedDownload(array $vars) { extract($vars); self::$_isChunkedDload = true; $converter = self::$_converter; $vHost = $converter->GetCurrentVidHost(); $dloadUrls = end($urls[$vidCount]); $dloadUrls = (!is_array($dloadUrls)) ? array($dloadUrls) : $dloadUrls; foreach ($dloadUrls as $urlKey => $dloadUrl) { self::$_downloaded = self::$_percentVidDownloaded = 0; $dloadUrlInfo = self::CheckDownloadUrl($dloadUrl, $extractor, $vidInfo, $vHost); $dloadUrl = (!empty($dloadUrlInfo['redirectUrl'])) ? $dloadUrlInfo['redirectUrl'] : $dloadUrl; if ($dloadUrlInfo['isValid']) { self::$_fsize = $dloadUrlInfo['filesize']; $chunkEnd = $chunkSize = 1000000; // 1 MB in bytes $numTries = $count = $chunkStart = 0; if (is_file($filename[$urlKey])) unlink($filename[$urlKey]); $file = fopen($filename[$urlKey], 'a'); self::$_curlResource = $ch = curl_init(); while (self::$_fsize >= $chunkStart) { //curl_setopt($ch, CURLOPT_FILE, $file); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_URL, $dloadUrl); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); if (Config::_ENABLE_IP_ROTATION && !Config::_DISABLE_IP_FOR_DOWNLOAD && $vHost == "YouTube" && $converter->GetOutgoingIP() != array()) { $currentIP = $converter->GetOutgoingIP(); $isProxy = !empty($currentIP['port']) || !empty($currentIP['proxy_user']) || !empty($currentIP['proxy_pass']); curl_setopt($ch, CURLOPT_REFERER, ''); if ($isProxy) { curl_setopt($ch, CURLOPT_PROXY, $currentIP['ip'] . ":" . $currentIP['port']); if (!empty($currentIP['proxy_user']) && !empty($currentIP['proxy_pass'])) { curl_setopt($ch, CURLOPT_PROXYUSERPWD, $currentIP['proxy_user'] . ":" . $currentIP['proxy_pass']); } if (Config::_ENABLE_TOR_PROXY) { curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); } curl_setopt($ch, CURLOPT_TIMEOUT, (int)ceil(3 * (round($chunkSize / 1048576, 2) / (1 / 8)))); } else { curl_setopt($ch, CURLOPT_INTERFACE, $currentIP['ip']); curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); } curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); } curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); curl_setopt($ch, CURLOPT_NOPROGRESS, false); curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, array('self', self::ProgressFuncName())); curl_setopt($ch, CURLOPT_BUFFERSIZE, $chunkSize); curl_setopt($ch, CURLOPT_RANGE, $chunkStart.'-'.$chunkEnd); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT, $extractor->GetMainUserAgent()); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); if (isset($vidInfo['cookies'])) { curl_setopt($ch, CURLOPT_COOKIE, $vidInfo['cookies']); } $output = curl_exec($ch); $curlInfo = curl_getinfo($ch); if ((curl_errno($ch) != 0 || $curlInfo['http_code'] != "206") && $numTries < 10) { $numTries++; continue; } $numTries = 0; fwrite($file, $output); $chunkStart += $chunkSize; $chunkStart += ($count == 0) ? 1 : 0; $chunkEnd += $chunkSize; self::$_chunkCount = ++$count; } curl_close($ch); fclose($file); self::$_prevChunkCount = self::$_chunkCount = 0; } /*if (is_file($filename[$urlKey])) echo "is file: " . $filename[$urlKey] . "<br>";*/ } } public static function Download(array $vars) { extract($vars); self::$_isChunkedDload = false; $converter = self::$_converter; $vHost = $converter->GetCurrentVidHost(); $dloadUrls = end($urls[$vidCount]); $dloadUrls = (!is_array($dloadUrls)) ? array($dloadUrls) : $dloadUrls; $resumeKey = 0; foreach ($dloadUrls as $urlKey => $dloadUrl) { self::$_curlResource = $ch = curl_init(); while ($urlKey == $resumeKey) { self::$_percentVidDownloaded = 0; $file = fopen($filename[$urlKey], 'w'); curl_setopt($ch, CURLOPT_FILE, $file); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_URL, $dloadUrl); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); if (Config::_ENABLE_IP_ROTATION && !Config::_DISABLE_IP_FOR_DOWNLOAD && $vHost == "YouTube" && $converter->GetOutgoingIP() != array()) { $currentIP = $converter->GetOutgoingIP(); $isProxy = !empty($currentIP['port']) || !empty($currentIP['proxy_user']) || !empty($currentIP['proxy_pass']); curl_setopt($ch, CURLOPT_REFERER, ''); if ($isProxy) { curl_setopt($ch, CURLOPT_PROXY, $currentIP['ip'] . ":" . $currentIP['port']); if (!empty($currentIP['proxy_user']) && !empty($currentIP['proxy_pass'])) { curl_setopt($ch, CURLOPT_PROXYUSERPWD, $currentIP['proxy_user'] . ":" . $currentIP['proxy_pass']); } if (Config::_ENABLE_TOR_PROXY) { curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); } } else { curl_setopt($ch, CURLOPT_INTERFACE, $currentIP['ip']); curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); } curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); } curl_setopt($ch, CURLOPT_NOPROGRESS, false); curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, array('self', self::ProgressFuncName())); curl_setopt($ch, CURLOPT_BUFFERSIZE, 4096000); curl_setopt($ch, CURLOPT_USERAGENT, $extractor->GetMainUserAgent()); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); if (isset($vidInfo['cookies'])) { curl_setopt($ch, CURLOPT_COOKIE, $vidInfo['cookies']); } curl_exec($ch); if (curl_errno($ch) == 0) { $curlInfo = curl_getinfo($ch); if (($vHost == "Dailymotion" || $vHost == "SoundCloud" || $vHost == "YouTube" || $vHost == "Pornhub") && $curlInfo['http_code'] == '302' && isset($curlInfo['redirect_url']) && !empty($curlInfo['redirect_url'])) { $dloadUrl = $curlInfo['redirect_url']; continue; } if (method_exists($extractor, 'GetCypherUsed') && $extractor->GetCypherUsed() && $curlInfo['http_code'] == '403') { $itag = $extractor->ExtractItagFromUrl($dloadUrl); if (!empty($itag)) { $extractor->FixDecryption($extractor->GetSignature($itag)); } } } fclose($file); $resumeKey++; } curl_close($ch); } } public static function DownloadPlaylist(array $vars) { extract($vars); $converter = self::$_converter; $vHost = $converter->GetCurrentVidHost(); $reqHeaders = (!empty($extractor->_reqHeaders)) ? $extractor->_reqHeaders : ""; $cmd = Config::_FFMPEG . (isset($pre_ffmpeg) ? $pre_ffmpeg : '') . ((!empty($reqHeaders)) ? ' -headers ' . escapeshellarg(implode('\r\n', $reqHeaders) . '\r\n') : '') . ' -i \'' . end($urls[$vidCount]) . '\' -bsf:a ' . ((strrchr($filename[0], ".") == ".mp3" || $vHost == "SoundCloud") ? 'mp3decomp' : 'aac_adtstoasc') . ' -c copy -y ' . $filename[0] . ' 2>&1'; //die($cmd); if (Config::_ENABLE_PLAYLIST_DOWNLOAD_PROGRESS && isset($vidInfo['duration'])) { $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "a") ); $pipes = array(); $process = proc_open($cmd, $descriptorspec, $pipes, null, null); if (is_resource($process)) { $processInfo = false; do { $cmdOutputLine = trim(fgets($pipes[1])); if (preg_match('/(time=)(.+?)(\s)/i', $cmdOutputLine, $times) == 1) { if (preg_match('/(\d\d):(\d\d):(\d\d\.\d\d)/', $times[2], $lastTime) == 1) { $lastTime = ((int)$lastTime[1] * 60 * 60) + ((int)$lastTime[2] * 60) + (float)$lastTime[3]; $progress = round(($lastTime / (float)$vidInfo['duration']) * 100); $progress = ($progress > 100) ? 100 : $progress; self::OutputDownloadProgress($progress, true); } } //echo $cmdOutputLine . "<br>"; if (!empty($cmdOutputLine)) $ffmpegOutput[] = $cmdOutputLine; $processInfo = proc_get_status($process); } while ($processInfo !== false && $processInfo['running']); } fclose($pipes[0]); fclose($pipes[1]); fclose($pipes[2]); proc_close($process); } else { self::OutputDownloadProgress(100, false); exec($cmd, $ffmpegOutput); } return $ffmpegOutput; } public static function DownloadPlaylistNative(array $vars) { extract($vars); $converter = self::$_converter; $vHost = $converter->GetCurrentVidHost(); $reqHeaders = (!empty($extractor->_reqHeaders)) ? $extractor->_reqHeaders : ""; self::OutputDownloadProgress(100, false); $context = stream_context_create(array( 'http' => array( 'method' => "GET", 'header' => $reqHeaders ) )); $m3u8Url = end($urls[$vidCount]); $m3u8file = file_get_contents($m3u8Url, false, $context); if ($m3u8file !== false && !empty($m3u8file)) { $m3u8Lines = preg_split('/\n|\r/', $m3u8file, -1, PREG_SPLIT_NO_EMPTY); $m3u8Lines = preg_grep('/^(#)/', $m3u8Lines, PREG_GREP_INVERT); //die(print_r($m3u8Lines)); if (!empty($m3u8Lines)) { ini_set('memory_limit', '-1'); $videoContent = ''; foreach ($m3u8Lines as $m3u8Line) { //die($m3u8Line); $urlPrefix = preg_replace('/(' . preg_quote(strrchr($m3u8Url, "/"), "/") . ')$/', "", $m3u8Url); $m3u8Line = $urlPrefix . "/" . $m3u8Line; //die($m3u8Line); $tsFileContent = file_get_contents($m3u8Line, false, $context); if ($tsFileContent === false || empty($tsFileContent)) { $videoContent = ''; break; } $videoContent .= $tsFileContent; } if (!empty($videoContent)) { $tmpfname = tempnam(dirname(__DIR__) . "/store", "m3u8"); if ($tmpfname !== false) { $bytes = file_put_contents($tmpfname, $videoContent); if ($bytes !== false && $bytes > 0) { $cmd = Config::_FFMPEG . (isset($pre_ffmpeg) ? $pre_ffmpeg : '') . ' -i ' . escapeshellarg($tmpfname) . ' -c copy -y -f mp4 -bsf:a aac_adtstoasc ' . escapeshellarg($filename[0]) . ' 2>&1'; exec($cmd, $ffmpegOutput); } unlink($tmpfname); } } } } return $ffmpegOutput; } public static function OutputDownloadProgress($percent, $isRealTime) { echo '<script type="text/javascript">updateVideoDownloadProgress("'. $percent .'", ' . (($isRealTime) ? 'true' : 'false') . ');</script>'; $converter = self::$_converter; $converter->FlushBuffer(); } #endregion #region Private "Helper" Methods private static function CheckDownloadUrl($url, Extractor $extractor, array $vidInfo, $vHost) { $retVal = array('isValid' => false, 'filesize' => 0, 'redirectUrl' => ''); $converter = self::$_converter; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_NOBODY, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_USERAGENT, $extractor->GetMainUserAgent()); if (Config::_ENABLE_IP_ROTATION && !Config::_DISABLE_IP_FOR_DOWNLOAD && $converter->GetCurrentVidHost() == "YouTube" && $converter->GetOutgoingIP() != array()) { $currentIP = $converter->GetOutgoingIP(); $isProxy = !empty($currentIP['port']) || !empty($currentIP['proxy_user']) || !empty($currentIP['proxy_pass']); curl_setopt($ch, CURLOPT_REFERER, ''); if ($isProxy) { curl_setopt($ch, CURLOPT_PROXY, $currentIP['ip'] . ":" . $currentIP['port']); if (!empty($currentIP['proxy_user']) && !empty($currentIP['proxy_pass'])) { curl_setopt($ch, CURLOPT_PROXYUSERPWD, $currentIP['proxy_user'] . ":" . $currentIP['proxy_pass']); } if (Config::_ENABLE_TOR_PROXY) { curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); } } else { curl_setopt($ch, CURLOPT_INTERFACE, $currentIP['ip']); curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); } curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); } curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); if (isset($vidInfo['cookies'])) { curl_setopt($ch, CURLOPT_COOKIE, $vidInfo['cookies']); } $headers = curl_exec($ch); if (curl_errno($ch) == 0) { $info = curl_getinfo($ch); //die(print_r($info)); $retVal['filesize'] = (int)$info['download_content_length']; if (($vHost == "Dailymotion" || $vHost == "SoundCloud" || $vHost == "YouTube" || $vHost == "Pornhub") && $info['http_code'] == '302' && isset($info['redirect_url']) && !empty($info['redirect_url'])) { $retVal['redirectUrl'] = $info['redirect_url']; } if (method_exists($extractor, 'GetCypherUsed') && $extractor->GetCypherUsed() && $info['http_code'] == '403') { $itag = $extractor->ExtractItagFromUrl($url); if (!empty($itag)) { $extractor->FixDecryption($extractor->GetSignature($itag)); } } else { $retVal['isValid'] = $info['http_code'] != '404' && $info['http_code'] != '403'; } } curl_close($ch); return $retVal; } private static function ProgressFuncName() { return (Config::_PHP_VERSION >= 5.5) ? ((self::$_isChunkedDload) ? 'UpdateVideoChunkDownloadProgress' : 'UpdateVideoDownloadProgress') : 'LegacyUpdateVideoDownloadProgress'; } private static function UpdateVideoDownloadProgress($curlResource, $downloadSize, $downloaded, $uploadSize, $uploaded) { $httpCode = curl_getinfo($curlResource, CURLINFO_HTTP_CODE); if ($httpCode == "200" && $downloadSize > 0) { $percent = round($downloaded / $downloadSize, 2) * 100; if ($percent > self::$_percentVidDownloaded) { self::$_percentVidDownloaded++; self::OutputDownloadProgress($percent, true); } } } private static function UpdateVideoChunkDownloadProgress($curlResource, $downloadSize, $downloaded, $uploadSize, $uploaded) { $httpCode = curl_getinfo($curlResource, CURLINFO_HTTP_CODE); if ($httpCode == "206" && $downloadSize > 0 && self::$_chunkCount != self::$_prevChunkCount) { self::$_prevChunkCount++; self::$_downloaded += $downloadSize; $percent = round(self::$_downloaded / self::$_fsize, 2) * 100; if ($percent > self::$_percentVidDownloaded) { self::$_percentVidDownloaded++; self::OutputDownloadProgress($percent, true); } } } // Deprecated - May be removed in future versions! private static function LegacyUpdateVideoDownloadProgress($downloadSize, $downloaded, $uploadSize, $uploaded) { if (self::$_isChunkedDload) { self::UpdateVideoChunkDownloadProgress(self::$_curlResource, $downloadSize, $downloaded, $uploadSize, $uploaded); } else { self::UpdateVideoDownloadProgress(self::$_curlResource, $downloadSize, $downloaded, $uploadSize, $uploaded); } } #endregion } ?> (03) VideoConverter.php <?php namespace YouTubeMp3Converter\lib; // Conversion Class class VideoConverter extends Config { // Private Fields private $_convertedFileName = ''; private $_convertedFileType = ''; private $_convertedFileCategory = ''; private $_convertedFileQuality = Config::_DEFAULT_AUDIO_QUALITY; private $_convertedFileVolume = Config::_VOLUME; private $_vidSourceUrls = array(); private $_tempVidFileName = array(); private $_uniqueID; private $_currentVidHost = ''; private $_vidInfo = array(); private $_validationError = ''; private $_skipConversion = false; private $_ffmpegCommand = ''; private $_extractor; private $_outgoingIP = array(); private $_doFFmpegCopy = false; private $_pluginInfo = array(); // Constants const _FILENAME_DELIMITER = "~~"; const _MAX_FILENAME_LENGTH = 255; const _URL_WILDCARD_PATTERN = '[^\\\\/\?]+'; #region Public Methods function __construct() { if (isset($_SESSION)) { $this->_uniqueID = (!isset($_SESSION[Config::_SITENAME])) ? time() . "_" . uniqid('', true) : $_SESSION[Config::_SITENAME]; $_SESSION[Config::_SITENAME] = (!isset($_SESSION[Config::_SITENAME])) ? $this->_uniqueID : $_SESSION[Config::_SITENAME]; $_SESSION['execFFmpegToken'] = (!isset($_SESSION['execFFmpegToken'])) ? uniqid($this->_uniqueID, true) : $_SESSION['execFFmpegToken']; $_SESSION['execFFmpegToken2'] = (!isset($_SESSION['execFFmpegToken2'])) ? uniqid($this->_uniqueID, true) : $_SESSION['execFFmpegToken2']; if (Config::_ENABLE_IP_ROTATION && !Config::_ENABLE_TOR_PROXY) Database::Connect(Config::_SERVER, Config::_DB_USER, Config::_DB_PASSWORD, Config::_DATABASE); $this->_pluginInfo = Plugin::Init(); // Load any plugin data } else { die('Error!: Session must be started in the calling file to use this class.'); } } function __destruct() { if (Config::_ENABLE_IP_ROTATION && !Config::_ENABLE_TOR_PROXY && class_exists('Database')) Database::Close(); } function DownloadVideo($vidUrl) { $videoInfo = $this->GetVidInfo(); if (!empty($videoInfo)) { $this->SetConvertedFileName(); $this->SetVidSourceUrls(); if ($this->GetConvertedFileName() != '' && count($this->GetVidSourceUrls()) > 0) { $urls = $this->GetVidSourceUrls(); if ((Config::_CACHING_ENABLED && !Config::_ENABLE_DIRECT_DOWNLOAD) || (Config::_ENABLE_DIRECT_DOWNLOAD && $this->GetConvertedFileCategory() != 'audio' && $this->GetConvertedFileVolume() == Config::_VOLUME)) { $urls = $this->FilterUrls($urls); //die(print_r($urls)); } return $this->SaveVideo($urls); } } return false; } function DoConversion() { $extractor = $this->GetExtractor(); $vidHost = $this->GetCurrentVidHost(); $fileType = $this->GetConvertedFileType(); $fileCategory = $this->GetConvertedFileCategory(); $fileQuality = $this->GetConvertedFileQuality(); $fileVolume = $this->GetConvertedFileVolume(); $newFile = $this->GetConvertedFileName(); $tempFile = $this->GetTempVidFileName(); $tmpNewFile = preg_replace('/^((.+)(' . preg_quote(strrchr($newFile, "."), '/') . '))$/', "$2.tmp$3", $newFile); if (!empty($fileType) && !empty($newFile) && !empty($tempFile)) { $exec_string = ''; $ftypes = $this->GetConvertedFileTypes(); foreach ($ftypes as $ftype) { if ($fileType == $ftype['fileExt']) { $videoBitrate = Config::_DEFAULT_VIDEO_QUALITY; if ($fileCategory == 'video') { exec(Config::_FFMPEG . ' -i ' . $tempFile[0] . ' 2>&1 | grep "Video:\|bitrate:"', $output); if (count($output) > 0) { foreach ($output as $line) { if (preg_match('/(\d+)( kb\/s)/i', $line, $matches) == 1) { $videoBitrate = $matches[1]; break; } } } } $ftypeFFmpeg = (isset($ftype['ffmpegCopy']) && $fileVolume == Config::_VOLUME && $fileQuality == Config::_DEFAULT_AUDIO_QUALITY && (($fileType == "aac" && $vidHost == "YouTube" && $extractor->AudioAvailable()) || $this->_doFFmpegCopy)) ? $ftype['ffmpegCopy'] : $ftype['ffmpeg']; $tempFile2 = ''; if (isset($ftype['ffmpegMerge'], $ftype['ffmpegMergeAndVol']) && count($tempFile) > 1) { $ftypeFFmpeg = ($fileVolume == Config::_VOLUME) ? $ftype['ffmpegMerge'] : $ftype['ffmpegMergeAndVol']; $tempFile2 = $tempFile[1]; } $this->_ffmpegCommand = $exec_string = preg_replace( array('/%ffmpeg%/', '/%tempFile%/', '/%tempFile2%/', '/%volume%/', '/%quality%/', '/%vquality%/', '/%newFile%/', '/%logsDir%/', '/%id%/'), array(Config::_FFMPEG, $tempFile[0], $tempFile2, $fileVolume, $fileQuality, $videoBitrate, $tmpNewFile, Config::_LOGSDIR, $this->_uniqueID), $ftypeFFmpeg ); break; } } //die($exec_string); if (!is_dir(realpath(Config::_LOGSDIR))) mkdir(Config::_LOGSDIR, 0777); if (is_file(realpath(Config::_LOGSDIR . $this->_uniqueID . ".txt"))) unlink(realpath(Config::_LOGSDIR . $this->_uniqueID . ".txt")); // If previous conversion was abandoned, remove corresponding log file with same file name, if it exists, to prevent subsequent conversion failure! $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443; if (!$isHttps && isset($_SERVER['HTTP_CF_VISITOR'])) { $cfJson = json_decode($_SERVER['HTTP_CF_VISITOR'], true); if (json_last_error() == JSON_ERROR_NONE) { $isHttps = !empty($cfJson) && current($cfJson) == 'https'; } } $protocol = ($isHttps) ? "https://" : "http://"; $ffmpegExecUrl = preg_replace('/(([^\/]+?)(\.php))$/', "exec_ffmpeg.php", $protocol.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']); $postData = "cmd=".urlencode($exec_string)."&token=".urlencode($_SESSION['execFFmpegToken'])."&fname=".urlencode($tmpNewFile); $strCookie = 'PHPSESSID=' . session_id() . '; path=/'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $ffmpegExecUrl); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_COOKIE, $strCookie); curl_exec($ch); curl_close($ch); } } function DownloadConvertedFile($file, $directory) { $ftypes = $this->GetConvertedFileTypes(); $filepath = $directory . urldecode($file); $ftype = trim(strrchr($filepath, '.'), '.'); $vidHostAbbr = current(explode('/', urldecode($file))); $mimeTypes = array(); array_walk($ftypes, function($ftype) use(&$mimeTypes) {$mimeTypes[$ftype['fileExt']] = $ftype['mimeType'];}); //print_r($mimeTypes); //die("\n\nftype: " . $ftype . ", vidHostAbbr: " . $vidHostAbbr); if ($this->ValidateDownloadFileName($filepath, $directory, array_keys($mimeTypes))) { $filename = $this->PrepareConvertedFileNameForDownload($file); $filepath = realpath($filepath); if (Config::_DELAY_POPULAR_FILE_DELETION && Config::_CACHING_ENABLED && (!Config::_ENABLE_DIRECT_DOWNLOAD || (Config::_ENABLE_DIRECT_DOWNLOAD && $vidHostAbbr != "sc" && ($ftype == "mp3" || $ftype == "aac")))) { $attr = array(); exec(Config::_ATTR . ' -q -g time.created ' . escapeshellarg($filepath) . ' 2>&1', $attr); if (count($attr) > 1) { $attr = array(); exec(Config::_ATTR . ' -s time.created -V ' . time() . ' ' . escapeshellarg($filepath)); exec(Config::_ATTR . ' -q -g time.created ' . escapeshellarg($filepath) . ' 2>&1', $attr); } if (count($attr) == 1 && preg_match('/^(\d+)$/', $attr[0]) == 1) { if (time() - (int)$attr[0] < Config::_MAX_DELETION_DELAY && time() - filemtime($filepath) < Config::_MAX_POPULAR_FILE_INCREMENT) { touch($filepath); } } } //if (filesize($filepath) > 10000) touch($filepath); $contentType = ($ftype == 'm4a') ? $mimeTypes['mp3'] : $mimeTypes[$ftype]; header('Content-Type: ' . $contentType); header('Content-Length: ' . filesize($filepath)); header('Content-Disposition: attachment; filename="'.$filename.'"'); ob_clean(); flush(); readfile($filepath); die(); } else { $redirect = explode("?", $_SERVER['REQUEST_URI']); header('Location: ' . $redirect[0]); } } function ValidateConversionForm($vidUrl, $ftype, $getVidInfo=false, $moreOptions=array()) { $vidHostName = $convertedFtype = ''; $vidHosts = $this->GetVideoHosts(); $urlRoots = array(); $urlSuffix = ''; foreach ($vidHosts as $host) { foreach ($host['url_root'] as $urlRoot) { //$urlRoot = preg_replace('/^(([^\?]+?)(\?{1})(.+))$/', "$2$3", $urlRoot); $wildcardRegex = (Config::_PHP_VERSION >= 7.3) ? '/\\\#wildcard\\\#/' : '/#wildcard#/'; $rootUrlPattern = preg_replace($wildcardRegex, self::_URL_WILDCARD_PATTERN, preg_quote($urlRoot, '/')); $rootUrlPattern = ($host['allow_https_urls']) ? preg_replace('/^(http)/', "https?", $rootUrlPattern) : $rootUrlPattern; if (preg_match('/^(('.$rootUrlPattern.')(.+))/i', $vidUrl, $matches) == 1 && preg_match('/'.$rootUrlPattern.'/', $matches[3]) != 1) { $vidHostName = $host['name']; $urlRoots = $host['url_root']; $urlSuffix = $matches[3]; break 2; } } } $ftypes = $this->GetConvertedFileTypes(); $convertedFtype = (in_array($ftype, array_keys($ftypes))) ? $ftypes[$ftype]['fileExt'] : ''; $convertedFcategory = (in_array($ftype, array_keys($ftypes))) ? current(explode("/", $ftypes[$ftype]['mimeType'])) : ''; $convertedFquality = (in_array($ftype, array_keys($ftypes)) && isset($ftypes[$ftype]['quality'])) ? $ftypes[$ftype]['quality'] : Config::_DEFAULT_AUDIO_QUALITY; $convertedFvolume = (isset($moreOptions['volume'])) ? $moreOptions['volume'] : Config::_VOLUME; if (!empty($vidHostName) && !empty($convertedFtype) && !empty($convertedFcategory)) { foreach ($urlRoots as $urlroot) { $urlroot = preg_replace('/^(https?)/', "", $urlroot); if (isset(Config::$_urlBlacklist["https" . $urlroot . $urlSuffix]) || isset(Config::$_urlBlacklist["http" . $urlroot . $urlSuffix])) { $this->_validationError = 'Validation_Error_Copyright'; return false; } } if ($vidHostName == 'SoundCloud' && $convertedFcategory == 'video') { $this->_validationError = 'Validation_Error_Audio_To_Video'; return false; } $this->SetCurrentVidHost($vidHostName); $this->SetConvertedFileType($convertedFtype); $this->SetConvertedFileCategory($convertedFcategory); $this->SetConvertedFileQuality($convertedFquality); $this->SetConvertedFileVolume($convertedFvolume); $this->SetExtractor($vidHostName); if ($getVidInfo) { $extractor = $this->GetExtractor(); $this->_vidInfo = $extractor->RetrieveVidInfo($vidUrl); //die(print_r($this->_vidInfo)); if (isset($this->_vidInfo['is_video_audio']) && !$this->_vidInfo['is_video_audio']) { $this->_validationError = 'Validation_Error_General'; return false; } $isOkDuration = true; if (isset($this->_vidInfo['duration'])) { foreach ($ftypes as $ftype) { if ($isOkDuration) { $quality = (isset($ftype['quality'])) ? $ftype['quality'] : Config::_DEFAULT_AUDIO_QUALITY; $isOkDuration = ($ftype['fileExt'] == $convertedFtype && $quality == $convertedFquality) ? (($ftype['maxDuration'] != -1) ? $ftype['maxDuration'] >= $this->_vidInfo['duration'] : true) : true; } } } if (!$isOkDuration) { $this->_validationError = 'Validation_Error_Vid_Length'; return false; } } return true; } $this->_validationError = 'Validation_Error_General'; return false; } function PrepareConvertedFileNameForDownload($file) { $filename = urldecode($file); $filename = current(array_reverse(explode(self::_FILENAME_DELIMITER, $filename))); $ftypesForRegex = $this->GetConvertedFileTypes(); if (Config::_ENABLE_CONCURRENCY_CONTROL) { array_walk($ftypesForRegex, function(&$ftype, $key) {$ftype = $ftype['fileExt'];}); $replacementStr = ((Config::_ENABLE_FILENAME_BRANDING) ? '[' . Config::_SITENAME . ']' : '') . "$4$5"; $filename = preg_replace('/((_uuid-)(\w{13})(\.)('.implode('|', $ftypesForRegex).'))$/', $replacementStr, $filename); } $fileBasename = pathinfo($filename, PATHINFO_FILENAME); $filename = (empty($fileBasename) || (!Config::_ENABLE_UNICODE_SUPPORT && preg_match('/^([^a-zA-Z0-9]+)$/', $fileBasename) == 1)) ? 'unknown' . strrchr($filename, '.') : $filename; return preg_replace('/_/', " ", $filename); } function ExtractVideoId($vidUrl) { $id = ''; $url = trim($vidUrl); $urlQueryStr = parse_url($url, PHP_URL_QUERY); if ($urlQueryStr !== false && !empty($urlQueryStr)) { parse_str($urlQueryStr, $params); if (isset($params['v']) && !empty($params['v'])) { $id = $params['v']; } else { $url = preg_replace('/(\?' . preg_quote($urlQueryStr, '/') . ')$/', "", $url); $id = trim(strrchr(trim($url, '/'), '/'), '/'); } } else { $id = trim(strrchr(trim($url, '/'), '/'), '/'); } return $id; } function RetrieveCachedFile() { $fileName = ''; $videoInfo = $this->GetVidInfo(); $ftype = $this->GetConvertedFileType(); $fquality = $this->GetConvertedFileQuality(); $fvolume = $this->GetConvertedFileVolume(); $extractor = $this->GetExtractor(); $vidHost = $this->GetCurrentVidHost(); $videoInfo['host_abbrev'] = $extractor->ReturnConfig('abbreviation'); if ((!Config::_ENABLE_DIRECT_DOWNLOAD || (Config::_ENABLE_DIRECT_DOWNLOAD && $vidHost != "SoundCloud" && ($ftype == "mp3" || $ftype == "aac"))) && !empty($videoInfo) && !empty($videoInfo['title']) && !empty($videoInfo['id']) && !is_null($videoInfo['host_abbrev'])) { $vTitle = html_entity_decode($videoInfo['title'], ENT_COMPAT | ENT_HTML401, 'UTF-8'); $fname = (!Config::_ENABLE_UNICODE_SUPPORT) ? preg_replace('/[^A-Za-z0-9 _-]/', '', $vTitle) : preg_replace('#/#', '', preg_replace('/\\\\|\/|\?|%|\*|:|\||"|<|>|\]|\[|\(|\)|\.|&|\^|\$|#|@|\!|`|~|=|\+|,|;|\'|\{|\}/', '', $vTitle)); $fname = preg_replace('/_{2,}/', '_', preg_replace('/ /', '_', $fname)); $dirName = Config::_CONVERTED_FILEDIR . $videoInfo['host_abbrev'] . '/' . $videoInfo['id'] . '/'; if (is_dir(realpath($dirName))) { $filesystemIterator = new \FilesystemIterator(realpath($dirName), \FilesystemIterator::KEY_AS_FILENAME); $regexIterator = new \RegexIterator($filesystemIterator, '/^(('.preg_quote($fquality . self::_FILENAME_DELIMITER . $fvolume . self::_FILENAME_DELIMITER . $fname, '/').')((_uuid-)(\w+))?(\.)('.preg_quote($ftype, '/').'))$/', \RegexIterator::MATCH, \RegexIterator::USE_KEY); $files = array_keys(iterator_to_array($regexIterator)); if (!empty($files)) { foreach ($files as $file) { if (is_file(realpath($dirName . $file))) { $fileName = $dirName . $file; break; } } } } } //die($fileName); return $fileName; } function FlushBuffer() { if (ob_get_length() > 0) ob_end_flush(); if (ob_get_length() > 0) ob_flush(); flush(); } function ValidateFile(array $filename, array $params) { extract($params); $error = true; foreach ($filename as $fname) { if (is_file($fname)) { $durationDiff = 0; $getID3 = new \getID3; $fileInfo = @$getID3->analyze($fname); //print_r($fileInfo); if (isset($duration)) { if (!isset($fileInfo['playtime_seconds'])) { // Use FFmpeg to detect duration as a backup!! exec(Config::_FFMPEG . ' -i ' . $fname . ' 2>&1', $ffOutput); //die(print_r($ffOutput)); if (count($ffOutput) > 0) { foreach ($ffOutput as $line) { if (preg_match('/Duration:\s*(\d{2}:\d{2}:\d{2})/', $line, $matches) == 1) { $fileInfo['playtime_seconds'] = strtotime("1970-01-01 " . $matches[1] . " UTC"); break; } } } } $durationDiff = (isset($fileInfo['playtime_seconds'])) ? abs((float)$fileInfo['playtime_seconds'] - (float)$duration) : $durationDiff; } $error = !filesize($fname) || filesize($fname) < 10000 || (isset($isPlaylist) && isset($ffmpegOutput) && $isPlaylist && (empty($ffmpegOutput) || preg_match('/muxing overhead/i', end($ffmpegOutput)) != 1)) || !isset($fileInfo['playtime_seconds']) || $durationDiff > Config::_MAX_ALLOWED_DURATION_DIFFERENCE; if ($error) break; } } return !$error; } #endregion #region Private "Helper" Methods private function ValidateDownloadFileName($filepath, $directory, array $fileExts) { $isValid = false; $fullFilepath = realpath($filepath); if ($fullFilepath !== false && $fullFilepath != $filepath && is_file($fullFilepath)) { $normalizedAppRoot = (Config::_APPROOT != "/") ? preg_replace('/\//', DIRECTORY_SEPARATOR, Config::_APPROOT) : DIRECTORY_SEPARATOR; $pathBase = realpath($_SERVER['DOCUMENT_ROOT']) . $normalizedAppRoot; $safePath = preg_replace('/^(' . preg_quote($pathBase, '/') . ')/', "", $fullFilepath); if ($safePath != $fullFilepath && preg_match('/^(' . preg_quote(preg_replace('/\//', DIRECTORY_SEPARATOR, $directory), '/') . ')/', $safePath) == 1) { $fileExt = pathinfo($fullFilepath, PATHINFO_EXTENSION); $isValid = in_array($fileExt, $fileExts); } } return $isValid; } private function FilterUrls(array $urls) { $filteredUrls = array(); $ftype = $this->GetConvertedFileType(); $vidHosts = array_values($this->GetVideoHosts()); $vidQualities = array_keys($vidHosts[0]['video_qualities']); $ftypes = $this->GetConvertedFileTypes(); $uniqueFtypes = array(); array_walk($ftypes, function($ft, $key) use(&$uniqueFtypes) {if (!isset($uniqueFtypes[$ft['fileExt']]) && isset($ft['qualityTolerance'])) $uniqueFtypes[$ft['fileExt']] = $ft['qualityTolerance'];}); if (Config::_ENABLE_DIRECT_DOWNLOAD && isset($uniqueFtypes[$ftype])) { $availableQualityIndexes = array(); array_walk($urls, function($url) use(&$availableQualityIndexes, $vidQualities) {if (in_array($url[1], $vidQualities)) $availableQualityIndexes[] = array_search($url[1], $vidQualities);}); $ftypeQualityIndex = array_search($uniqueFtypes[$ftype], $vidQualities); $reduceQualityToleranceFurther = false; do { $filteredAvailableQuals = array_filter($availableQualityIndexes, function($index) use($ftypeQualityIndex) {return $index <= $ftypeQualityIndex;}); if (empty($filteredAvailableQuals)) { $uniqueFtypes[$ftype] = $vidQualities[++$ftypeQualityIndex]; $reduceQualityToleranceFurther = $ftypeQualityIndex < count($vidQualities) - 1; } else { $reduceQualityToleranceFurther = false; } } while ($reduceQualityToleranceFurther); } foreach ($urls as $url) { $qualityToleranceCondition = (Config::_ENABLE_DIRECT_DOWNLOAD) ? array_search($url[1], $vidQualities) <= array_search($uniqueFtypes[$ftype], $vidQualities) : true; if ($ftype == $url[0] && in_array($url[1], $vidQualities) && $qualityToleranceCondition) { $filteredUrls[] = $url; } } return $filteredUrls; } private function SaveVideo(array $urls) { //die(print_r($urls)); //die(print_r($this->GetVidSourceUrls())); $vidInfo = $this->GetVidInfo(); $extractor = $this->GetExtractor(); $this->_skipConversion = $skipConversion = Config::_ENABLE_DIRECT_DOWNLOAD && (($this->GetConvertedFileCategory() != 'audio' && ($this->GetCurrentVidHost() != 'YouTube' || ($this->GetConvertedFileType() == '3gp' && $extractor->ThreegpAvailable()))) || ($this->GetCurrentVidHost() == 'SoundCloud' && !$vidInfo['downloadable'] && $this->GetConvertedFileType() == 'mp3' && $this->GetConvertedFileQuality() == '128') || ($this->GetCurrentVidHost() == 'YouTube' && $extractor->AudioAvailable() && $this->GetConvertedFileType() == 'm4a')) && $this->GetConvertedFileVolume() == Config::_VOLUME && !empty($urls); $this->_doFFmpegCopy = $doFFmpegCopy = ((Config::_CACHING_ENABLED && !Config::_ENABLE_DIRECT_DOWNLOAD) || (Config::_ENABLE_DIRECT_DOWNLOAD && $this->GetCurrentVidHost() == 'YouTube' && $this->GetConvertedFileCategory() != 'audio' && !$skipConversion)) && !empty($urls); if (!$skipConversion && !$doFFmpegCopy) $urls = $this->GetVidSourceUrls(); $success = false; $vidCount = -1; //die(print_r($urls)); $urls = array_values($urls); while (!$success && ++$vidCount < count($urls)) { if (isset($urls[$vidCount-1]) && $urls[$vidCount-1][1] == 'au' && $skipConversion && $this->GetCurrentVidHost() == 'YouTube' && $this->GetConvertedFileType() == 'm4a') { $this->_skipConversion = $skipConversion = false; } if (!$skipConversion) { $this->SetTempVidFileName(); if (is_array(end($urls[$vidCount]))) { $this->SetTempVidFileName(); } } $filename = (!$skipConversion) ? $this->GetTempVidFileName() : $this->GetConvertedFileName(); $filename = (!is_array($filename)) ? array($filename) : $filename; $tries = 0; $isPlaylist = preg_match('/^((\.m3u8)(.*))$/', (string)strrchr((string)parse_url(end($urls[$vidCount]), PHP_URL_PATH), ".")) == 1; $ffmpegOutput = array(); $pre_ffmpeg = isset($vidInfo['ff_pre']) ? $vidInfo['ff_pre'] : ''; do { $dloadVars = compact('extractor', 'vidInfo', 'urls', 'vidCount', 'filename', 'tries', 'ffmpegOutput', 'pre_ffmpeg'); $remote = (isset($this->_pluginInfo['AntiCaptcha']['Remote'][$this->GetCurrentVidHost()])) ? $this->_pluginInfo['AntiCaptcha']['Remote'][$this->GetCurrentVidHost()] : __NAMESPACE__ . '\\Remote'; $remote::Init($this); if ($isPlaylist) { $nativePlaylistDload = $extractor->ReturnConfig("enable_native_playlist_download"); if(isset($vidInfo['ff_for']) && $vidInfo['ff_for']) $ffmpegOutput = $remote::DownloadPlaylist($dloadVars); else $ffmpegOutput = (!is_null($nativePlaylistDload) && $nativePlaylistDload) ? $remote::DownloadPlaylistNative($dloadVars) : $remote::DownloadPlaylist($dloadVars); //die(print_r($ffmpegOutput)); } else { $isChunkedDload = $extractor->ReturnConfig('enable_chunked_download'); if (!is_null($isChunkedDload) && $isChunkedDload) { $remote::ChunkedDownload($dloadVars); } else { $remote::Download($dloadVars); } } $vidDurArr = (isset($vidInfo['duration'])) ? array('duration' => $vidInfo['duration']) : array(); $success = $this->ValidateFile($filename, $vidDurArr + compact('isPlaylist', 'ffmpegOutput')); if (!$success) { foreach ($filename as $fname) { if (is_file($fname)) unlink($fname); } $ffmpegOutput = array(); } $tries++; } while (!$success && Config::_ENABLE_IP_ROTATION && $tries < Config::_MAX_CURL_TRIES && $this->GetCurrentVidHost() == "YouTube"); } return $success; } #endregion #region Properties public function GetConvertedFileName() { return $this->_convertedFileName; } private function SetConvertedFileName() { $videoInfo = $this->GetVidInfo(); //die($videoInfo['title']); $ftype = $this->GetConvertedFileType(); $fquality = $this->GetConvertedFileQuality(); $fvolume = $this->GetConvertedFileVolume(); $extractor = $this->GetExtractor(); $videoInfo['host_abbrev'] = $extractor->ReturnConfig('abbreviation'); if (!empty($videoInfo) && !empty($videoInfo['title']) && !empty($videoInfo['id']) && !is_null($videoInfo['host_abbrev']) && !empty($ftype)) { $vTitle = html_entity_decode($videoInfo['title'], ENT_COMPAT | ENT_HTML401, 'UTF-8'); $fnameTitle = (!Config::_ENABLE_UNICODE_SUPPORT) ? preg_replace('/[^A-Za-z0-9 _-]/', '', $vTitle) : preg_replace('#/#', '', preg_replace('/\\\\|\/|\?|%|\*|:|\||"|<|>|\]|\[|\(|\)|\.|&|\^|\$|#|@|\!|`|~|=|\+|,|;|\'|\{|\}/', '', $vTitle)); $fnameTitle = preg_replace('/_{2,}/', '_', preg_replace('/ /', '_', $fnameTitle)); $fname = ''; $excessFilenameLength = -1; do { $fnameTitle = ($excessFilenameLength >= 0) ? substr($fnameTitle, 0, strlen($fnameTitle) - $excessFilenameLength - 1) : $fnameTitle; $fname = $fquality . self::_FILENAME_DELIMITER . $fvolume . self::_FILENAME_DELIMITER . $fnameTitle; $fname .= (Config::_ENABLE_CONCURRENCY_CONTROL) ? uniqid('_uuid-') : ''; $fname .= '.' . $ftype; $excessFilenameLength = strlen($fname) - self::_MAX_FILENAME_LENGTH; } while ($excessFilenameLength >= 0); // If file name length is greater than or equal to _MAX_FILENAME_LENGTH bytes, truncate X characters from end of title in file name until the full file name is less than _MAX_FILENAME_LENGTH bytes. $dirName = Config::_CONVERTED_FILEDIR . $videoInfo['host_abbrev'] . '/' . $videoInfo['id'] . '/'; if (!is_dir(realpath($dirName))) mkdir($dirName, 0777, true); $this->_convertedFileName = $dirName . $fname; } //die($this->_convertedFileName); } public function GetVidSourceUrls() { return $this->_vidSourceUrls; } private function SetVidSourceUrls() { $extractor = $this->GetExtractor(); $this->_vidSourceUrls = $extractor->ExtractVidSourceUrls(); } public function GetTempVidFileName() { return $this->_tempVidFileName; } private function SetTempVidFileName() { $extractor = $this->GetExtractor(); $srcVideoType = $extractor->ReturnConfig('src_video_type'); if (!is_null($srcVideoType)) { if (!is_dir(realpath(Config::_TEMPVIDDIR))) mkdir(Config::_TEMPVIDDIR, 0777); $tmpFnameCount = (!empty($this->_tempVidFileName)) ? count($this->_tempVidFileName) + 1 : 1; $tmpFileName = Config::_TEMPVIDDIR . $tmpFnameCount . '_' . $this->_uniqueID . '.' . $srcVideoType; $this->_tempVidFileName = (!empty($this->_tempVidFileName)) ? array_merge($this->_tempVidFileName, array($tmpFileName)) : array($tmpFileName); } //die($this->_tempVidFileName); } public function GetUniqueID() { return $this->_uniqueID; } public function GetConvertedFileTypes() { return $this->_convertedFileTypes; } public function GetVideoHosts() { return $this->_videoHosts; } public function GetCurrentVidHost() { return $this->_currentVidHost; } public function SetCurrentVidHost($hostName) { $this->_currentVidHost = $hostName; } public function GetVidInfo() { return $this->_vidInfo; } public function SetVidInfo($vidInfo) { $this->_vidInfo = $vidInfo; } public function GetConvertedFileType() { return $this->_convertedFileType; } private function SetConvertedFileType($ftype) { $this->_convertedFileType = $ftype; } public function GetConvertedFileCategory() { return $this->_convertedFileCategory; } private function SetConvertedFileCategory($fcat) { $this->_convertedFileCategory = $fcat; } public function GetConvertedFileQuality() { return $this->_convertedFileQuality; } private function SetConvertedFileQuality($quality) { $this->_convertedFileQuality = $quality; } public function GetConvertedFileVolume() { return $this->_convertedFileVolume; } private function SetConvertedFileVolume($volume) { $this->_convertedFileVolume = $volume; } public function GetExtractor() { return $this->_extractor; } public function SetExtractor($vidHostName) { //die(print_r($this->_pluginInfo)); $className = (isset($this->_pluginInfo['AntiCaptcha']['Extractors'][$vidHostName])) ? $this->_pluginInfo['AntiCaptcha']['Extractors'][$vidHostName] : __NAMESPACE__ . "\\extractors\\"; $className .= $vidHostName; try {$this->_extractor = new $className($this);} catch(\Exception $ex) {} } public function GetSkipConversion() { return $this->_skipConversion; } public function GetFFmpegCommand() { return $this->_ffmpegCommand; } public function GetValidationError() { return $this->_validationError; } public function GetOutgoingIP() { return $this->_outgoingIP; } public function SetOutgoingIP() { $noTor = !Config::_ENABLE_TOR_PROXY; $skipIP = false; $outgoingIP = (!$noTor) ? array('ip' => '127.0.0.1', 'port' => Config::_TOR_PROXY_PORT) : array(); $tries = 0; $resetBan = array(); do { if ($noTor) { $resetBan = array(); if (Config::_IP_ROTATION_METHOD == "round-robin") { $ips = Database::Find(Config::_DB_IPS_TABLE, array('order' => array('usage_count'))); $outgoingIP = (!empty($ips)) ? $ips[0] : array(); } else { $ips = Database::Find(Config::_DB_IPS_TABLE, array('order' => array('id'))); $allBanned = true; if (!empty($ips)) { foreach ($ips as $ip) { if ($ip['banned'] == 0) { $outgoingIP = $ip; $allBanned = false; break; } } if ($allBanned) { Database::UpdateAll(Config::_DB_IPS_TABLE, array('banned' => 0)); $ips = Database::Find(Config::_DB_IPS_TABLE, array('order' => array('id'))); $outgoingIP = (!empty($ips)) ? $ips[0] : array(); } } } } if (!empty($outgoingIP)) { if ($this->GetCurrentVidHost() == "YouTube") { $skipIP = ($noTor) ? $outgoingIP['banned'] != 0 && time() - $outgoingIP['banned'] < Config::_IP_BAN_PAUSE : false; if (!$skipIP) { $extractor = $this->GetExtractor(); $ipReqResult = $extractor->CheckIp($outgoingIP); $resetBan = ($noTor) ? (($ipReqResult['isBanned']) ? array('banned' => time()) : array('banned' => 0)) : $resetBan; $skipIP = $ipReqResult['isBanned'] || $ipReqResult['isCurlErr']; if (!$noTor && $skipIP) { $fp = fsockopen($outgoingIP['ip'], Config::_TOR_CONTROL_PORT, $error_number, $err_string, 10); if ($fp !== false) { fwrite($fp, "AUTHENTICATE \"" . Config::_TOR_PROXY_PASSWORD . "\"\n"); $received = fread($fp, 512); fwrite($fp, "signal NEWNYM\n"); $received = fread($fp, 512); fclose($fp); } } } if ($noTor) { Database::Save(Config::_DB_IPS_TABLE, array('id' => $outgoingIP['id'], 'usage_count' => ++$outgoingIP['usage_count']) + $resetBan); } } } $tries++; } while ((empty($outgoingIP) || $skipIP) && $tries < Config::_MAX_CURL_TRIES); $this->_outgoingIP = (empty($outgoingIP)) ? array('ip' => $_SERVER['SERVER_ADDR']) : $outgoingIP; } #endregion } ?> (04) Extractor.php <?php namespace YouTubeMp3Converter\lib\extractors; use YouTubeMp3Converter\lib\Config; use YouTubeMp3Converter\lib\VideoConverter; // Extraction Base Class abstract class Extractor { // Common Fields protected $_converter; protected $_isCurlError = false; protected $_headers = array(); protected $_mainUserAgent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Ubuntu/12.04 Chromium/18.0.1025.168 Chrome/18.0.1025.168 Safari/535.19'; protected $_videoWebpageUrl = ''; protected $_videoWebpage = ''; public $_reqHeaders = array(); // Common Public Methods function __construct(VideoConverter $converter) { $this->_converter = $converter; } function ReturnConfig($setting) { $config = NULL; $converter = $this->GetConverter(); $vidHosts = $converter->GetVideoHosts(); foreach ($vidHosts as $host) { if ($host['name'] == $converter->GetCurrentVidHost() && isset($host[$setting])) { $config = $host[$setting]; break; } } return $config; } function CheckIp($ip) { $noWebpageUrl = empty($this->_videoWebpageUrl); $url = ($noWebpageUrl) ? current($this->ReturnConfig('url_root')) . $this->ReturnConfig('url_example_suffix') : $this->_videoWebpageUrl; $ipReqResult = array("isCurlErr" => false, "isBanned" => false); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); if ($noWebpageUrl) { curl_setopt($ch, CURLOPT_NOBODY, true); curl_setopt($ch, CURLOPT_HEADER, true); } else { curl_setopt($ch, CURLOPT_HEADER, 0); } curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, $this->GetMainUserAgent()); // Set IP options $isProxy = !empty($ip['port']) || !empty($ip['proxy_user']) || !empty($ip['proxy_pass']); curl_setopt($ch, CURLOPT_REFERER, ''); if ($isProxy) { curl_setopt($ch, CURLOPT_PROXY, $ip['ip'] . ":" . $ip['port']); if (!empty($ip['proxy_user']) && !empty($ip['proxy_pass'])) { curl_setopt($ch, CURLOPT_PROXYUSERPWD, $ip['proxy_user'] . ":" . $ip['proxy_pass']); } if (Config::_ENABLE_TOR_PROXY) { curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); } curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, Config::_IP_CONNECT_TIMEOUT); curl_setopt($ch, CURLOPT_TIMEOUT, Config::_IP_REQUEST_TIMEOUT); } else { curl_setopt($ch, CURLOPT_INTERFACE, $ip['ip']); curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); } curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $output = curl_exec($ch); $ipReqResult['isCurlErr'] = curl_errno($ch) != 0; if (curl_errno($ch) == 0) { $this->_videoWebpage = (!$noWebpageUrl) ? $output : $this->_videoWebpage; if (!$noWebpageUrl && !empty($output)) { $ipReqResult['isBanned'] = $this->ReturnConfig('name') == "YouTube" && preg_match(YouTube::_CAPTCHA_PATTERN, $output) == 1; } $info = curl_getinfo($ch); //die(print_r($info)); $ipReqResult['isBanned'] = (!$ipReqResult['isBanned']) ? $info['http_code'] == '429' : $ipReqResult['isBanned']; } curl_close($ch); return $ipReqResult; } // Common Protected Methods protected function FileGetContents($url, $postData='', $reqHeaders=array()) { $converter = $this->GetConverter(); if ($converter->GetCurrentVidHost() == "YouTube") { $urlRoot = $this->ReturnConfig('url_root'); $urlRoot = preg_replace('/^(https?)/', "https", $urlRoot[0]); $this->_videoWebpageUrl = (preg_match('/^(' . preg_quote($urlRoot, "/") . ')/', $url) == 1) ? $url : ''; } $file_contents = ''; $tries = 0; do { $this->_headers = array(); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT, $this->GetMainUserAgent()); if (Config::_ENABLE_IP_ROTATION && in_array($converter->GetCurrentVidHost(), array("YouTube", "GoogleDrive", "TikTok"))) { if ($converter->GetOutgoingIP() == array() || $tries > 0) $converter->SetOutgoingIP(); if (!empty($this->_videoWebpageUrl) && !empty($this->_videoWebpage)) { return $this->_videoWebpage; } $currentIP = $converter->GetOutgoingIP(); $isProxy = !empty($currentIP['port']) || !empty($currentIP['proxy_user']) || !empty($currentIP['proxy_pass']); curl_setopt($ch, CURLOPT_REFERER, ''); if ($isProxy) { curl_setopt($ch, CURLOPT_PROXY, $currentIP['ip'] . ":" . $currentIP['port']); if (!empty($currentIP['proxy_user']) && !empty($currentIP['proxy_pass'])) { curl_setopt($ch, CURLOPT_PROXYUSERPWD, $currentIP['proxy_user'] . ":" . $currentIP['proxy_pass']); } if (Config::_ENABLE_TOR_PROXY) { curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); } curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, Config::_IP_CONNECT_TIMEOUT); curl_setopt($ch, CURLOPT_TIMEOUT, Config::_IP_REQUEST_TIMEOUT); } else { curl_setopt($ch, CURLOPT_INTERFACE, $currentIP['ip']); curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); } curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); } if (!empty($postData)) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); } if (!empty($reqHeaders)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $reqHeaders); } curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'AppendHttpHeader')); $file_contents = curl_exec($ch); $this->_isCurlError = curl_errno($ch) != 0; $curlInfo = curl_getinfo($ch); //print_r($curlInfo); if (curl_errno($ch) == 0) { if ($converter->GetCurrentVidHost() == "YouTube" && ($curlInfo['http_code'] == '302' || $curlInfo['http_code'] == '301')) { if (isset($curlInfo['redirect_url']) && !empty($curlInfo['redirect_url'])) { $file_contents = $this->FileGetContents($curlInfo['redirect_url']); } } } curl_close($ch); $tries++; } while (Config::_ENABLE_IP_ROTATION && in_array($converter->GetCurrentVidHost(), array("YouTube", "GoogleDrive", "TikTok")) && $tries < Config::_MAX_CURL_TRIES && ($this->_isCurlError || $curlInfo['http_code'] == '403' || $curlInfo['http_code'] == '429' || empty($file_contents) || preg_match(YouTube::_CAPTCHA_PATTERN, $file_contents) == 1)); return $file_contents; } protected function AppendHttpHeader($ch, $headr) { $this->_headers[] = $headr; return strlen($headr); } protected function ExtractCookies() { $cookies = ''; $cookieNames = array(); $headers = array_reverse($this->_headers); foreach ($headers as $headr) { $cookies .= (preg_match('/^(Set-Cookie:\s*(\w+)=([^;]+))/i', $headr, $matches) == 1 && !in_array($matches[2], $cookieNames)) ? $matches[2] . "=" . $matches[3] . ";" : ''; $cookieNames[] = $matches[2]; } return trim($cookies, ";"); } // Force child classes to define these methods abstract public function RetrieveVidInfo($vidUrl); abstract public function ExtractVidSourceUrls(); // Common Properties protected function GetConverter() { return $this->_converter; } public function GetMainUserAgent() { return $this->_mainUserAgent; } public function GetVideoWebpage() { return $this->_videoWebpage; } protected function GetStoreDir() { return dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'store' . DIRECTORY_SEPARATOR; } } ?> Hope i can get some help to solve this issue. Thank you kindly.
  16. Good day. I am new to php, did learn quit a few things with php, but now I am stuck. (don't hurt the newbie) 1. in phpmysql I have a table with one of the columns (LIVE) in it that I want to show a live price in. At the moment I the column is set as varchar(30) do not know if this is correct. In my html table I want to add 3 or more if/else in, so when I update my html it must show 0.03234523 (depending on the price) I do not want all the rows to show this information I am getting the info from a js file, but cannot get it to work. (I did add the script in so it see my sss.js file. Here is the full script of javascript (it is at the moment just for one, will add the other two later when we can fix this), and the php script from my php file. What am I dong wrong and how can I fixed it. let ws_binance = new WebSocket('wss://stream.binance.com:9443/ws'); let html_element_binance = document.getElementById('show_price_binance'); let last_price_binance = null; ws_binance.onopen = function () { ws_binance.send(JSON.stringify ({ 'method': 'SUBSCRIBE', 'params': ['shibusdt@trade'], 'id': 1 })) }; ws_binance.onmessage = function (event) { let current_price_binance = JSON.parse(event.data); let price_binance = parseFloat(current_price_binance.p).toFixed(8); html_element_binance.innerText = price_binance; if ((price_binance < last_price_binance) && (isNaN(price_binance) == false)) { html_element_binance.innerText = '↓' + price_binance; html_element_binance.style.color = 'red'; } else if ((price_binance > last_price_binance) && (isNaN(price_binance) == false)) { html_element_binance.innerText = '↑' + price_binance; html_element_binance.style.color = 'lime'; } else if ((price_binance == last_price_binance) && (isNaN(price_binance) == false)) { html_element_binance.innerText = price_binance; html_element_binance.style.color = 'purple'; } last_price_binance = price_binance; }; <td> <?php $checkSqlRow["CCOINGECKO_LIVE"] = strtolower($checkSqlRow["COINGECKO_LIVE"]); if($checkSqlRow["COINGECKO_LIVE"] == 'trx') { echo "id='show_price_binance'"; } ?> </td>
  17. Hi, I have pre-written code that produces a license key but I don’t like the format that the key is in and was wondering if I could get some help fixing it? This is the code @section('scripts') <script type="text/javascript"> function Createkey(length) { var result = ''; var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; var charactersLength = characters.length; for ( var i = 0; i < length; i++ ) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } $('#licenses-gen').click(function(){ var GetType = $('#type_of_key_id').find(":selected").text(); $('#licence').val(GetType.trim()+Createkey(18)); }); </script> @endsection the output is just a random string of 18 characters like: H3CJPE5JMS501FH52A though I want to get an output like: FSOWP-DHJEO-SKJ3D-2DF5R-3FG51 What can I change in the code to get the second output option?
  18. Hi guys! I've tried to insert data inside an input's value but the input goes like it is hidden, When I inspect the page it shows that there is no input inside my form. I've tried to move the code to the top of page but nothing is changed always a hidden input while it is not hidden at all as you can see below: <div class="mb-3"> <?php //Checking if submit button is clicked if (isset($_POST['submit'])) { //database cn $db = new PDO("mysql:host=localhost;dbname=centrify","root",""); $username = $_POST['user']; $stmt = $db->prepare("SELECT * FROM agencies_data WHERE agency_user = ".$username.""); $stmt->execute(); ?> <input class="form-control" type="text" name="oid" value="<?php while($item = $stmt->fetch()) { echo $item['agency_user']; } ?>"> <?php } ?> </div> I've tested a lot of placements but it doesnt work for me.
  19. Hello Coders, wanted to know if anybody could help to validate modal form based on the query below please? Appreciate your help if possible. Thank you so much! MODAL FORM FORM <div class="modal fade" id="exampleModal" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="staticBackdrop" aria-hidden="true"> > <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Add user</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <i aria-hidden="true" class="ki ki-close"></i> </button> </div> <div class="modal-body"> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" class="needs-validation" novalidate id="adduser"> <div class="form-row"> <div class="form-group col-md-6 mb-3"> <label for="inputState">Select a name</label><br> <select class="form-control select2 <?php echo (!empty($fullname_err)) ? 'is-invalid' : ''; ?>" id="kt_select2_1" name="fullname" required> <option value="" selected>Select a name</option> <?php require_once('./conn/inc.php'); $sql = mysqli_query($link,"SELECT * FROM members ORDER BY fullname ASC"); while($row=mysqli_fetch_array($sql)) { $mid = $row['mid']; $fullname = $row['fullname']; echo '<option value="'.$mid.'">'.$fullname.'</option>'; } ?> </select> <span class="invalid-feedback"><?php echo $fullname_err; ?></span> </div> <div class="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 mb-3"> <label for="username">Username</label> <input type="text" class="form-control <?php echo (!empty($uname_err)) ? 'is-invalid' : ''; ?>" placeholder="username" name="uname" required> <span class="invalid-feedback"><?php echo $uname_err; ?></span> </div> <div class="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 mb-3"> <label for="showpass">Password</label> <input type="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>" id="showpass" placeholder="Password" name="password" required> <span class="invalid-feedback"><?php echo $password_err; ?></span> </div> <div class="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 mb-3"> <label for="showpass2">Confirm Password</label> <input type="password" name="confirm_password" class="form-control <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>" id="showpass2" placeholder="Confirm password" required> <span class="invalid-feedback"><?php echo $confirm_password_err; ?></span> </div> </div> </div> <div class="modal-footer"> <div class="checkbox-inline mr-2"> <label class="checkbox"> <input type="checkbox" onclick="myFunction()" class="form-check-input" id="exampleCheck1"> <span></span> Show password </label> </div> <button type="reset" class="btn btn-secondary">Clear</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> </div> </div> VALIDATION QUERY <?php // Define variables and initialize with empty values $fullname = $uname = $password = $confirm_password = ""; $fullname_err = $uname_err = $password_err = $confirm_password_err = ""; // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ // Validate username if(empty(trim($_POST["uname"]))){ $uname_err = "Please enter a username."; } elseif(!preg_match('/^[a-zA-Z0-9_]+$/', trim($_POST["uname"]))){ $uname_err = "Username can only contain letters, numbers, and underscores."; } else{ // Prepare a select statement $sql = "SELECT id FROM users WHERE uname = ?"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "s", $param_username); // Set parameters $param_username = trim($_POST["uname"]); // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ /* store result */ mysqli_stmt_store_result($stmt); if(mysqli_stmt_num_rows($stmt) == 1){ $uname_err = "This username is already taken."; } else{ $uname = trim($_POST["uname"]); } } else{ echo "Oops! Something went wrong. Please try again later."; } // Close statement mysqli_stmt_close($stmt); } } // Validate username if(empty(trim($_POST["fullname"]))){ $fullname_err = "Please enter a fullname."; } else{ // Prepare a select statement $sql = "SELECT id FROM users WHERE fullname = ?"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "s", $param_fullname); // Set parameters $param_fullname = trim($_POST["fullname"]); // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ /* store result */ mysqli_stmt_store_result($stmt); if(mysqli_stmt_num_rows($stmt) == 1){ $fullname_err = "This names is already taken."; } else{ $fullname = trim($_POST["fullname"]); } } else{ echo "Oops! Something went wrong. Please try again later."; } // Close statement mysqli_stmt_close($stmt); } } // Validate password if(empty(trim($_POST["password"]))){ $password_err = "Please enter a password."; } elseif(strlen(trim($_POST["password"])) < 6){ $password_err = "Password must have atleast 6 characters."; } else{ $password = trim($_POST["password"]); } // Validate confirm password if(empty(trim($_POST["confirm_password"]))){ $confirm_password_err = "Please confirm password."; } else{ $confirm_password = trim($_POST["confirm_password"]); if(empty($password_err) && ($password != $confirm_password)){ $confirm_password_err = "Password did not match."; } } // Check input errors before inserting in database if(empty($fullname_err) && empty($uname_err) && empty($password_err) && empty($confirm_password_err)){ $fullname = mysqli_real_escape_string($link, $_REQUEST['fullname']); $uname = mysqli_real_escape_string($link, $_REQUEST['uname']); // Prepare an insert statement $sql = "INSERT INTO users (fullname, uname, password) VALUES (?, ?, ?)"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "sss", $param_fullname, $param_username, $param_password); // Set parameters $param_fullname = $fullname; $param_username = $uname; $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ // Redirect to login page header("location: users.php"); $_SESSION['status'] = "Record Successfuly Saved!"; } else{ echo "Oops! Something went wrong. Please try again later."; } // Close statement mysqli_stmt_close($stmt); } } // Close connection // mysqli_close($link); } ?> I have put javascript to validate form before submitting and this only works on client side ; It won't fetch data from database to compare. <script> // Example starter JavaScript for disabling form submissions if there are invalid fields (function() { 'use strict'; window.addEventListener('load', function() { // Fetch all the forms we want to apply custom Bootstrap validation styles to var forms = document.getElementsByClassName('needs-validation'); // Loop over them and prevent submission var validation = Array.prototype.filter.call(forms, function(form) { form.addEventListener('submit', function(event) { if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } form.classList.add('was-validated'); }, false); }); }, false); })(); </script>
  20. I'm getting the following error on a contact form I'm trying to implement: Fatal error: Uncaught Error: Undefined constant "secretcode" in /home/foxclo98/test.foxclone.com/contact.php:33 Stack trace: #0 {main} thrown in /home/foxclo98/test.foxclone.com/contact.php on line 33 Here's the full code of the contact form: <?php $errorlevel=error_reporting(); error_reporting($errorlevel & ~E_WARNING); //...code that generates notices error_reporting($errorlevel); // initialization session_start(); $email_contact = "help@foxclone.com"; $email_website = "webmaster@foxclone.com"; // definition of permitted types/subject/category. use to dynamically build the option list, // pre-selecting any existing choice, and used in the validation logic $permitted_types = ['Questions', 'Report Problem', 'Suggestion', 'Other', 'Website Problem']; $secretcode = ['nospam']; $post = []; // array to hold a trimmed working copy of the form data $errors = []; // array to hold user/validation errors // post method form processing if($_SERVER['REQUEST_METHOD'] == 'POST') { // trim all the data at once $post = array_map('trim',$_POST); // if any of the fields are arrays, use a recursive call-back function here instead of php's trim function // inputs: name, email, type/subject/category, message - all required // validate the inputs $errors = []; //Other validation stuff. if ($post['secretcode'] != 'nospam') { $errors[secretcode] = 'You did not enter the correct secret code.'; } if($post['name'] === '') { $errors['name'] = 'Name is required.'; } if($post['email'] === '') { $errors['email'] = 'Email is required.'; } else { // while it is true that the following email format validation will produce an error // for an empty value, you should specifically tell the visitor what is wrong with what // they submitted if (false === filter_var($post['email'], FILTER_VALIDATE_EMAIL)) { $errors['email'] = 'The Email Address you entered does not appear to be valid.'; } } if($post['type'] === '') { $errors['type'] = 'You must select a Type/Subject/Category.'; } else { // you will only see the following error due to a programming mistake or someone/something submitting their own values if(!in_array($post['type'],$permitted_types)) { $errors['type'] = 'The selected Type is invalid.'; // you would want to log the occurrence of this here... } } if($post['message'] === '') { $errors['message'] = 'Message is required.'; } else { if(strlen($post['message']) < 10) { $errors['message'] = 'The Message must be at least 10 characters.'; } } // if no errors, use the submitted data if(empty($errors)) { // apply htmlentities() to help prevent cross site scripting when viewing the received email in a browser $formcontent = htmlentities("From: {$post['name']}\r\nEmail: {$post['email']}\r\nSubject: {$post['type']}\r\nMessage: {$post['message']}", ENT_QUOTES); if ($post['type'] === "Website Problem") { $recipient=$email_website; } else { $recipient=$email_contact; } $email = $post['email']; // add $post['email'] as a Reply-to: header if desired, it is one, valid email address at this point $mailheader = "From: $email\r\n" ; $mailheader .= "Cc: $email\r\n"; if(!mail($recipient, $post['type'], $formcontent, $mailheader)) { // an error // setup the user error message $errors['mail'] = 'The email could not be sent, the site owner has been notified.'; // system error handling goes here... - datatime, get the last error message, include the mail parameter values... // at this point, all parameters are either an internal value, have been validated they they are just an expected // value/format, or have had htmlentities() applied. } // if no errors at this point, success if(empty($errors)) { $_SESSION['success_message'] = "Mail Sent. Thank you {$post['name']}, we will contact you shortly.."; die(header("Refresh:0")); } } } // html document starts here... ?> <?php // display any success message if(!empty($_SESSION['success_message'])) { // for demo purposes, just output it as a paragraph. add any markup/styling you want echo '<p>'; echo htmlentities($_SESSION['success_message'], ENT_QUOTES); echo " - <a href='index.php#home' style='color:#ff0099;'> Return Home</a>"; echo '</p>'; unset($_SESSION['success_message']); } ?> <?php // display any errors if(!empty($errors)) { // for demo purposes, just output them as a paragraph. add any markup/styling you want echo '<p>'; echo implode('<br>',$errors); echo '</p>'; } ?> <?php // (re)display the form here..., re-populating the fields with any existing values ?> <?php require_once("header.php");?> <style> input, select { width: 20rem; line-height:30px; border:2px solid #2f496e; padding: 0; margin: 0; height: 30px; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; font: 500 1rem sans-serif; background: #fff; } .input { text-indent: 3px; } </style> </head> <body> <?PHP require_once("navbar.php"); ?> <!--****************** * CONTACT * *******************--> <div class="head__h1"> Need help? Have a suggestion? Why not send us an email?</div> <div class="subtext"> You'll receive a copy of your inquiry for your records </div> <div class ="download"> <div class="cont__row" style="background-color: #d9b44a;"> <div class="cont__column"> <form method="POST"> <label>Secret Code:</label><br> <input type="text" name="secretcode" id="secretcode" placeholder="Type nospam here"> <br> <br> <label>Name</label><br> <input type="text" name="name"><br> <br> <label>Email</label><br> <input type="email" name="email"><br> <br> <label>Select a Category</label> <br> <select name="type" id="category" size="1"> <option value=''> </option> <option value='Questions'>Questions</option> <option value="Report Problem">Report Problem</option> <option value='Suggestion'>Suggestion</option> <option value='Other'>Other</option> <option value="Website Problem"> Website Problem</option> </select> </div> <div class="cont__column"> <label>Message</label><br> <textarea name="message" rows="10" cols="50" style="font: 500 1rem sans-serif"></textarea><br> <br> <div class="button"> <input type="image" id="myimage" src="images/email1.jpg" style="height:40px; width:160px;"/> </form> </div> </div> </div> </div> <?PHP require_once("footer.php"); ?> I'd appreciate ssome help on this.
  21. I have to insert $z into DB. And $z is consisted from: $x = 5; $y = "123hg5"; With $z = $x.$y; I get only 5. And I need it to be 5123hg5.
  22. Hello Coding Masters, Thank you for reading my post. I need your help if if it's possible that Database table value will automatically update the value when time expires? Sample, If now time is is between ENTRYTime and CLOSE Time, table value will automatically update if time set expires? Enabled value is = 0 on my table Disabled value is = 0 on my table. But I have someone close to me suggested if its possible to set these automatically? Thank you so much for your feedback.
  23. Hello There, Anyone wants to help me how to achive this thing on PHP? I have zero knowledge on Pibot table for PHP Mysqli and minimal knowledge on programming. Here's the link for output And below is the Table Attendance: -- phpMyAdmin SQL Dump -- version 5.2.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jun 01, 2022 at 10:29 AM -- Server version: 10.4.24-MariaDB -- PHP Version: 8.1.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `mcgibn` -- -- -------------------------------------------------------- -- -- Table structure for table `attendance` -- CREATE TABLE `attendance` ( `atid` int(11) NOT NULL, `memid` int(11) NOT NULL, `serid` int(11) NOT NULL, `calid` int(11) NOT NULL, `entrydate` timestamp NOT NULL DEFAULT current_timestamp(), `month` varchar(30) CHARACTER SET latin1 NOT NULL, `year` varchar(5) DEFAULT NULL, `createdat` timestamp NOT NULL DEFAULT current_timestamp(), `updatedat` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `viewfrom` int(11) NOT NULL, `astatus` int(11) NOT NULL, `stype` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `attendance` -- INSERT INTO `attendance` (`atid`, `memid`, `serid`, `calid`, `entrydate`, `month`, `year`, `createdat`, `updatedat`, `viewfrom`, `astatus`, `stype`) VALUES (32, 37, 1, 1, '2022-05-31 12:55:28', 'May', '2022', '2022-05-31 12:55:28', '2022-05-31 12:55:28', 0, 1, 2), (33, 37, 2, 1, '2022-05-31 12:55:36', 'May', '2022', '2022-05-31 12:55:36', '2022-05-31 12:55:36', 0, 1, 1), (34, 37, 3, 1, '2022-05-31 12:55:43', 'May', '2022', '2022-05-31 12:55:43', '2022-06-01 03:28:55', 0, 1, 1), (35, 37, 1, 0, '2022-05-31 12:56:15', 'Jun', '2022', '2022-05-31 12:56:15', '2022-06-01 01:17:35', 0, 1, 2), (36, 37, 2, 1, '2022-05-31 12:56:25', 'Jun', '2022', '2022-05-31 12:56:25', '2022-06-01 01:17:35', 0, 1, 1), (37, 37, 3, 1, '2022-05-31 12:56:40', 'Jun', '2022', '2022-05-31 12:56:40', '2022-06-01 01:17:35', 0, 1, 1), (38, 37, 1, 1, '2022-05-31 12:57:24', 'May', '2023', '2022-05-31 12:57:24', '2022-05-31 12:57:24', 0, 1, 2), (39, 37, 2, 1, '2022-05-31 12:57:37', 'May', '2023', '2022-05-31 12:57:37', '2022-05-31 12:57:37', 0, 1, 1), (40, 37, 3, 1, '2022-05-31 12:57:46', 'May', '2023', '2022-05-31 12:57:46', '2022-05-31 12:57:46', 0, 1, 1), (41, 37, 1, 1, '2022-05-31 12:57:57', 'Jun', '2023', '2022-05-31 12:57:57', '2022-06-01 01:17:35', 0, 1, 2), (42, 37, 2, 1, '2022-05-31 12:58:08', 'Jun', '2023', '2022-05-31 12:58:08', '2022-06-01 01:17:35', 0, 1, 1), (43, 37, 3, 1, '2022-05-31 12:58:18', 'Jun', '2023', '2022-05-31 12:58:18', '2022-06-01 01:12:40', 0, 1, 1), (44, 49, 1, 1, '2022-05-31 12:58:32', 'May', '2022', '2022-05-31 12:58:32', '2022-05-31 12:58:32', 0, 1, 2), (45, 49, 2, 1, '2022-05-31 12:58:40', 'May', '2022', '2022-05-31 12:58:40', '2022-05-31 12:58:40', 0, 1, 1), (47, 49, 1, 1, '2022-05-31 12:59:01', 'Jun', '2022', '2022-05-31 12:59:01', '0000-00-00 00:00:00', 0, 1, 2), (48, 49, 2, 1, '2022-05-31 12:59:14', 'Jun', '2022', '2022-05-31 12:59:14', '2022-06-01 01:12:40', 0, 1, 1), (49, 49, 3, 1, '2022-05-31 12:59:31', 'Jun', '2022', '2022-05-31 12:59:31', '2022-06-01 01:12:40', 0, 1, 1), (50, 49, 1, 1, '2022-05-31 12:59:41', 'May', '2023', '2022-05-31 12:59:41', '2022-05-31 12:59:41', 0, 1, 2), (51, 49, 2, 1, '2022-05-31 12:59:49', 'May', '2023', '2022-05-31 12:59:49', '2022-05-31 12:59:49', 0, 1, 1), (52, 49, 3, 1, '2022-05-31 13:00:05', 'May', '2023', '2022-05-31 13:00:05', '2022-05-31 13:00:05', 0, 1, 1), (53, 49, 1, 1, '2022-05-31 13:00:21', 'Jun', '2023', '2022-05-31 13:00:21', '2022-06-01 01:12:40', 0, 1, 2), (54, 49, 2, 1, '2022-05-31 13:00:32', 'Jun', '2023', '2022-05-31 13:00:32', '2022-06-01 01:12:40', 0, 1, 1), (55, 49, 3, 1, '2022-05-31 13:00:43', 'Jun', '2023', '2022-05-31 13:00:43', '2022-06-01 01:12:40', 0, 1, 1), (56, 88, 1, 1, '2022-05-31 13:01:25', 'May', '2022', '2022-05-31 13:01:25', '2022-05-31 13:01:25', 0, 1, 2), (57, 88, 2, 1, '2022-05-31 13:01:30', 'May', '2022', '2022-05-31 13:01:30', '2022-05-31 13:01:30', 0, 1, 1), (58, 88, 3, 1, '2022-05-31 13:01:37', 'May', '2022', '2022-05-31 13:01:37', '2022-05-31 13:01:37', 0, 1, 1), (59, 88, 1, 1, '2022-05-31 13:01:45', 'Jun', '2022', '2022-05-31 13:01:45', '2022-06-01 01:27:00', 0, 1, 2), (60, 88, 2, 1, '2022-05-31 13:01:52', 'Jun', '2022', '2022-05-31 13:01:52', '2022-06-01 01:12:40', 0, 1, 1), (62, 88, 1, 1, '2022-05-31 13:02:37', 'Jun', '2023', '2022-05-31 13:02:37', '2022-06-01 01:27:07', 0, 1, 2), (63, 88, 2, 1, '2022-05-31 13:02:54', 'Jun', '2023', '2022-05-31 13:02:54', '2022-06-01 01:12:40', 0, 1, 1), (64, 88, 3, 1, '2022-05-31 13:03:04', 'Jun', '2023', '2022-05-31 13:03:04', '2022-06-01 01:27:10', 0, 1, 1), (65, 88, 1, 1, '2022-05-31 13:03:14', 'May', '2023', '2022-05-31 13:03:14', '2022-05-31 13:03:14', 0, 1, 2), (66, 88, 2, 1, '2022-05-31 13:03:22', 'May', '2023', '2022-05-31 13:03:22', '2022-05-31 13:03:22', 0, 1, 1), (67, 88, 3, 1, '2022-05-31 13:03:31', 'May', '2023', '2022-05-31 13:03:31', '2022-05-31 13:03:31', 0, 1, 1), (68, 89, 1, 1, '2022-05-31 13:04:21', 'May', '2022', '2022-05-31 13:04:21', '2022-05-31 13:04:21', 0, 1, 2), (69, 89, 2, 1, '2022-05-31 13:04:34', 'May', '2022', '2022-05-31 13:04:34', '2022-05-31 13:04:34', 0, 1, 1), (70, 89, 3, 1, '2022-05-31 13:04:40', 'May', '2022', '2022-05-31 13:04:40', '2022-05-31 13:04:40', 0, 1, 1), (71, 89, 1, 1, '2022-05-31 13:04:49', 'Jun', '2022', '2022-05-31 13:04:49', '2022-06-01 01:12:40', 0, 1, 2), (72, 89, 2, 1, '2022-05-31 13:04:56', 'Jun', '2022', '2022-05-31 13:04:56', '2022-06-01 01:12:40', 0, 1, 1), (73, 89, 3, 1, '2022-05-31 13:05:14', 'Jun', '2022', '2022-05-31 13:05:14', '2022-06-01 01:10:41', 0, 1, 1), (74, 89, 1, 1, '2022-05-31 13:05:24', 'May', '2023', '2022-05-31 13:05:24', '2022-05-31 13:05:24', 0, 1, 2), (75, 89, 2, 1, '2022-05-31 13:05:31', 'May', '2023', '2022-05-31 13:05:31', '2022-05-31 13:05:31', 0, 1, 1), (76, 89, 3, 1, '2022-05-31 13:05:41', 'May', '2023', '2022-05-31 13:05:41', '2022-05-31 13:05:41', 0, 1, 1), (77, 89, 1, 1, '2022-05-31 13:05:51', 'Jun', '2023', '2022-05-31 13:05:51', '2022-06-01 01:12:40', 0, 1, 2), (78, 89, 2, 1, '2022-05-31 13:05:59', 'Jun', '2023', '2022-05-31 13:05:59', '0000-00-00 00:00:00', 0, 1, 1), (79, 89, 3, 1, '2022-05-31 13:06:09', 'Jun', '2023', '2022-05-31 13:06:09', '2022-06-01 01:27:12', 0, 1, 1), (80, 84, 1, 1, '2022-05-31 13:07:19', 'May', '2022', '2022-05-31 13:07:19', '2022-06-01 03:40:25', 0, 1, 2), (81, 84, 2, 1, '2022-05-31 13:07:24', 'May', '2022', '2022-05-31 13:07:24', '2022-05-31 13:07:24', 0, 1, 1), (82, 84, 3, 1, '2022-05-31 13:07:31', 'May', '2022', '2022-05-31 13:07:31', '2022-06-01 03:42:52', 0, 1, 1), (83, 84, 1, 1, '2022-05-31 13:07:38', 'Jun', '2022', '2022-05-31 13:07:38', '2022-06-01 01:12:40', 0, 1, 2), (84, 84, 2, 1, '2022-05-31 13:07:45', 'Jun', '2022', '2022-05-31 13:07:45', '2022-06-01 01:27:14', 0, 1, 1), (85, 84, 3, 1, '2022-05-31 13:07:53', 'Jun', '2022', '2022-05-31 13:07:53', '2022-06-01 01:27:16', 0, 1, 1), (86, 84, 1, 1, '2022-05-31 13:08:12', 'May', '2023', '2022-05-31 13:08:12', '2022-05-31 13:08:12', 0, 1, 2), (87, 84, 2, 1, '2022-05-31 13:08:23', 'May', '2023', '2022-05-31 13:08:23', '2022-05-31 13:08:23', 0, 1, 1), (88, 84, 3, 1, '2022-05-31 13:08:30', 'May', '2023', '2022-05-31 13:08:30', '2022-05-31 13:08:30', 0, 1, 1), (89, 84, 1, 1, '2022-05-31 13:08:44', 'Jun', '2023', '2022-05-31 13:08:44', '2022-06-01 01:27:20', 0, 1, 2), (90, 84, 2, 1, '2022-05-31 13:08:58', 'Jun', '2023', '2022-05-31 13:08:58', '2022-06-01 01:27:22', 0, 1, 1), (91, 84, 3, 1, '2022-05-31 13:09:06', 'Jun', '2023', '2022-05-31 13:09:06', '2022-06-01 01:27:26', 0, 1, 1), (92, 121, 1, 1, '2022-05-31 13:09:59', 'May', '2022', '2022-05-31 13:09:59', '2022-05-31 13:09:59', 0, 1, 2), (93, 121, 2, 1, '2022-05-31 13:10:06', 'May', '2022', '2022-05-31 13:10:06', '2022-05-31 13:10:06', 0, 1, 1), (94, 121, 3, 1, '2022-05-31 13:10:13', 'May', '2022', '2022-05-31 13:10:13', '2022-05-31 13:10:13', 0, 1, 1), (95, 121, 1, 1, '2022-05-31 13:10:20', 'Jun', '2022', '2022-05-31 13:10:20', '2022-06-01 01:27:27', 0, 1, 2), (96, 121, 2, 1, '2022-05-31 13:10:29', 'Jun', '2022', '2022-05-31 13:10:29', '2022-06-01 01:27:29', 0, 1, 1), (97, 121, 3, 1, '2022-05-31 13:10:38', 'Jun', '2022', '2022-05-31 13:10:38', '2022-06-01 01:27:30', 0, 1, 1), (98, 121, 1, 1, '2022-05-31 13:10:50', 'May', '2023', '2022-05-31 13:10:50', '2022-05-31 13:10:50', 0, 1, 2), (99, 121, 2, 1, '2022-05-31 13:10:57', 'May', '2023', '2022-05-31 13:10:57', '2022-05-31 13:10:57', 0, 1, 1), (100, 121, 3, 1, '2022-05-31 13:11:11', 'May', '2023', '2022-05-31 13:11:11', '2022-05-31 13:11:11', 0, 1, 1), (101, 107, 1, 1, '2022-05-31 13:11:34', 'May', '2022', '2022-05-31 13:11:34', '2022-05-31 13:11:34', 0, 1, 2), (102, 107, 2, 1, '2022-05-31 13:11:39', 'May', '2022', '2022-05-31 13:11:39', '2022-05-31 13:11:39', 0, 1, 1), (103, 107, 3, 1, '2022-05-31 13:11:44', 'May', '2022', '2022-05-31 13:11:44', '2022-05-31 13:11:44', 0, 1, 1), (104, 107, 1, 1, '2022-05-31 13:11:51', 'Jun', '2022', '2022-05-31 13:11:51', '2022-06-01 01:10:41', 0, 1, 2), (105, 107, 2, 1, '2022-05-31 13:12:05', 'Jun', '2022', '2022-05-31 13:12:05', '2022-06-01 01:27:32', 0, 1, 1), (106, 107, 3, 1, '2022-05-31 13:12:14', 'Jun', '2022', '2022-05-31 13:12:14', '2022-06-01 07:57:46', 0, 1, 1), (107, 107, 1, 1, '2022-05-31 13:12:28', 'May', '2023', '2022-05-31 13:12:28', '2022-05-31 13:12:28', 0, 1, 2), (108, 107, 2, 1, '2022-05-31 13:12:37', 'May', '2023', '2022-05-31 13:12:37', '2022-05-31 13:12:37', 0, 1, 1), (109, 107, 3, 1, '2022-05-31 13:12:45', 'May', '2023', '2022-05-31 13:12:45', '2022-05-31 13:12:45', 0, 1, 1), (110, 107, 1, 1, '2022-05-31 13:12:56', 'Jun', '2023', '2022-05-31 13:12:56', '2022-06-01 01:27:36', 0, 1, 2), (111, 107, 2, 1, '2022-05-31 13:13:05', 'Jun', '2023', '2022-05-31 13:13:05', '2022-06-01 01:27:38', 0, 1, 1), (112, 107, 3, 1, '2022-05-31 13:17:28', 'Jun', '2023', '2022-05-31 13:17:28', '2022-06-01 01:27:40', 0, 1, 1), (113, 113, 1, 1, '2022-05-31 13:18:57', 'May', '2022', '2022-05-31 13:18:57', '2022-05-31 13:18:57', 0, 1, 1), (114, 113, 2, 1, '2022-05-31 13:19:04', 'May', '2022', '2022-05-31 13:19:04', '2022-05-31 13:19:04', 0, 1, 1), (115, 113, 3, 1, '2022-05-31 13:19:10', 'May', '2022', '2022-05-31 13:19:10', '2022-05-31 13:19:10', 0, 1, 1), (116, 113, 1, 1, '2022-05-31 13:19:18', 'Jun', '2022', '2022-05-31 13:19:18', '2022-06-01 01:10:41', 0, 1, 1), (117, 113, 2, 1, '2022-05-31 13:19:24', 'Jun', '2022', '2022-05-31 13:19:24', '2022-06-01 01:27:41', 0, 1, 1), (118, 113, 3, 1, '2022-05-31 13:19:31', 'Jun', '2022', '2022-05-31 13:19:31', '2022-06-01 07:57:43', 0, 1, 1), (119, 113, 1, 1, '2022-05-31 13:19:41', 'May', '2023', '2022-05-31 13:19:41', '2022-05-31 13:19:41', 0, 1, 1), (120, 113, 2, 1, '2022-05-31 13:19:48', 'May', '2023', '2022-05-31 13:19:48', '2022-05-31 13:19:48', 0, 1, 1), (121, 113, 3, 1, '2022-05-31 13:19:54', 'May', '2023', '2022-05-31 13:19:54', '2022-05-31 13:19:54', 0, 1, 1), (122, 113, 1, 1, '2022-05-31 13:20:04', 'Jun', '2023', '2022-05-31 13:20:04', '2022-06-01 01:27:45', 0, 1, 1), (123, 113, 2, 1, '2022-05-31 13:20:13', 'Jun', '2023', '2022-05-31 13:20:13', '2022-06-01 01:27:49', 0, 1, 1), (124, 113, 3, 1, '2022-05-31 13:20:22', 'Jun', '2023', '2022-05-31 13:20:22', '2022-06-01 01:27:53', 0, 1, 1), (125, 119, 1, 1, '2022-05-31 13:21:12', 'May', '2022', '2022-05-31 13:21:12', '2022-05-31 13:21:12', 0, 1, 1), (126, 119, 2, 1, '2022-05-31 13:21:18', 'May', '2022', '2022-05-31 13:21:18', '2022-05-31 13:21:18', 0, 1, 1), (127, 119, 3, 1, '2022-05-31 13:21:29', 'May', '2022', '2022-05-31 13:21:29', '2022-05-31 13:21:29', 0, 1, 1), (128, 119, 1, 1, '2022-05-31 13:21:45', 'Jun', '2022', '2022-05-31 13:21:45', '2022-06-01 01:27:54', 0, 1, 1), (129, 119, 2, 1, '2022-05-31 13:21:53', 'Jun', '2022', '2022-05-31 13:21:53', '2022-06-01 01:27:56', 0, 1, 1), (130, 119, 3, 1, '2022-05-31 13:22:16', 'Jun', '2022', '2022-05-31 13:22:16', '2022-06-01 01:28:00', 0, 1, 1), (131, 119, 1, 1, '2022-05-31 13:22:24', 'May', '2023', '2022-05-31 13:22:24', '2022-05-31 13:22:24', 0, 1, 1), (132, 119, 2, 1, '2022-05-31 13:22:30', 'May', '2023', '2022-05-31 13:22:30', '2022-05-31 13:22:30', 0, 1, 1), (133, 119, 3, 1, '2022-05-31 13:22:36', 'May', '2023', '2022-05-31 13:22:36', '2022-05-31 13:22:36', 0, 1, 1), (134, 119, 1, 1, '2022-05-31 13:22:45', 'Jun', '2023', '2022-05-31 13:22:45', '2022-06-01 01:28:03', 0, 1, 1), (135, 119, 2, 1, '2022-05-31 13:22:53', 'Jun', '2023', '2022-05-31 13:22:53', '2022-06-01 01:28:04', 0, 1, 1), (136, 119, 3, 1, '2022-05-31 13:23:10', 'Jun', '2023', '2022-05-31 13:23:10', '2022-06-01 01:28:08', 0, 1, 1), (137, 13, 1, 1, '2022-05-31 13:40:26', 'May', '2022', '2022-05-31 13:40:26', '2022-05-31 13:40:26', 0, 1, 1), (138, 13, 2, 1, '2022-05-31 13:40:31', 'May', '2022', '2022-05-31 13:40:31', '2022-05-31 13:40:31', 0, 1, 1), (139, 13, 3, 1, '2022-05-31 13:40:36', 'May', '2022', '2022-05-31 13:40:36', '2022-05-31 13:40:36', 0, 1, 1), (140, 13, 1, 1, '2022-05-31 13:40:42', 'Jun', '2022', '2022-05-31 13:40:42', '2022-06-01 01:28:10', 0, 1, 1), (141, 13, 2, 1, '2022-05-31 13:40:53', 'Jun', '2022', '2022-05-31 13:40:53', '2022-06-01 01:28:11', 0, 1, 1), (142, 13, 3, 1, '2022-05-31 13:41:11', 'Jun', '2022', '2022-05-31 13:41:11', '2022-06-01 03:41:46', 0, 1, 1); -- -- Indexes for dumped tables -- -- -- Indexes for table `attendance` -- ALTER TABLE `attendance` ADD PRIMARY KEY (`atid`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `attendance` -- ALTER TABLE `attendance` MODIFY `atid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=143; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; I followed this code below and it has different results and can't really do it myself, <?php if(isset($_POST['search'])) { $search = $_POST['search'] ?? ''; $year = $_POST['year'] ?? ''; $month = $_POST['month'] ?? ''; $sql = "SELECT DISTINCT entrydate FROM attendance ORDER BY entrydate "; $res = $link->query($sql); // mysqli query while ($row = $res->fetch_row()) { $dates[] = $row[0]; } /*********************************** * Table headings * ************************************/ $emptyRow = array_fill_keys($dates,''); // format dates foreach ($dates as $k=>$v) { $dates[$k] = date('d-M', strtotime($v)); } $heads = "<table class='table table-stripped table-bordered'>\n"; $heads .= "<tr><th>Name</th><th>" . join('</th><th>', $dates) . "</th></tr>\n"; /*********************************** * Main data * ************************************/ $sql = "SELECT entrydate, memid, astatus FROM attendance ORDER BY memid"; $res = $link->query($sql); $curname=''; $tdata = ''; while (list($d, $sn, $s) = $res->fetch_row()) { if ($curname != $sn) { if ($curname) { $tdata .= "<tr><td>$curname</td><td>" . join('</td><td>', $rowdata). "</td></tr>\n"; } $rowdata = $emptyRow; $curname = $sn; } $rowdata[$d] = $s; } $tdata .= "<tr><td>$curname</td><td>" . join('</td><td>', $rowdata). "</td></tr>\n"; $tdata .= "</table\n"; } ?> <?php echo $heads; echo $tdata; ?> Notes: memid = Member name serid = Services like (PM, PBB, WS) calid = 1st Week, 2nd Week and so-on. entrydate = TimeIn date. Hoping that there are someone who's able to help a newbie like me. Thank you and appreciate that.
  24. I am trying to develop an PHP MySQL database application where edit details is not working.I am new to PHP and doing this with the help of various web resources such as youtube videos, tutorials, similar programs etc .I am able to fetch the data from the database, but when it comes to edit, the data remains the same even after changing.Can anyone suggest the solution of this problem. manage-profile.php <?php session_start(); require('connection.php'); //If your session isn't valid, it returns you to the login screen for protection if(empty($_SESSION['sl_no'])){ header("location:access-denied.php"); } //retrive student details from the student table $result=mysqli_query($con, "SELECT * FROM student WHERE sl_no = '$_SESSION[sl_no]'"); if (mysqli_num_rows($result)<1){ $result = null; } $row = mysqli_fetch_array($result); if($row) { // get data from db $stdId = $row['sl_no']; $stdRoll = $row['roll_no']; $stdName = $row['name']; $stdClass = $row['class']; $stdSex= $row['sex']; } ?> <?php // updating sql query if (isset($_POST['update'])){ $myId = addslashes( $_GET[$id]); $myRoll = addslashes( $_POST['roll_no'] ); $myName = addslashes( $_POST['name'] ); $myClass = addslashes( $_POST['class'] ); $myGender = $_POST['sex']; $sql = mysqli_query($con,"UPDATE student SET roll_no='$myRoll', name='$myName', class='$myClass', sex='$myGender' WHERE sl_no = '$myId'" ); // redirect back to profile header("Location: manage-profile.php"); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Student Profile Management</title> <link href="css/student_styles.css" rel="stylesheet" type="text/css" /> <script language="JavaScript" src="js/user.js"> </script> </head> <body bgcolor="#e6e6e6"> <center><b><font color = "black" size="6">Online Voting System</font></b></center><br><br> <div id="page"> <div id="header"> <h2>Manage Profile</h2> <a href="student.php">Home</a> | <a href="vote.php">Current Polls</a> | <a href="manage-profile.php">Manage My Profile</a> | <a href="changepassword.php">Change Password</a>| <a href="logout.php">Logout</a> </div> <div id="container"> <table border="0" width="620" align="center"> <CAPTION><h3>Update Profile</h3></CAPTION> <form action="manage-profile.php?$id=<?php echo $_SESSION['sl_no']; ?>" method="post" onsubmit="return updateProfile(this)"> <table align="center"> <tr><td>Roll Number:</td><td><input type="text" style="background-color:#e8daef; font-weight:regular;" name="roll_no" maxlength="50" value="<?php echo $row["roll_no"]; ?>"></td></tr> <tr><td>Name:</td><td><input type="text" style="background-color:#e8daef; font-weight:regular;" name="Name" maxlength="30" value="<?php echo $row["name"]; ?>"></td></tr> <tr><td>Class:</td><td><select name='sclass' style='background-color:#e8daef; font-weight:regular;' maxlength='10' id='class' required='true'> <option value='HS-1st Year' <?php if($row["class"]=='HS-1st Year') { echo "selected"; } ?> >HS-1st Year</option> <option value='HS-2nd Year' <?php if($row["class"]=='HS-2nd Year') { echo "selected"; } ?> >HS-2nd Year</option> <option value='BA-1st Sem' <?php if($row["class"]=='BA-1st Sem') { echo "selected"; } ?> >BA-1st Sem</option> <option value='BA-3rd Sem' <?php if($row["class"]=='BA-3rd Sem') { echo "selected"; } ?> >BA-3rd Sem</option> <option value='BA-5th Sem' <?php if($row["class"]=='BA-5th Sem') { echo "selected"; } ?> >BA-5th Sem</option> <option value='BCom-1st Sem' <?php if($row["class"]=='BCom-1st Sem') { echo "selected"; } ?> >BCom-1st Sem</option> <option value='BCom-3rd Sem' <?php if($row["class"]=='BCom-3rd Sem') { echo "selected"; } ?> >BCom-3rd Sem</option> <option value='BCom-5th Sem' <?php if($row["class"]=='BCom-5th Sem') { echo "selected"; } ?> >BCom-5th Sem</option> </select> </td></tr> <tr><td>Sex:</td><td> <input type='radio' style='background-color:#e8daef; font-weight:regular;' name='gender' id='male' value='Male' <?php if($row["sex"]=='Male') { echo "checked"; } ?> >Male<br> <input type='radio' style='background-color:#e8daef; font-weight:regular;' name='gender' id='female' value='Female' <?php if($row["sex"]=='Female') { echo "checked"; } ?> >Female<br></td></tr> <tr><td>&nbsp;</td></tr><tr><td><input type="submit" name="update" value="Update Profile"></td></tr> </table> </form> </div> <div id="footer"> <div class="bottom_addr">Student Union Election,Anonymous College</div> </div> </body> </html>
  25. I want to scrape a website content. here is the example html source code of that site. <div class="entry-content"> <h2>hi tags?</h2> <ul> <li>some text</li> <li>sometext</li> <li>sometext</li> <li>sometext</li> </ul> <h2>hi tags2 ?</h2> <ul> <li>some text</li> <li>sometext</li> <li>To ometext</li> <li>Theometext</li> </ul> </div> I want to extract data of <li> tags from first <ul> html code. Here I've tried. include('../simple_html_dom.php'); // get DOM from URL or file //$html = check above html code $articles = $html->find('div[class="entry-content"]') ? $html->find('div[class="entry-content"]') : []; foreach($articles as $article) { $items = $article->find('ul',0) ? $article->find('ul',0) : false; if($items !==false){ $lis = $item->find('li') ? $item->find('li') : []; foreach($lis as $b){ $mcpcons .= $b->plaintext; } } } Help me by giving the correct info how can I do that?
×
×
  • 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.