Search the Community
Showing results for tags 'php'.
-
Hi guys, I have this issue. It works fine in another piece of php code as in where I ban a user, it will show sweetalert to confirm and when I click unban this user, it will ask me in a nice sweetalert if I am sure. When I click Yes, the user ban gets lifted and then disaster strikes. It shows a normal js alert with html code inside. Here is the code that is used to lift the ban: <?php include_once('config.php'); // Function to unban a user function unbanUser($userId) { global $conn; // Prepare the SQL statement securely $stmt = $conn->prepare("UPDATE users SET status = ? WHERE user_id = ?"); $status = 'Active'; $stmt->bind_param("si", $status, $userId); // Execute the statement and handle the result if ($stmt->execute()) { echo '<script>Swal.fire("Success", "User has been unbanned.", "success");</script>'; } else { echo '<script>Swal.fire("Error", "Error removing user ban: ' . htmlspecialchars($stmt->error) . '", "error");</script>'; } $stmt->close(); } // Check if the request is made via POST and validate user input if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['userId'])) { $userId = filter_input(INPUT_POST, 'userId', FILTER_VALIDATE_INT); if ($userId !== false) { unbanUser($userId); } else { echo '<script>Swal.fire("Invalid Input", "Invalid user ID.", "warning");</script>'; } } ?> Just confirming, I do have Sweetalert script included in the header (because it needs to be before any execution). <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> If anyone can work this out I would appreciate it. Thank you
-
Hello folks, I am trying to create a script that will check the current domain, compare it with an array of domains that are stored externally in domains.php. If we have a match, great. If not, show an error. I am using CURL because of the vulnerabilities used using allow_url_include() so don't want to use that. Here is domains.php <?php // domains.php // Prevent direct access if (basename($_SERVER['PHP_SELF']) === basename(__FILE__)) { die('Access denied.'); } // Array of allowed domain names $domains_content = [ 'test1.com', 'test.com', 'mywebsite.org' ]; ?> Here is the function for checking: // This script checks if the current domain is in the allowed domains list. // Function to fetch the external PHP file using CURL function fetchDomains($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); if (curl_errno($ch)) { throw new Exception('CURL Error: ' . curl_error($ch)); } curl_close($ch); return $response; } try { // URL of the external PHP file $url = 'https://www.domain/domains.php'; // Replace with the actual URL // Fetch the domains $domains_content = fetchDomains($url); // Evaluate the fetched content to get the array eval('?>' . $domains_content); // Get the current domain $current_domain = $_SERVER['HTTP_HOST']; // Check if the current domain is in the allowed domains if (!in_array($current_domain, $domains_content)) { throw new Exception('Error: The current domain "' . $current_domain . '" is not allowed.'); } echo 'Domain check passed. Current domain: ' . $current_domain; } catch (Exception $e) { // Handle exceptions and display error message echo 'An error occurred: ' . $e->getMessage(); } I haven't included the actual domain I am checking for privacy reasons but you get the drift. Here is the error I am getting: [24-Oct-2024 00:04:58 Australia/Melbourne] PHP Warning: in_array() expects parameter 2 to be array, string given in includes/header.php on line 85 Here is that line: if (!in_array($current_domain, $domains_content)) { throw new Exception('Error: The current domain "' . $current_domain . '" is not allowed.'); } If anyone can help resolve this I would appreciate it. The domain the script is hosted on is actually listed in the array.
-
Hi guys, I have the following logout code, which works just fine, as in it logs the user out and kills the session etc. However, there is one part that is not working and that is updating the database to change the is_logged_in to set to 0 rather than 1, which is set upon login. <?php session_start(); // Start the session // Include database connection require_once('includes/config.php'); // Check if user is logged in if (!empty($_SESSION['user_id'])) { logoutUser($conn, $_SESSION['user_id']); } else { redirectToLogin(); } // Close the database connection $conn->close(); /** * Logs out the user by updating their login status and destroying the session. * * @param mysqli $conn The database connection. * @param int $user_id The ID of the user to log out. */ function logoutUser($conn, $user_id) { // Prepare statement to update user login status $stmt = $conn->prepare("UPDATE users SET is_logged_in = ? WHERE user_id = ?"); $is_logged_in = '0'; // Set user status to logged out $stmt->bind_param("si", $is_logged_in, $user_id); // Execute the statement if ($stmt->execute()) { // Destroy the session session_unset(); session_destroy(); redirectToLogin(); } else { echo "Error updating user status: " . $stmt->error; } // Close the statement $stmt->close(); } /** * Redirects the user to the login page. */ function redirectToLogin() { header("Location: login.php"); exit(); } ?> If anyone can help that would be great. Thanks
- 10 replies
-
- php
- prepared statements
-
(and 2 more)
Tagged with:
-
Hi. I've been thrown in the deep end with a community shed website when the person who knows HTML bailed out I have very little knowledge of writing forms - none actually. I've done my best at writing (plagarising) an application form with no success. Can someone give me a heads up where I've gone wrong? This is the application HTML: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title>Application</title> <meta content="Alistair" name="author"> <style> body { background-color:rgb(102, 255, 255); } ul { list-style-type: none; display: flex; margin: 70; padding: 60; overflow: hidden; spacing: 120; # background-color:rgb(102, 255, 255); } li { float: left; } li { margin-right: 110px; } li a, .dropbtn { display: inline-block; color: black; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover, .dropdown:hover .dropbtn { background-color: grey; } li.dropdown { display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; text-align: left; } .dropdown-content a:hover {background-color: #f1f1f1;} .dropdown:hover .dropdown-content { display: block; } </style> </head> <body style="margin-left: 0px; width: 1303px;"> <table style="width: 1280px; height: 129px;" border="0"> <tbody> <tr> <td style="width: 377.25px; text-align: right;"><img style="width: 302px; height: 115px;" alt="Logo" src="Images/logo.png"></td> <td style="width: 560.883px;"> <div style="text-align: center;"><font size="+3"><span style="font-family: serif;"><span style="font-family: Helvetica,Arial,sans-serif;">Livingston Community Shed <div style="text-align: center;"><small style="font-family: sans-serif;">Application Form</small><br> </div> <font size="+3"><span style="font-family: serif;"><span style="font-family: Helvetica,Arial,sans-serif;"></span></span></font></span></span></font></div> <big> <font size="+3"> <font size="+3"><span style="font-family: serif;"></span></font> </font></big></td> <td style="width: 402.867px; text-align: left;"><span><img src="Images/smsa-logo.png" alt="smsa logo" style="width: 279px; height: 102px;"><br> </span></td> </tr> </tbody> </table> <ul> <li style="font-weight: bold;"><big><a href="index.html">Home</a></big></li> <li style="font-weight: bold;"><big><a href="about.html">About</a></big></li> <li style="font-weight: bold;"><big><a href="findus.html">Find Us</a></big></li> <big> </big> <li style="font-weight: bold;" class="dropdown"><big> <a href="javascript:void(0)" class="dropbtn">News</a></big> <div style="top: 178px; left: 671px;" class="dropdown-content"><a href="updates.html">Updates</a><a href="projects.html">Projects</a><a href="gardens.html">Gardens</a><a href="videos.html">Videos</a></div> </li> <li style="font-weight: bold;"><big><a href="join.html">Join</a></big></li> <big> <big> </big> </big> <li style="font-weight: bold;"><big><a href="contact.html">Contact</a></big></li> </ul> <div style="text-align: center;"><!-- ************ End of Headings ************** --> <br> <big><big><big><span style="font-family: Helvetica,Arial,sans-serif; color: rgb(51, 51, 255); font-weight: bold;">Livingston Community Shed Application Form</span></big></big></big> </div> <div style="text-align: center; width: 1199px;"><br> </div> <table style="text-align: left; width: 900px; margin-left: auto; margin-right: auto;" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; width: 464px;"> <form style="margin-left: 0px; width: 410px;"><!-- ************ Forename ************** --> <div style="margin-left: 0px; width: 391px;"> <div style="text-align: left;"> <label for="fname">First name:</label><br> </div> <div style="text-align: left;"><input id="fname" name="fname" value="" type="text"><br> <br> </div> <!-- ************ Surname ************** --> <div style="text-align: left;"><label for="sname">Surname:</label><br> </div> <div style="text-align: left;"><input id="sname" name="sname" value="" type="text"><br> <br> </div> <!-- ************ Address 1 ************** --> <div style="text-align: left;"> <label for="add1">Address 1:</label><br> </div> <div style="text-align: left;"><input size="30" id="add1" name="add1"><br> <br> </div> <!-- ************ Address 2 ************** --> <div style="text-align: left;"><label for="add2">Address 2:</label><br> </div> <div style="text-align: left;"><input size="30" id="add2" name="add2"><br> <br> </div> <!-- ************ Town ************** --> <div style="text-align: left;"> <label for="town">Town / City:</label><br> </div> <div style="text-align: left;"><input id="town" name="town" value="" type="text"><br> <br> </div> <!-- ************ Postcode ************** --> <div style="text-align: left;"><label for="pcode">Postcode:</label><br> </div> <div style="text-align: left;"><input size="8" name="pcode" id="pcode"><br> <br> </div> <!-- ************ email ************** --> <div style="text-align: left;"><label for="email">Email:<br> <input id="email" name="email" type="email"><br> </label></div> <!-- ************ Phone number ************** --> <div style="text-align: left;"><label for="phone">Phone Number:</label><br> </div> <div style="text-align: left;"><input size="15" name="phone" id="phone" type="tel"><br> <br> </div> <!-- ************ Birthday ************** --> <div style="text-align: left;"><label for="bday">Date of Birth:</label><br> </div> <div style="text-align: left;"><input size="8" id="bday" name="bday" value="" type="date"><br> <br> </div> </div> </form> </td> <td style="vertical-align: top; width: 632px;"> <form style="width: 529px;"> <label for="cname">Contact name:</label><br> <input id="cname" name="cname" value="" type="text"><br> <br> <label for="relat">Relationship:</label><br> <input id="relat" name="relat" value="" type="text"> <br> <br> <label for="cphone">Contact Phone Number:</label><br> <input id="cphone" name="cphone" type="tel"> <span style="font-weight: bold;"><br> <br> </span> <div><label for="allergy">Please list any allergies you may have:<br> </label> <div style="text-align: left; margin-left: 0px; width: 978px;" class="fcf-input-group"> <textarea cols="30" id="allergy" name="allergy" class="fcf-form-control" rows="5" maxlength="1000" required=""></textarea> </div> <br> <label for="skill">Please list any skills/interests which may be useful to the shed:</label><br> <div style="text-align: left; margin-left: 0px; width: 978px;" class="fcf-input-group"> <textarea cols="30" id="skill" name="skill" class="fcf-form-control" rows="5" maxlength="1000" required=""></textarea> </div> <br> </div> </form> </td> </tr> </tbody> </table> <table style="text-align: left; width: 950px; margin-left: auto; height: 31px; margin-right: auto;" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; width: 874px;"><input id="permit" name="permit" value="No" type="checkbox"> <label for="permit">May we include a summary of this and a photo in the member’s section of the website?</label><br> </td> </tr> </tbody> </table> <table style="text-align: left; height: 151px; margin-right: auto; width: 950px; margin-left: auto;" cellpadding="2" cellspacing="2"> <tbody> <tr> <td colspan="1" rowspan="1" style="vertical-align: top; text-align: center; width: 950px;"> <p style="line-height: 100%; margin-bottom: 0cm;" align="left"><font style="font-size: 14pt;" size="4"><b>Constitution acceptance</b></font></p> <span style="font-weight: bold;"></span> <p style="line-height: 100%; margin-bottom: 0cm;" align="left"><font style="font-size: 12pt;" size="3"><input id="perm" name="agree" value="No" type="checkbox"> <label for="agree">I agree to abide by the constitution of the Livingston Community Shed, a copy of which is held in the shed and on this Website.</label><br> </font><br> </p> <p style="line-height: 100%; margin-bottom: 0cm;" align="left"><font style="font-size: 12pt;" size="3"><input id="smsa" name="smsa" value="No" type="checkbox"><label for="smsa">By applying, I also agree to abide by the Scottish Men’s Sheds Association (SMSA) Constitution and Purposes to which we are affiliated with group membership.</label></font></p> <form style="margin-top: 16px; height: 55px;" enctype="text/plain" method="post" action="/application.php"> <input style="height: 50px; width: 70px;" value="Submit" align="middle" type="submit"><br> <!-- **** If you click the "Submit" button, the form-data will be sent to a page called "/application.php **** --> </form> </td> </tr> </tbody> </table> </body> </html> The PHP page that accompanies it is: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta content="text/html;charset=ISO-8859-1" http-equiv="Content-Type"> <?php if (isset($_POST['Email'])) { // EDIT THE 2 LINES BELOW AS REQUIRED $email_to = "merg.eosag@gmail.com"; $email_subject = "New Application Request."; function problem($error) { echo "We are very sorry, but there were error(s) found with the form you submitted. "; echo "These errors appear below.<br><br>"; echo $error . "<br><br>"; echo "Please go back and fix these errors.<br><br>"; die(); } // validation expected data exists if ( !isset($_POST['fname']) || !isset($_POST['sname']) || !isset($_POST['email']) || !isset($_POST['bday']) || !isset($_POST['agree']) || !isset($_POST['smsa']) ) { problem('We are sorry, but there appears to be a problem with the form you submitted.'); } $fname = $_POST['fname']; // required $sname = $_POST['sname']; // required $email = $_POST['email']; // required $fname = $_POST['bday']; // required $sname = $_POST['agree']; // required $email = $_POST['smsa']; // required $error_message = ""; $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if (!preg_match($email_exp, $email)) { $error_message .= 'The Email address you entered does not appear to be valid.<br>'; } $string_exp = "/^[A-Za-z .'-]+$/"; if (!preg_match($string_exp, $fname)) { $error_message .= 'The Name you entered does not appear to be valid.<br>'; } $string_exp = "/^[A-Za-z .'-]+$/"; if (!preg_match($string_exp, $sname)) { $error_message .= 'The Name you entered does not appear to be valid.<br>'; } $string_exp = ""; if(!preg_match($string_exp,$bday)) { $error_message .= 'You did not choose a date.<br />'; } if (isset($_POST['agree'])) { // Checkbox is checked } else { $error_message .= 'You did not agree to the constitution.<br>'; } if (isset($_POST['smsa'])) { // Checkbox is checked } else { $error_message .= 'You did not agree to the SMSA rules.<br>'; } $email_message = "Form details below.\n\n"; function clean_string($string) { $bad = array("content-type", "bcc:", "to:", "cc:", "href"); return str_replace($bad, "", $string); } $email_message .= "Foreame: " . clean_string($fname) . "\n"; $email_message .= "Surname: " . clean_string($sname) . "\n"; $email_message .= "Address1: " . clean_string($add1) . "\n"; $email_message .= "Address2: " . clean_string($add2) . "\n"; $email_message .= "Town: " . clean_string($town) . "\n"; $email_message .= "Postcode: " . clean_string($pcode) . "\n"; $email_message .= "Email: " . clean_string($email) . "\n"; $email_message .= "Phone Number: " . clean_string($phone) . "\n"; $email_message .= "Date of Birth: " . clean_string($bday) . "\n"; $email_message .= "Contact Name: " . clean_string($cname) . "\n"; $email_message .= "Relationship: " . clean_string($relat) . "\n"; $email_message .= "Contact Phone: " . clean_string($cphone) . "\n"; $email_message .= "Allergies: " . clean_string($allergy) . "\n"; $email_message .= "Skills: " . clean_string($skill) . "\n"; $email_message .= "Page Permission: " . clean_string($permit) . "\n"; $email_message .= "Abide by LCS Rules: " . clean_string($agree) . "\n"; $email_message .= "Abide by SMSA Rules: " . clean_string($smsa) . "\n"; // create email headers $headers = 'From: ' . $email . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); ?><!-- include your success message below --> <title>Application.php</title> </head> <body style="color: rgb(0, 0, 0); background-color: rgb(102, 255, 255);" alink="#000099" link="#000099" vlink="#990099"> <br> <div style="text-align: center;"><?php } ?> <br> <br> <big>Thank you for your application. We will be in touch with you very soon. <br> </big> </div> <div style="text-align: center;"><big><a href="index.html"><br> Back to Home page</a></big><br> </div> </body> </html>
-
I have just begun dabbling with javascript as a hobby and have a very crude understanding of php so please bare with me, I am a noob! I am using a javascript onclick button to reference the function shown below. function deleteReply(fpid) { $.post("ajax_forumdelete.php", {'reply': fpid}, function (d) { }); location.reload(); } When the button is pressed and the function executes it does as it should. It deletes the forum reply post as its told and the page reloads and the post is gone! But without some sort of explanation, success message or something telling me that it did what its intended is very unsatisfying. I read around and found that an additional function is needed to give me a little message. success : function() { var x="Success"; alert(x); } Looks simple enough and one would think should be easy to incorporate but when I add it in every way shape or form I cannot get it to work. The original function wont even work after adding this. Below is basically what I am wanting to do but not quite sure how to go about it. function deleteReply(fpid) { $.post("ajax_forumdelete.php", {'reply': fpid}, function (d) { }); success : function() { var x="<?php $mtg->success("Reply has been deleted."); ?>"; alert(x); location.reload(); } } I want to use the php $mtg->success() function to echo the message in the pre defined output location and format and want to output the message after the reload... Any ideas on how to go about this?
-
Hi Freaks I have an update page for an online groundwater information system. I am using Postgresql/PostGIS. This is a screenshot of the update page with 2 select boxes. My problem is I don't want the columns 'well_no' or 'geom' to appear in the first select element, i.e. the column to update, as they should NOT be updated. The code for the first selection drop-down list is as follows: <p> Columns available - select the column to update</p> <form class="my-form" method="post"> <select name='up_column' id='up_column'> <?php try { $result = $pdo->query("select column_name from information_schema.Columns WHERE table_schema = 'public' AND table_name = '{$table}' ORDER BY column_name desc"); foreach ($result as $row) { unset($row['well_no']); unset($row['geom']); echo "<option value={$row['column_name']}>{$row['column_name']}</option>"; } } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } ?> </select> No need to comment that I am not using prepared statements, as I am in a test environment and will rewrite the query before going into production. Please focus on why my use of unset is not working, as both the forbidden columns are appearing in the select list.
-
Hi guys, Not sure where this one should be posted but will post here. Please move to appropriate if needed. I am trying to open a new modal by clicking a link inside another one. It doesn't seem to want to play ball and the open modal just closes. Can anyone give me a punch bag or maybe just point me in the right direction? The button: <button type="button" id="viewcharterBtn" data-bs-toggle="modal" data-bs-target="#viewcharterModal<?php echo $row['id']; ?>" data-bs-dismiss="modal" class="btn btn-primary">View</button> The modal I want to open: <div tabindex="-1" class="modal" id="viewcharterModal<?php echo $row['id']; ?>" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"><h4><i class="fa fa-map-marker fa-fw"></i><?php echo $row['charter_name']; ?></h4></div> <div class="modal-body"> <h3><?php echo $row['charter_name']; ?></h3> <p>Leaving at <?php echo $row['dep_date']; ?></p> <p>Customer's name is <?php echo $row['customer_name']; ?> and their contact number is <?php echo $row['customer_number']; ?>.</p> <p>The vehicle for this trip is <?php echo $row['fleet_number']; ?></p> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-bs-dismiss="modal"><i class="fa fa-ban"></i> <?php echo lang('CLOSE'); ?></button> </div> </div> </div> </div> Any help would be appreciated.
-
I am retrieving data via Ajax into Choices.js select options My scenario is when I select date, getting the available restaurant tables The retrieving data is 100% working, but it reflects in the select options only in the first request, then when I try to reselect another date I receive the below console error, and choices still keep the initial retrieved data choices.min.js:11 Trying to initialise Choices on element already initialised Choices setValue Function var el = document.getElementsByClassName("table_number")[0]; if (el) { function setChoices(values) { const tableNumbers = new Choices(el, { removeItemButton: true, }).setValue(values); } setChoices(values); } Ajax Code let shiftDate = document.getElementById('reservation_shift_date'); shiftDate.addEventListener("change", function(){ let request = new XMLHttpRequest(); request.open("POST","get_tables.php",true); request.setRequestHeader("content-type","application/x-www-form-urlencoded"); request.onreadystatechange = function(){ if(request.readyState == 4 && request.status == 200){ setChoices(JSON.parse(request.responseText)); } } request.send("date="+shiftDate.value); }); get_tables.php if($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['date'])){ $stmt = $conn->prepare("SELECT table_id FROM reservation WHERE shift_date = ?"); $stmt->execute([$_POST['date']]); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach($rows as $row){ $reserved_tables_id[] = $row['table_id']; } $in = implode(',',$reserved_tables_id); $execute_query = mysqli_query($dbConnection,"SELECT id, table_name FROM tables WHERE id NOT IN ($in)"); while($row = mysqli_fetch_assoc($execute_query)){ $tbl_id = $row['id']; $tbl_name = $row['table_name']; $arr[] = ["value"=>$tbl_id,"label"=>$tbl_name]; } echo json_encode($arr); }
- 1 reply
-
- javascrip
- choices.js
-
(and 2 more)
Tagged with:
-
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>"; ?>
-
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!
- 11 replies
-
- php
- phpmyadmin
-
(and 3 more)
Tagged with:
-
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.
-
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>
-
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?
-
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.
-
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>
-
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.
-
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.
-
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.
-
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> </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>
-
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?
- 13 replies
-
hey basically my code is something like taxi meter but with time i have made functions that calculates money by minute whenever it reaches a minute the money will add by far i made a confirm button which when i click on it i want to send money and time values to data base how ever i had no errors in all my codes but still the values don't want to be sent to my db help me <form id ="data" method ="post" > <h2 id ="done"></h2> <div class="jumbotron jumbotron-single d-flex align-items-center" style="background-image: url(img/billard.jpg)"> <div class="col-md-3 col-sm-10 text-center mt-2"> <div class="shadow rounded feature-item align-items-center p-2 mb-2" data-aos="fade-up"> <div class="my-4"> <i class="lnr lnr-cog fs-40"></i> </div> <h4>Post 1 </h4> <div id="timer"> <span id="hours">00:</span> <span id="mins">00:</span> <span id="seconds">00</span> <br><span id="money">0TND</span> </div> <div id="controls"> <button id="start">Start</button> <button id="stop">Stop</button> <button id="reset">Reset</button> <button id="confirm" >confirm</button><br> <button id="tarifA">TarifA</button> <button id="tarifB">TarifB</button> <button id="tarifC">TarifC</button> </div> <p>Post de PS5</p> </div> </form> $('#confirm').click(function(e) { e.preventDefault(); clearTimeout(timex); $.ajax({ method: "post", url : "collect.php", data: $('#data').serialize(), datatype: "text", success : function (response){ $('#done').html('done'),1000;} })}); <?php if (isset($_POST['money'])) { sleep(4); $servername='localhost'; $username='root'; $password=''; $dbname = "khalil"; $conn=mysqli_connect($servername,$username,$password,"$dbname"); if($conn){print_r("connected ");} $money=$_POST['money']; $hours=$_POST['hours']; $mins=$_POST['mins']; $seconds=$_POST['seconds']; $sql = "INSERT INTO `history` (`prix`,`time1`,`date1`) VALUES (`$money`,`mins`,`wassim`)"; // insert in database $rs = mysqli_query($conn, $sql); if($rs) { $success= "done"; } } ?>
- 3 replies
-
- php
- javascript
-
(and 1 more)
Tagged with:
-
<?php include(dirname( __DIR__ ,1) . "/PDO_db_config.php"); function hexToRgb($hex) { $hex = str_replace('#', '', $hex); $length = strlen($hex); $r = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0)); $g = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0)); $b = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0)); return $r.",".$g.",".$b; } function getcolorname($mycolor) { $colors = array( "black" =>array(0,0,0), "green" =>array(0,255,0), "blue" =>array(0,0,255), "cyan" =>array(0,255,255), "red" =>array(255,0,0), "yellow" =>array(255,255,0), "magenta" =>array(255,0,255), "grey" =>array(128,128,128), "white" =>array(255,255,255) ); $tmpdist = 765; $tmpname = "none"; foreach($colors as $colorname => $colorset) { $r_dist = (pow($mycolor[0],2) - pow($colorset[0],2)); $g_dist = (pow($mycolor[1],2) - pow($colorset[1],2)); $b_dist = (pow($mycolor[2],2) - pow($colorset[2],2)); $totaldist = sqrt($r_dist + $g_dist + $b_dist); if ($totaldist < $tmpdist) { $tmpname = $colorname; $tmpdist = $totaldist; } } return $tmpname; } $sql = $pdo->prepare("SELECT * FROM colors"); $sql->execute(); foreach ($sql as $data) { $RGB = hexToRgb($data['HEX']); $arry = explode(',', $RGB); $DEC = "<".round(($arry[0]/255),3).",".round(($arry[1]/255),3).",".round(($arry[2]/255),3).">"; $color = getcolorname($arry); $sql2 = $pdo->prepare("UPDATE `colors` SET `category` = :CAT, RGB = :RGB, LSL = :DEC WHERE (`color_ID` = :color_ID)"); $sql2->bindValue(':CAT', $color, PDO::PARAM_STR); $sql2->bindValue(':RGB', $RGB, PDO::PARAM_STR); $sql2->bindValue(':DEC', $DEC, PDO::PARAM_STR); $sql2->bindValue(':color_ID', $data['color_ID'], PDO::PARAM_STR); $sql2->execute(); } echo "done"; I have a table of colors and I am trying to add color categories to each Color, but it is not categorizing correctly, any Help please.
-
I have school fees management system it's work perfect but now I need to add email print on receipt I have email table but I don't know to print too on receipt kindly give me any idea to print ( <?php include 'db_connect.php'; $fees = $conn->query("SELECT ef.*,s.name as sname,s.id_no,concat(c.course,' - ',c.level) as `class` FROM student_ef_list ef inner join student s on s.id = ef.student_id inner join courses c on c.id = ef.course_id where ef.id = {$_GET['ef_id']}"); foreach($fees->fetch_array() as $k => $v){ $$k= $v; } $payments = $conn->query("SELECT * FROM payments where ef_id = $id "); $pay_arr = array(); while($row=$payments->fetch_array()){ $pay_arr[$row['id']] = $row; } ?> <style> .flex{ display: inline-flex; width: 100%; } .w-50{ width: 50%; } .text-center{ text-align:center; } .text-right{ text-align:right; } table.wborder{ width: 100%; border-collapse: collapse; } table.wborder>tbody>tr, table.wborder>tbody>tr>td{ border:1px solid; } p{ margin:unset; } </style> <div class="container-fluid"> <p class="text-center"><b><?php echo $_GET['pid'] == 0 ? "Payments" : 'Payment Receipt' ?></b></p> <hr> <div class="flex"> <div class="w-50"> <p>EF. No: <b><?php echo $ef_no ?></b></p> <p>Student: <b><?php echo ucwords($sname) ?></b></p> <p>Course/Level: <b><?php echo $class ?></b></p> </div> <?php if($_GET['pid'] > 0): ?> <div class="w-50"> <p>Payment Date: <b><?php echo isset($pay_arr[$_GET['pid']]) ? date("M d,Y",strtotime($pay_arr[$_GET['pid']]['date_created'])): '' ?></b></p> <p>Paid Amount: <b><?php echo isset($pay_arr[$_GET['pid']]) ? number_format($pay_arr[$_GET['pid']]['amount'],2): '' ?></b></p> <p>Remarks: <b><?php echo isset($pay_arr[$_GET['pid']]) ? $pay_arr[$_GET['pid']]['remarks']: '' ?></b></p> </div> <?php endif; ?> </div> <hr> <p><b>Payment Summary</b></p> <table class="wborder"> <tr> <td width="50%"> <p><b>Fee Details</b></p> <hr> <table width="100%"> <tr> <td width="50%">Fee Type</td> <td width="50%" class='text-right'>Amount</td> </tr> <?php $cfees = $conn->query("SELECT * FROM fees where course_id = $course_id"); $ftotal = 0; while ($row = $cfees->fetch_assoc()) { $ftotal += $row['amount']; ?> <tr> <td><b><?php echo $row['description'] ?></b></td> <td class='text-right'><b><?php echo number_format($row['amount']) ?></b></td> </tr> <?php } ?> <tr> <th>Total</th> <th class='text-right'><b><?php echo number_format($ftotal) ?></b></th> </tr> </table> </td> <td width="50%"> <p><b>Payment Details</b></p> <table width="100%" class="wborder"> <tr> <td width="50%">Date</td> <td width="50%" class='text-right'>Amount</td> </tr> <?php $ptotal = 0; foreach ($pay_arr as $row) { if($row["id"] <= $_GET['pid'] || $_GET['pid'] == 0){ $ptotal += $row['amount']; ?> <tr> <td><b><?php echo date("Y-m-d",strtotime($row['date_created'])) ?></b></td> <td class='text-right'><b><?php echo number_format($row['amount']) ?></b></td> </tr> <?php } } ?> <tr> <th>Total</th> <th class='text-right'><b><?php echo number_format($ptotal) ?></b></th> </tr> </table> <table width="100%"> <tr> <td>Total Payable Fee</td> <td class='text-right'><b><?php echo number_format($ftotal) ?></b></td> </tr> <tr> <td>Total Paid</td> <td class='text-right'><b><?php echo number_format($ptotal) ?></b></td> </tr> <tr> <td>Balance</td> <td class='text-right'><b><?php echo number_format($ftotal-$ptotal) ?></b></td> </tr> </table> </td> </tr> </table> </div> ) My WhatsApp number is +923409871374 Pls help me
- 1 reply
-
- php
- php database
-
(and 1 more)
Tagged with:
-
Hello member's please check my code i set weebhook aleady but bot didnt respond <?php $input= file_get_contents('php://input'); $update= json_decode($input); $message=$update->message; $chat_id=$message->chat->id; $text=$message->text; $token='key'; file_get_contents("https://api.telegram.org/bot$token/sendMessage?chat_id=$chat_id&text=$text"); ?>
-
I want to allow users on my hosted website to download files. Most of the following code was copied from php.net but when I run it, I'm only getting 495 bytes of a 5.7M file when testing downloads from my webhost. This code exists in a window that is never seen by the user. $l_filename is passed from another window. I'm not seeing any errors. My code follows: <?php error_reporting(E_ALL); ini_set('display_errors', '1'); function usdloader($l_filename=NULL){ if (file_exists($l_filename)) { $file = preg_replace("/\s+/u", " ", $l_filename); header('Content-Description: File Transfer'); header('Content-Type: ' . mime_content_type($file)); header('Content-Disposition: inline; filename="'.basename($file).'"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); readfile($file); else die; } } usdloader($_GET["f"]); I thank you for your help.