Jump to content

Search the Community

Showing results for tags 'php'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

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

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. Out of thousands of twitter profiles active in the PHP environment, we assembled a Ranking of the Top 25 Social Influencers in PHP. http://www.cloudways.com/blog/php-influencers-to-follow/ What are some people that you would like to add?
  2. When I first started this project, PHP was new to me and I didn't have a clue how to use it. Here, seven months later, I still don't know what I'm doing. I have 47 pages that are MySQL intensive. Each client has their own login credentials to the database. I've been using the $_SESSION global to carry these credentials across the pages. I realize this is a huge security issue, but I don't know any other way to keep their username / password handy as they log in and out of the database. I've searched and not found anything resembling my need here. Most of the discussions relate to setting $_SESSION['foo'] = 'bar' and carying that from page to page. I cld really use some insight on this. Thanks.
  3. how can i use implode() on a multi dimensional array? say I have: $cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("Land Rover",17,15) ); And i say: implode('||',$cars); what will it be like in the string ?what effect will it have on the inner child arrays of $cars?will they also have the '||' as separator?
  4. Hi everyone, I'm sure you have seen me around in here by learning PHP, I am getting advance now. But I don't understand why it won't insert in PHPmyadmin (MySQL) with my prompt in php. Can you find why it won't add name as insert into my database? if ($_POST['submmited']) { $first = $_POST['firstname']; $last = $_POST['lastname']; $email = $_POST['email']; if ($first && $last && $email) { $sql = "INSERT INTO Student (StudentID,Firstname,LastName,Email) VALUES (NULL,'$first','$last','$email')"; mysqli_query($Garydb, $sql); } else { echo "Failed to add register"; } } I checked around, there is no mistake but it won't add a new as insert into my database...why? What Did I do wrong? Thank you in advance Gary
  5. hi, guys can any one say where im going wrong in this code as im not able to get to display friend lists in both search_results.php and home.php. the code in friend_list.php which is included in both home and search results page to display friends list: <?php $friends_html=""; $orlogic=""; $uname_s= \htmlentities($_GET['u']); $sql="select count(friend_id) from friends where friend_one=:uname_s and accepted='1' or friend_two=:uname_s and accepted='1'"; $stmt=$conn->prepare($sql); $stmt->bindparam(":uname_s", $uname_s); $stmt->execute(); $query_count=$stmt->fetchAll(PDO::FETCH_ASSOC); $friend_count=$query_count[0]; if ($friend_count<1) { $friends_html="$uname_s has no friends yet"; } else { $all_friends=array(); $sql="select friend_one, friend_two from friends where friend_two=:uname_s and accepted='1' order by rand()"; $stmt=$conn->prepare($sql); $stmt->bindparam(":uname_s",$uname_s); $stmt->execute(); while ($row =$stmt->fetchAll(PDO::FETCH_ASSOC)) { array_push($all_friends, $row[0]['friend_one']); } $sql1="select * from friends where friend_one=:uname_s and accepted='1' order by rand()"; $stmt1=$conn->prepare($sql1); $stmt1->bindparam(":uname_s",$uname_s); $stmt1->execute(); while ($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)) { array_push($all_friends, $row1['friend_two']); } $friendArrayCount= count($all_friends); foreach ($all_friends as $key => $user) { $orlogic .="uname='$user' OR"; } $orlogic1= chop($orlogic, "OR"); $sql2="select uname,avatar from user where :orlogic1"; $stmt2=$conn->prepare($sql2); $stmt2->bindparam(":orlogic1",$orlogic1); $stmt2->execute(); while ($row11 = $stmt2->fetchAll(PDO::FETCH_ASSOC)) { $friend_username=$row11[0]["uname"]; $friend_avatar=$row11[0]["avatar"]; if ($friend_avatar!=""){ $friend_pic='user/'.$friend_username.'/'.$friend_avatar; } else { $friend_pic='img/avatardefault.png'; } echo '<a href="search_results.php?u='.$friend_username.'"><img class="friendpics" src="'.$friend_pic.'" height="80" width="80" alt="'.$friend_username.'" title="'.$friend_username.'">'.$friend_username.'</a>'; } } if you guys need any further info please let me know
  6. loading image during ajax process not working properly: my code smthing like this... div to show content and loading image- <div id="adS" style="float: left; width: 70%"> <div id="loading-image" style="background-image: url('images/processing.gif'); display: none;"> </div> </div> jquery code- $(function() { $("#lets_search").bind('submit',function() { var gen = $("input[name='radGen']:checked").val(); var mt = $('#selMtQ').val(); var agf = $('#agf').val(); var agt = $('#agt').val(); var rel = $('#religQ').val(); var cast = $('#selCstQ').val(); $('#loading-image').show(); $.post('adSearch.php',{gen:gen,mt:mt,agf:agf,agt:agt,rel:rel,cast:cast}, function(data){ $("#adS").html(data); $('#loading-image').hide(); }); return false; }); }); The loading image show only one time on click event.. not every time when i click search li... Need help...
  7. Hello - I hope I explain this clearly... I have some php code that presently displays 4 boxes in a row with images. When you click on a box/image, you go to a web post. The code goes to the bottom, sets the link, then loops back for the next image and repeats the process. What I'm trying to do is break this code apart so that that I can make each image go to a different link - basically set it up as html - image with link to a page. ( 4 of these) However, I don't want to break the code or the page that it displays ( our home page ) Here's the code snippet: <div id="new-classes" class="carousel slide"> <!-- Wrapper for slides ufff--> <div class="carousel-inner"> <?php $pieces=array_chunk($gallery,4); $j=0; foreach ($pieces as $slice) { echo '<div class="item '; if($j==0){echo 'active';} echo '">'; foreach ($slice as $i => $conte) { ?> <div class="col-sm-6 col-md-3" > <div class="new-class" > <img src="<?php echo $slice[$i]['image']; ?>" alt="//" /> <div class="class-title" > <div class="occult" > TEST this is where the specialities boxes link is <a <?php echo colors('a');?> href="<?php echo $slice[$i]['link']; ?>" class="link" ></a> I duplicated the above line and put in a specific link but it makes all the images go to the same page <a <?php echo colors('a');?> href="https://www.absolutept.com/tendinopathy/" class="link" ></a> --> </div> <h3 <?php echo colors('h3');?>><?php echo $slice[$i]['title']; ?></h3> <p <?php echo colors('p');?> class="occult" ><?php echo wp_trim_words(insert_br($slice[$i]['desc']),10,'...'); ?></p> </div> </div> </div> <?php } //end slice echo '</div>'; $j++; } // end pieces ?> </div> our homepage is absolutept.com -- these images are the "specialties" section 3/4 of the way down In the theme( wordpress) - there's an option to enter specialties ( custom post type ) which we did but we don't want these links to go to those special posts, we want them to go to the pages that the user can find in the main menu I know this is breaking the set up of the theme but if it's doable, we'd like to try First - any idea if it's doable and if so, thoughts on how? =) Thanks in advance.
  8. Hi I'm currently stuck with an image upload script that doesn't seem to rename my files correctly and if its a jpg file the conversion doesn't take place correctly as well any assistance please? All I'm trying to do is to change a random photo to jpg format and resize it to be less than 100kb <?php include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php'; $ip = $_SERVER["HTTP_X_MXIT_USERID_R"]; if(!isset($ip)) { $ip = "Debater"; } $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\""); $row = mysql_fetch_array($result9); $id = $row['ID']; // Access the $_FILES global variable for this specific file being uploaded // and create local PHP variables from the $_FILES array of information $fileName = $_FILES["uploaded_file"]["name"]; // The file name $fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder $fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is $fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes $fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true $fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter the $filename $kaboom = explode(".", $fileName); // Split file name into an array using the dot $imageTypeArray = array ( 0=>'UNKNOWN', 1=>'GIF', 2=>'JPEG', 3=>'PNG', 4=>'SWF', 5=>'PSD', 6=>'BMP', 7=>'TIFF_II', 8=>'TIFF_MM', 9=>'JPC', 10=>'JP2', 11=>'JPX', 12=>'JB2', 13=>'SWC', 14=>'IFF', 15=>'WBMP', 16=>'XBM', 17=>'ICO', 18=>'COUNT' ); $size = getimagesize($fileTmpLoc); $size[2] = $imageTypeArray[$size[2]]; $fileExt = $size[2]; // Now target the last array element to get the file extension // START PHP Image Upload Error Handling -------------------------------- if (!$fileTmpLoc) { // if file not chosen echo "ERROR: Please browse for a file before clicking the upload button."; exit(); } else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes echo "ERROR: Your file was larger than 5 Megabytes in size."; unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder exit(); } else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) { // This condition is only if you wish to allow uploading of specific file types echo "ERROR: Your image was not .gif, .jpg, or .png."; unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder exit(); } else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1 echo "ERROR: An error occured while processing the file. Try again."; exit(); } // END PHP Image Upload Error Handling ---------------------------------- // Place it into your "uploads" folder mow using the move_uploaded_file() function $moveResult = move_uploaded_file($fileTmpLoc, "images/".$id."_".date_create()->getTimestamp().".".$fileExt); // Check to make sure the move result is true before continuing if ($moveResult != true) { echo "ERROR: File not uploaded. Try again."; exit(); } // Include the file that houses all of our custom image functions include_once("ak_php_img_lib_1.0.php"); // ---------- Start Universal Image Resizing Function -------- $target_file = "images/".$id."_".date_create()->getTimestamp().".".$fileExt; $resized_file = "images/resized_".$id."_".date_create()->getTimestamp()."." . $fileExt; $wmax = 320; $hmax = 240; ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt); unlink($target_file); // ----------- End Universal Image Resizing Function ---------- // ---------- Start Convert to JPG Function -------- $target_file = "images/resized_".$id."_".date_create()->getTimestamp()."." . $fileExt; $new_jpg = "images/resized_".$id."_".date_create()->getTimestamp().".jpg"; ak_img_convert_to_jpg($target_file, $new_jpg, $fileExt); unlink($target_file); $new_jpg = "images/resized_".$id."_".date_create()->getTimestamp().".jpg"; if(!get_magic_quotes_gpc()) { $new_jpg = addslashes($new_jpg); $filePath = addslashes($filePath); } $resultc = mysql_query("SELECT * FROM Users2 WHERE mxitid = '$ip'"); $rowc = mysql_fetch_array($resultc); $ppica = $rowc['pprofilepic']; $naam = "ADMIN"; $naam2 = $rowc['pprofilepic']; $msg = "You Requested a Profile Picture change, please wait till an Admin can manage the request"; $msg1 = "Please aprove my Profile Picture"; $post_time = date("U"); $read1 = "unread"; $banby2 = "ADMIN"; $result = mysql_query("UPDATE Users2 SET pprofilepic='$new_jpg', aprove='requested' WHERE mxitid='$ip'") or die(mysql_error()); unlink($ppica); $query1 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam\",\"$ip\",\"$msg\",\"$post_time\",\"$read1\",\"$banby2\")"; $result1 = mysql_query($query1, $db) or die("Invalid query: " . mysql_error()); $query2 = "INSERT INTO pm (`username`,`mxitid`,`message`,`time`,`read`,`ip`) VALUES (\"$naam2\",\"$banby2\",\"$msg1\",\"$post_time\",\"$read1\",\"$ip\")"; $result2 = mysql_query($query2, $db) or die("Invalid query: " . mysql_error()); // ----------- End Convert to JPG Function ----------- // Display things to the page so you can see what is happening for testing purposes echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />"; echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />"; echo "It is an <strong>$fileType</strong> type of file.<br /><br />"; echo "The file extension is <strong>$fileExt</strong><br /><br />"; echo "The Error Message output for this upload is: $fileErrorMsg"; if($result){ header('Location: ../profile/thankyou.php'); } else { echo "ERROR"; } // close mysql mysql_close(); ?>
  9. Hi all, I am a real newbie with PHP and mysql. I am trying to create a thumbnail carousel to present all the web applications we have in house.I am using some code from this demo because it does close to everything I need. The problem is that it displays only one image per slide and I would like to display multiple items per slide instead. Is it possible with a foreach loop for example? Code: <?php include_once('db.php'); $query = "select * from images order by id desc limit 6"; $res = mysqli_query($connection,$query); $count = mysqli_num_rows($res); $slides=''; $Indicators=''; $counter=0; while($row=mysqli_fetch_array($res)) { $title = $row['title']; $desc = $row['desc']; $image = $row['image']; if($counter == 0) { $Indicators .='<li data-target="#carousel-example-generic" data-slide-to="'.$counter.'" class="active"></li>'; $slides .= '<div class="item active"> <img src="images/'.$image.'" alt="'.$title.'" /> <div class="carousel-caption"> <h3>'.$title.'</h3> <p>'.$desc.'.</p> </div> </div>'; } else { $Indicators .='<li data-target="#carousel-example-generic" data-slide-to="'.$counter.'"></li>'; $slides .= '<div class="item"> <img src="images/'.$image.'" alt="'.$title.'" /> <div class="carousel-caption"> <h3>'.$title.'</h3> <p>'.$desc.'.</p> </div> </div>'; } $counter++; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Dynamic image slider using twitter bootstrap & PHP with MySQL | PGPGang.com</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <style type="text/css"> img {border-width: 0} * {font-family:'Lucida Grande', sans-serif;} </style> </head> <body onload="changePagination('0','first')"> <h2>Dynamic image slider using twitter bootstrap & PHP with MySQL Example. => <a href="http://www.phpgang.com/">Home</a> | <a href="http://demo.phpgang.com/">More Demos</a></h2> <link rel="stylesheet" href="css/bootstrap.min.css" /> <script type="text/javascript" src="js/jquery-1.8.0.min.js"></script> <script src="js/bootstrap.min.js"></script> <style> .carousel-caption { background-image: url("http://www.phpgang.com/wp-content/themes/PHPGang_v2/img/bg_sidebar.png"); } .carousel-inner>.item>img, .carousel-inner>.item>a>img { height:400px; width:700px; } </style> <div class="container" style="width: 730px;"> <h2>Dynamic Image Slider</h2><span style="float: right;margin-top: -30px;"><a href="addnew.php">Add More Images</a></span> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <?php echo $Indicators; ?> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <?php echo $slides; ?> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a class="right carousel-control" href="#carousel-example-generic" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> </a> </div> </div> </body> </html> Thanks, Alex
  10. Hi I'm trying to create a countdown timer strictly php only and do an action once the time runs out I found an example of a countdown timer but I'm uncertain on how to use it to show in the format D H:m:s ( 01 Days 23:01:20) and how to chaeck if the time is done and do the action and afterwards remove the countdown timer from showing on the page <?php // Define your target date here $targetYear = 2007; $targetMonth = 9; $targetDay = 10; $targetHour = 12; $targetMinute= 00; $targetSecond= 00; // End target date definition // Define date format $dateFormat = "Y-m-d H:i:s"; $targetDate = mktime($targetHour,$targetMinute,$targetSecond,$targetMonth,$targetDay,$targetYear); $actualDate = time(); $secondsDiff = $targetDate - $actualDate; $remainingDay = floor($secondsDiff/60/60/24); $remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60); $remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60); $remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60)); $targetDateDisplay = date($dateFormat,$targetDate); $actualDateDisplay = date($dateFormat,$actualDate); echo "$remainingDay days, $remainingHour hours, $remainingMinutes minutes, $remainingSeconds seconds"; ?>
  11. I need urgent help! For two days I've been trying to find the source code to upload image to database and display, after trying all the codes I kept getting all sorts of errors. I'm using phpmyadmin. Fatal error: Call to undefined function finfo_open() in C:\xampp\htdocs\geology\file_insert.php on line 51 Second help needed is to display or restrict 3 latest posts only. I want to display only 3 latest posts sort by latest date posted. I'm not sure how to loop this through. Another thing is, when the user clicks on the title of a specific article, a new window will appear to display only the data that belong to it (Title, Publisher, Content...) For example, there are 3 articles (rock, mineral, salt) user clicks on Rocks, a new window appear showing all Rocks info. <?php $sql = "select * from article ORDER by article_postdate DESC"; $result = mysqli_query($conn, $sql); while($row = mysqli_fetch_assoc($result)) { ?> <h3><a href="#"><?php echo $row["article_title"]; ?></a></h3> <p class="byline"><span><?php echo $row["article_postdate"]; ?><br> Published By:<?php echo $row["author_id"]; ?></p></a></span></p> <p><?php echo $row["article_details"]; ?></p> <td><a href = "edit.php?article_id=<?php echo $row['article_id']; ?>">More...</a></td> <?php } ?>
  12. Hello I have a strange issue. (or maybe not for you). In wordpress you can put instagram as iframes simply by writing the url on a separate line. That works fine. But I needed to get the url proglamaticly so I did a php code like the following <?php echo '<iframe height="1250px" width="96%" frameborder="0" scrolling="no" src="', htmlspecialchars($_GET["insta"]), '">', '</iframe>'; ?> What it does is that it takes from the url the variable insta and puts that on the page as an iframe. ex. www.myblog.com/specialpage?insta=https://instagram.com/p/8JEjgAicX7/ So this doesent work. it gives an empty iframe, but if I only write that address in a wordpress post or page it do work. However with the exact same code with /embed/ added do work. Problem is that does not show the captions and hashtags. www.myblog.com/specialpage?insta=https://instagram.com/p/8JEjgAicX7/embed/ <-- this is working I dont know if this a php-wordpress or what problem. but if you have a clue then your help is appreciated
  13. Hi all. How can i send mail to multiple users at the same time with each user getting their own related data. I'm using php mailer as an engine to send the mail. Based on this, i'd have loved to setup a cron for it but i do not know how, so i figure i'd just do it manually before i get to know how to setup a cron job. It's just to send a reminder to users and each user has a different subscription expiry time. I want each user to get their respective expiration date, expiry day etc. Thanks if(isset($_POST['send_reminder'])){ $sql = "SELECT * FROM users WHERE status = '$status'"; $stmt = $pdo->query($sql); $stmt->execute(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ $name = $row['name']; $acct_no = $row['acct_no']; $email_addresses = $row['email']; $expiry_date = $row['expiry_date']; $expiry_day = $row['expiry_day']; } $message="Hello $name,<br> <p> This is to remind you that your subscription will expire in $expiry_day. </p> <p> Details as follows: Name: $name<br> Account Number: $acct_no<br> Email: $email_addresses<br> Expire in days: $expiry_day<br> Expiry Date: $expiry_date </p> <p> Thank you </p> $mail = new PHPMailer; //$mail->SMTPDebug = 3; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'mail.server.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'mails@services.cap'; // SMTP username $mail->Password = 'password'; // SMTP password $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 465; // TCP port to connect to $mail->From = mails@services.cap'; $mail->FromName = 'Club 404'; $mail->addAddress($email_addresses); // Add a recipient $mail->WordWrap = 587; // Set word wrap to 50 characters $mail->AddEmbeddedImage("../img/logo.png", "my_logo"); $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'REMINDER ON CLUB EXPIRY DATE'; $mail->Body = $mess; $mail->send(); }
  14. Hi, Just wondering if someone could point me in the right direction, I have a simple PHP MySQL login script which passes/stores data via sessions. It works fine, there is no problem with it. All I would like to do is pass some additional data from the users MySQL table. Currently it users just username and password, but I would like it to pass firstname and surname data as well. So when a user logs in with their username and password, on the next page it might say Welcome, Michael Smith. The script below is originally setup for the username to be a persons name, as it's used in the login welcome message in the login.php But I might change the username to be an email address, if I can pull in the additional data. config.php <?php /***************************** File: includes/config.php Written by: Frost of Slunked.com Tutorial: User Registration and Login System ******************************/ // start the session before any output. session_start(); // Set the folder for our includes $sFolder = '/predictor/login'; /*************** Database Connection You will need to change the user (user) and password (password) to what your database information uses. Same with the database name if you used something else. ****************/ mysql_connect('localhost', 'root', '') or trigger_error("Unable to connect to the database: " . mysql_error()); mysql_select_db('football') or trigger_error("Unable to switch to the database: " . mysql_error()); /*************** password salts are used to ensure a secure password hash and make your passwords much harder to be broken into Change these to be whatever you want, just try and limit them to 10-20 characters each to avoid collisions. ****************/ define('SALT1', '24859f@#$#@$'); define('SALT2', '^&@#_-=+Afda$#%'); // require the function file require_once($_SERVER['DOCUMENT_ROOT'] . $sFolder . '/includes/functions.php'); // default the error variable to empty. $_SESSION['error'] = ""; // declare $sOutput so we do not have to do this on each page. $sOutput=""; ?> login.php <?php /***************************** File: login.php Written by: Frost of Slunked.com Tutorial: User Registration and Login System ******************************/ require($_SERVER['DOCUMENT_ROOT'] . '/predictor/login/includes/config.php'); // If the user is logging in or out // then lets execute the proper functions if (isset($_GET['action'])) { switch (strtolower($_GET['action'])) { case 'login': if (isset($_POST['username']) && isset($_POST['password'])) { // We have both variables. Pass them to our validation function if (!validateUser($_POST['username'], $_POST['password'])) { // Well there was an error. Set the message and unset // the action so the normal form appears. $_SESSION['error'] = "Bad username or password supplied."; unset($_GET['action']); } }else { $_SESSION['error'] = "Username and Password are required to login."; unset($_GET['action']); } break; case 'logout': // If they are logged in log them out. // If they are not logged in, well nothing needs to be done. if (loggedIn()) { logoutUser(); $sOutput .= '<h1>Logged out!</h1><br />You have been logged out successfully. <br /><h4>Would you like to go to <a href="index.php">site index</a>?</h4>'; }else { // unset the action to display the login form. unset($_GET['action']); } break; } } $sOutput .= '<div id="index-body">'; // See if the user is logged in. If they are greet them // and provide them with a means to logout. if (loggedIn()) { $sOutput .= '<h1>Logged In!</h1><br /><br /> Hello, ' . $_SESSION["username"] . ' how are you today?<br /><br /> <h4>Would you like to <a href="login.php?action=logout">logout</a>?</h4> <h4>Would you like to go to <a href="index.php">site index</a>?</h4>'; }elseif (!isset($_GET['action'])) { // incase there was an error // see if we have a previous username $sUsername = ""; if (isset($_POST['username'])) { $sUsername = $_POST['username']; } $sError = ""; if (isset($_SESSION['error'])) { $sError = '<span id="error">' . $_SESSION['error'] . '</span><br />'; } $sOutput .= '<h2>Login to our site</h2><br /> <div id="login-form"> ' . $sError . ' <form name="login" method="post" action="login.php?action=login"> Username: <input type="text" name="username" value="' . $sUsername . '" /><br /> Password: <input type="password" name="password" value="" /><br /><br /> <input type="submit" name="submit" value="Login!" /> </form> </div> <h4>Would you like to <a href="login.php">login</a>?</h4> <h4>Create a new <a href="register.php">account</a>?</h4>'; } $sOutput .= '</div>'; // lets display our output string. echo $sOutput; ?> functions.php <?php /***************************** File: includes/functions.php Written by: Frost of Slunked.com Tutorial: User Registration and Login System ******************************/ /*********** bool createAccount (string $pUsername, string $pPassword) Attempt to create an account for the passed in username and password. ************/ function createAccount($pUsername, $pPassword, $pFirstname, $pSurname) { // First check we have data passed in. if (!empty($pUsername) && !empty($pPassword) && !empty($pFirstname) && !empty($pSurname)) { $uLen = strlen($pUsername); $pLen = strlen($pPassword); $fLen = strlen($pFirstname); $sLen = strlen($pSurname); // escape the $pUsername to avoid SQL Injections $eUsername = mysql_real_escape_string($pUsername); $sql = "SELECT username FROM users WHERE username = '" . $eUsername . "' LIMIT 1"; // Note the use of trigger_error instead of or die. $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); // Error checks (Should be explained with the error) if ($uLen <= 4 || $uLen >= 11) { $_SESSION['error'] = "Username must be between 4 and 11 characters."; }elseif ($pLen < 6) { $_SESSION['error'] = "Password must be longer then 6 characters."; }elseif (mysql_num_rows($query) == 1) { $_SESSION['error'] = "Username already exists."; }else { // All errors passed lets // Create our insert SQL by hashing the password and using the escaped Username. $sql = "INSERT INTO users (`username`, `password`, `firstname`, `surname`) VALUES ('" . $eUsername . "', '" . hashPassword($pPassword, SALT1, SALT2) . "', '" . $pFirstname . "', '" . $pSurname . "');"; $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); $sql2 = "INSERT INTO predictions (userID, predictionID, week) SELECT LAST_INSERT_ID(), id, week FROM fixtures"; $query = mysql_query($sql2) or trigger_error("Query Failed: " . mysql_error()); if ($query) { return true; } } } return false; } /*********** string hashPassword (string $pPassword, string $pSalt1, string $pSalt2) This will create a SHA1 hash of the password using 2 salts that the user specifies. ************/ function hashPassword($pPassword, $pSalt1="2345#$%@3e", $pSalt2="taesa%#@2%^#") { return sha1(md5($pSalt2 . $pPassword . $pSalt1)); } /*********** bool loggedIn verifies that session data is in tack and the user is valid for this session. ************/ function loggedIn() { // check both loggedin and username to verify user. if (isset($_SESSION['loggedin']) && isset($_SESSION['userID']) && isset($_SESSION['username'])) { return true; } return false; } /*********** bool logoutUser Log out a user by unsetting the session variable. ************/ function logoutUser() { // using unset will remove the variable // and thus logging off the user. unset($_SESSION['username']); unset($_SESSION['userID']); unset($_SESSION['loggedin']); return true; } /*********** bool validateUser Attempt to verify that a username / password combination are valid. If they are it will set cookies and session data then return true. If they are not valid it simply returns false. ************/ function validateUser($pUsername, $pPassword) { // See if the username and password are valid. $sql = "SELECT * FROM users WHERE username = '" . mysql_real_escape_string($pUsername) . "' AND password = '" . hashPassword($pPassword, SALT1, SALT2) . "' LIMIT 1"; $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); // If one row was returned, the user was logged in! if (mysql_num_rows($query) == 1) { $row = mysql_fetch_assoc($query); $_SESSION['username'] = $row['username']; $_SESSION['userID'] = $row['userID']; $_SESSION['password'] = $row['password']; $_SESSION['loggedin'] = true; return true; } return false; } ?> USERS TABLE ID username password firstname surname 1 rich 12345 Richard Branson 2 alan 67898 Lord Sugar
  15. <!DOCTYPE html> <!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. --> <html> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <div id="txtHint"></div> <script> function showUser(str) { // alert (str); if (str == "") { document.getElementById("txtHint").innerHTML = ""; return; } else { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("txtHint").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "new.php?q=" + str, true); xmlhttp.send(); } } </script> <body> <form> <select onchange="showUser(this.value)"> <option value="1" > 1 </option> <option value="3" > 3 </option> </select> <?php $con = mysqli_connect("localhost", "root", ""); mysqli_select_db($con, "crud_tutorial"); if (isset($_REQUEST['q'])) { $q = intval($_GET['q']); //echo "$q"; $sql = "SELECT * FROM customers WHERE id = '" . $q . "'"; $result = mysqli_query($con, $sql); } else { $sql = "SELECT * FROM customers "; $result = mysqli_query($con, $sql); } echo "<table> <tr> <th>id</th> <th>name</th> </tr>"; while ($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['id'] . "</td>"; echo "<td>" . $row['name'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); ?> </form> </body> </html>
  16. Hi, I im using an API script to retrieve info, but im getting the error Can anyone please help me out what could be the cause of this error and how to resolve it? <?php /** * MXit API PHP Wrapper - version 1.4.0 * * Written by: Ashley Kleynhans <ashley@digigoblin.com> * * Copyright 2013 DigiGoblin (Pty) Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Ensure that CURL and JSON PHP extensions are present */ if (!function_exists('curl_init')) { throw new Exception('The Mxit PHP class is unable to find the CURL PHP extension.'); } if (!function_exists('json_decode')) { throw new Exception('The Mxit PHP class is unable to find the JSON PHP extension.'); } if (!function_exists('base64url_decode')) { function base64url_decode($base64url) { $base64 = strtr($base64url, '-_', '+/'); $plainText = base64_decode($base64); return ($plainText); } } if (!function_exists('is_json')) { function is_json($json) { json_decode($json); return (json_last_error() == JSON_ERROR_NONE); } } if (!function_exists('is_base64')) { function is_base64($encoded_string) { $length = strlen($encoded_string); for ($i = 0; $i < $length; ++$i) { $c = $encoded_string[$i]; if ( ($c < '0' || $c > '9') && ($c < 'a' || $c > 'z') && ($c < 'A' || $c > 'Z') && ($c != '+') && ($c != '/') && ($c != '=') ) { return false; } } return true; } } class MxitAPI { private $_version; private $_base_outh_url; private $_base_user_api_url; private $_base_messaging_api_url; private $_app_key; private $_app_secret; private $_token_type; private $_access_token; private $_expires_in; private $_scope; private $_id_token; private $_headers; public $http_status; public $content_type; public $result; public $error; public function __construct($key, $secret) { $this->_version = '1.4.0'; $this->_base_outh_url = 'https://auth.mxit.com/'; $this->_base_user_api_url = 'http://api.mxit.com/user/'; $this->_base_messaging_api_url = 'http://api.mxit.com/message/'; $this->_app_key = $key; $this->_app_secret = $secret; $this->error = FALSE; } private function _call_api($url, $method='POST', $params='', $decode=TRUE) { $this->http_status = NULL; $this->content_type = NULL; $this->result = NULL; $this->error = FALSE; $fields = ''; if (($method == 'POST' || $method == 'PUT' || $method == 'DELETE') && $params != '') { $fields = (is_array($params)) ? http_build_query($params) : $params; } if ($method == 'PUT' || $method == 'POST' || $method == 'DELETE') { $this->_headers[] = 'Content-Length: '. strlen($fields); } $opts = array( CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_RETURNTRANSFER => true, CURLOPT_VERBOSE => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_TIMEOUT => 60, CURLOPT_USERAGENT => 'mxit-php-'. $this->_version, CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $this->_headers ); if (($method == 'POST' || $method == 'PUT' || $method == 'DELETE') && $params != '') { $opts[CURLOPT_POSTFIELDS] = $fields; } if ($method == 'POST' && is_array($params)) { $opts[CURLOPT_POST] = count($params); } elseif ($method == 'PUT') { $opts[CURLOPT_CUSTOMREQUEST] = 'PUT'; } elseif ($method == 'DELETE') { $opts[CURLOPT_CUSTOMREQUEST] = 'DELETE'; } elseif ($method == 'POST') { $opts[CURLOPT_POST] = TRUE; } $ch = curl_init(); curl_setopt_array($ch, $opts); $result = curl_exec($ch); $this->http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $this->content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); curl_close($ch); if ($this->http_status != 200) { // Problem with API call, we received an HTTP status code other than 200 $this->error = TRUE; } $this->result = (($decode === TRUE) && (is_json($result) === TRUE)) ? json_decode($result) : $result; } private function _api_headers($format='application/json') { $this->_headers = array(); $this->_headers[] = 'Content-type: '. $format; // Don't specify the accept format if data is being sent as an octet-stream if ($format == 'application/json' || $format == 'application/xml') $this->_headers[] = 'Accept: '. $format; $this->_headers[] = 'Authorization: '. ucfirst($this->_token_type) .' '. $this->_access_token; } private function _check_scope($method, $scope) { if (strstr($this->_scope, $scope) === FALSE) throw new Exception('Invalid scope specified for '. $method .'() method, should be: '. $scope); if (!isset($this->_access_token) || !isset($this->_token_type) || !isset($this->_expires_in)) throw new Exception('Access token is not set, obtain an access token using get_token()'); } /** * Requests the user to allow your application access to specific MXit information * * Redirects back to redirect_uri/?code=f00df00df00df00df00df00df00df00d * * Where the value of code (f00df00df00df00df00df00df00df00d in this example) * is used to obtain the access token. */ public function request_access($redirect_uri, $scope, $state='') { $url = $this->_base_outh_url ."authorize?response_type=code&client_id=". $this->_app_key; $url .= "&redirect_uri=". urlencode($redirect_uri); $url .= "&scope=". urlencode($scope); if ($state != '') $url .= '&state='. urlencode($state); header('Location: '. $url); exit; } /** * Authenticates the user against their MXit credentials * * SUCCESS: * Redirects back to redirect_uri/?code=f00df00df00df00df00df00df00df00d * * FAILURE: * Redirects back to redirect_uri/?error=access_denied * * Where the value of code (f00df00df00df00df00df00df00df00d in this example) * is used to obtain the access token. */ public function authenticate($redirect_uri, $state='') { $this->request_access($redirect_uri, 'openid', $state); } /** * Checks the authentication status from the authentication server callback */ public function authentication_status() { if (isset($_GET['code'])) { $authenticated = TRUE; } else { $authenticated = FALSE; $this->error = TRUE; } return $authenticated; } public function refresh_token() { $url = $this->_base_outh_url . "token"; $params = array( 'grant_type' => 'refresh_token', 'refresh_token' => $this->_refresh_token, ); $this->_headers = array(); $this->_headers[] = 'Authorization: Basic '. base64_encode($this->_app_key .':'. $this->_app_secret); $this->_headers[] = "Content-Type: application/x-www-form-urlencoded"; $this->_call_api($url, 'POST', $params); if ($this->error === FALSE) { $this->_access_token = $this->result->access_token; $this->_token_type = $this->result->token_type; $this->_expires_in = $this->result->expires_in; $this->_refresh_token = isset($this->result->refresh_token) ? $this->result->refresh_token : null; $this->_scope = $this->result->scope; // Only applicable to OpenID token requests if (isset($this->result->id_token)) $this->_id_token = $this->result->id_token; } } /** * Request the actual token from the OAuth2 server */ public function get_user_token($code, $redirect_uri) { $url = $this->_base_outh_url ."token"; $params = array('grant_type' => 'authorization_code', 'code' => $code, 'redirect_uri' => $redirect_uri); $this->_headers = array(); $this->_headers[] = 'Authorization: Basic '. base64_encode($this->_app_key .':'. $this->_app_secret); $this->_headers[] = "Content-Type: application/x-www-form-urlencoded"; $this->_call_api($url, 'POST', $params); if ($this->error === FALSE) { $this->_access_token = $this->result->access_token; $this->_token_type = $this->result->token_type; $this->_expires_in = $this->result->expires_in; $this->_refresh_token = isset($this->result->refresh_token) ? $this->result->refresh_token : null; $this->_scope = $this->result->scope; // Only applicable to OpenID token requests if (isset($this->result->id_token)) $this->_id_token = $this->result->id_token; } } /** * Get an access token for an application, to perform an API Request */ public function get_app_token($scope, $grant_type='client_credentials', $username='', $password='') { $url = $this->_base_outh_url ."token"; $this->_headers = array(); $this->_headers[] = 'Authorization: Basic '. base64_encode($this->_app_key .':'. $this->_app_secret); $this->_headers[] = "Content-Type: application/x-www-form-urlencoded"; $params = array('grant_type' => $grant_type, 'scope' => $scope); if ($grant_type == 'password') { $params['username'] = $username; $params['password'] = $password; } $this->_scope = $scope; $this->_call_api($url, 'POST', $params); if ($this->error === FALSE) { $this->_access_token = $this->result->access_token; $this->_token_type = $this->result->token_type; $this->_expires_in = $this->result->expires_in; $this->_refresh_token = isset($this->result->refresh_token) ? $this->result->refresh_token : null; } } /** * Get access token detail */ public function get_token() { $detail = array('access_token' => $this->_access_token, 'token_type' => $this->_token_type, 'expires_in' => $this->_expires_in, 'refresh_token' => $this->_refresh_token, 'scope' => $this->_scope); return $detail; } /** * Set access token detail */ public function set_token($detail) { $this->_access_token = $detail['access_token']; $this->_token_type = $detail['token_type']; $this->_expires_in = $detail['expires_in']; $this->_refresh_token = $detail['refresh_token']; $this->_scope = $detail['scope']; } /** * Validate OpenID token */ public function validate_token() { if (isset($this->_id_token)) { $token_parts = explode('.', $this->_id_token); $header = base64url_decode($token_parts[0]); $payload = base64url_decode($token_parts[1]); $signature = base64url_decode($token_parts[2]); if (is_json($header) && is_json($payload)) { $header = json_decode($header); $payload = json_decode($payload); if ($payload->aud != $this->_app_key) return FALSE; // Time zone differences could potentially pose a problem, so disabling for now /*if ($payload->exp < time()) return FALSE;*/ return $payload->user_id; } else { return FALSE; } } else { return FALSE; } } /** * ------------------------------------------------------------------------------ * The following methods are publicly available (no user authentication) required * so you should use the get_app_token() method when working with them. * ------------------------------------------------------------------------------- */ /** * Get the users internally unique UserId for the provided MxitId or LoginName. * * Url: http://api.mxit.com/user/lookup/{MXITID} * * Application Token Required * * Required scope: profile/public */ public function get_user_id($login) { $this->_check_scope('get_user_id', 'profile/public'); $url = $this->_base_user_api_url ."lookup/". $login; $this->_api_headers(); $this->_call_api($url, 'GET'); return $this->result; } /** * Get the status message for the given MXitId. * * Url: http://api.mxit.com/user/public/statusmessage/{MXITID} * * Application Token Required * * Required scope: profile/public */ public function get_status($login) { $this->_check_scope('get_status', 'profile/public'); $url = $this->_base_user_api_url ."public/statusmessage/". $login; $this->_api_headers(); $this->_call_api($url, 'GET'); return $this->result; } /** * Get the nickname of a MXit user with the given MXitId. * * Url: http://api.mxit.com/user/public/displayname/{MXITID} * * Application Token Required * * Required scope: profile/public */ public function get_display_name($login) { $this->_check_scope('get_display_name', 'profile/public'); $url = $this->_base_user_api_url ."public/displayname/". $login; $this->_api_headers(); $this->_call_api($url, 'GET'); return $this->result; } /** * Download the user avatar image for a MXit user with the given MXitId. * * Url: http://api.mxit.com/user/public/avatar/{MXITID} * * Application Token Required * * Required scope: profile/public */ public function get_avatar($login) { $this->_check_scope('get_avatar', 'profile/public'); $url = $this->_base_user_api_url ."public/avatar/". $login; $this->_api_headers(); $this->_call_api($url, 'GET', '', FALSE); return $this->result; } /** * Get the basic profile information for a MXit user with the given UserId. * * Url: http://api.mxit.com/user/profile/{USERID} * * Application Token Required * * Required scope: profile/public * * NOTE: This method requires the user's mxitid and NOT their login */ public function get_basic_profile($mxitid) { $this->_check_scope('get_basic_profile', 'profile/public'); $url = $this->_base_user_api_url ."profile/". $mxitid; $this->_api_headers(); $this->_call_api($url, 'GET'); return $this->result; } /** * Send a message to one or more MXit users. * Url: http://api.mxit.com/message/send/ * Application Token Required * Required scope: message/send or message/user * * @param string $from * @param string $to * @param string $message * @param boolean $contains_markup * @param array $links array of associative arrays * http://dev.mxit.com/docs/api/messaging/post-message-send * * <code> * $links = array( * array( * 'CreateTemporaryContact':true, * 'TargetService':'Service name', * 'Text':'Link text' * ); * ); * </code> * * @param boolean $spool * @param int $spool_timeout * * @return int error code see http://dev.mxit.com/docs/common-error-codes * for details */ public function send_message($from, $to, $message, $contains_markup=true, $links=array(), $spool=true, $spoolTimeOut=3600) { try { $this->_check_scope('send_message', 'message/send'); } catch(Exception $e) { $this->_check_scope('send_message', 'message/user'); } $params = array( 'Body' => $message, 'ContainsMarkup' => $contains_markup, 'From' => $from, 'To' => $to, 'Spool' => $spool, 'SpoolTimeOut' => $spoolTimeOut, ); if(count($links) > 0) { $params['Links'] = $links; } $url = $this->_base_messaging_api_url ."send/"; $this->_api_headers(); $this->_call_api($url, 'POST', json_encode($params)); } /** * ---------------------------------------------------------------------------------- * The following methods require authentication with the user's username and password * ----------------------------------------------------------------------------------- */ /** * Retrieves the full profile including the cellphone number and email address of the userid in the access token. * * User Token Required * * Required scope: profile/private */ public function get_full_profile($bypass_scope_check=FALSE) { if ($bypass_scope_check === FALSE) $this->_check_scope('get_full_profile', 'profile/private'); $url = $this->_base_user_api_url ."profile"; $this->_api_headers(); $this->_call_api($url, 'GET'); return $this->result; } /** * Update the profile information for a MXit user with the given UserId contained in the access token. * * Url: http://api.mxit.com/user/profile * * User Token Required * * Required scope: profile/write */ public function update_profile($data) { $this->_check_scope('update_profile', 'profile/write'); $url = $this->_base_user_api_url ."profile"; $this->_api_headers(); $this->_call_api($url, 'PUT', json_encode($data)); return $this->result; } /** * Subscribes the MXit user with the given UserId, contained in the access token, to the * service or sends an invite to another user. If {contact} is a Service, then the service * is added and accepted. If {contact} is a MXitId, then an invite is sent to the other user. * * User Token Required * * Required scope: contact/invite * * NOTE: This method requires the user's mxitid and NOT their login */ public function add_contact($mxitid) { $this->_check_scope('add_contact', 'contact/invite'); $url = $this->_base_user_api_url ."socialgraph/contact/". $mxitid; $this->_api_headers(); $this->_call_api($url, 'PUT'); } /** * Get the social graph information for a MXit user with the given UserId contained in the * access token. * * Filters: @All, @Friends, @Apps, @Invites, @Connections (Default), @Rejected, @Pending, @Deleted, @Blocked * * Url: http://api.mxit.com/user/socialgraph/contactlist?filter={FILTER}&skip={SKIP}&count={COUNT} * * User Token Required * * Required scope: graph/read * * NOTE: You might expect count to return 2 items if you specify a value of 2, but it will return 3 items * So you should treat the value similar to an array value, ie specify 1 if you want 2 results */ public function get_contact_list($filter='', $skip=0, $count=0) { $this->_check_scope('get_contact_list', 'graph/read'); $url = $this->_base_user_api_url ."socialgraph/contactlist"; if ($filter != '') $url .= '?filter='. $filter; if ($skip != 0) { $url .= ($filter == '') ? '?' : '&'; $url .= 'skip='. $skip; } if ($count != 0) { $url .= ($filter == '' && $skip == 0) ? '?' : '&'; $url .= 'count='. $count; } $this->_api_headers(); $this->_call_api($url, 'GET'); return $this->result; } /** * Get a list of friends the user might know for a MXit user with the given UserId contained in the access token. * * Url: http://api.mxit.com/user/socialgraph/suggestions * * User Token Required * * Required scope: graph/read * * FIXME: HTTP status 400 (Bad Request) */ public function get_friend_suggestions() { $this->_check_scope('get_friend_suggestions', 'graph/read'); $url = $this->_base_user_api_url ."socialgraph/suggestions"; $this->_api_headers('application/xml'); $this->_call_api($url, 'GET'); return $this->result; } /** * Set the status message for a MXit user with the given UserId contained in the access token. * * Url: http://api.mxit.com/user/statusmessage * * User Token Required * * Required scope: status/write */ public function set_status($message) { $this->_check_scope('set_status', 'status/write'); $url = $this->_base_user_api_url ."statusmessage"; $this->_api_headers(); $this->_call_api($url, 'PUT', json_encode($message)); } /** * Upload or create an avatar image for a MXit user with the given UserId contained in the access token. * * Url: http://api.mxit.com/user/avatar * * User Token Required * * Required scope: avatar/write */ public function set_avatar($data, $mime_type='application/octet-stream') { $this->_check_scope('set_avatar', 'avatar/write'); // Base64 encoding is deprecated if (is_base64($data)) { throw new Exception('Base64 encoding of avatar data is deprecated'); } else { $url = $this->_base_user_api_url ."avatar"; $this->_api_headers($mime_type); $this->_call_api($url, 'POST', $data); } } /** * Delete a avatar image for a MXit user with the given UserId contained in the access token. * * Url: http://api.mxit.com/user/avatar * * User Token Required * * Required scope: avatar/write */ public function delete_avatar() { $this->_check_scope('delete_avatar', 'avatar/write'); $url = $this->_base_user_api_url ."avatar"; $this->_api_headers(); $this->_call_api($url, 'DELETE'); } /** * Get the gallery root information for a MXit user with the given UserId contained in the access token. * * Url: http://api.mxit.com/user/media/ * * User Token Required * * Required scope: content/read */ public function list_gallery_folders() { $this->_check_scope('list_gallery_folders', 'content/read'); $url = $this->_base_user_api_url ."media/"; $this->_api_headers(); $this->_call_api($url, 'GET'); return $this->result; } /** * Get the list of content in the gallery folder for a user with the given UserId contained in the access token and FolderId. * * Url: http://api.mxit.com/user/media/list/{FOLDERNAME}?skip={SKIP}&count={COUNT} * * User Token Required * * Required scope: content/read */ public function list_gallery_items($folder, $skip=0, $count=0) { $this->_check_scope('list_gallery_items', 'content/read'); $url = $this->_base_user_api_url ."media/list/". urlencode($folder); if ($skip != 0) { $url .= '?skip='. $skip; } if ($count != 0) { $url .= ($filter == '' && $skip == 0) ? '?' : '&'; $url .= 'count='. $count; } $this->_api_headers(); $this->_call_api($url, 'GET'); return $this->result; } /** * Creates a gallery folder for a MXit user with the given UserId contained in the access token. * * Url: http://api.mxit.com/user/media/{FOLDERNAME} * * User Token Required * * Required scope: content/write */ public function create_gallery_folder($folder) { $this->_check_scope('create_gallery_folder', 'content/write'); $url = $this->_base_user_api_url ."media/". urlencode($folder); $this->_api_headers(); $this->_call_api($url, 'POST'); } /** * Rename a gallery folder for a MXit user with the given UserId contained in the access token. * * Url: http://api.mxit.com/user/media/{FOLDERNAME} * * User Token Required * * Required scope: content/write */ public function rename_gallery_folder($source, $destination) { $this->_check_scope('rename_gallery_folder', 'content/write'); $url = $this->_base_user_api_url ."media/". urlencode($source); $this->_api_headers(); $this->_call_api($url, 'PUT', json_encode($destination)); } /** * Delete a gallery folder for a MXit user with the given UserId contained in the access token. * * Url: http://api.mxit.com/user/media/{FOLDERNAME} * * User Token Required * * Required scope: content/write */ public function delete_gallery_folder($folder) { $this->_check_scope('delete_gallery_folder', 'content/write'); $url = $this->_base_user_api_url ."media/". urlencode($folder); $this->_api_headers(); $this->_call_api($url, 'DELETE'); } /** * Download the content item in the user's gallery for a MXit user with the given UserId contained in the access token and given FileId. * * Url: http://api.mxit.com/user/media/content/{FILEID} * * User Token Required * * Required scope: content/read */ public function download_gallery_image($file_id) { $this->_check_scope('download_gallery_image', 'content/read'); $url = $this->_base_user_api_url ."media/content/". $file_id; $this->_api_headers(); $this->_call_api($url, 'GET', '', FALSE); return $this->result; } /** * Upload a gallery file for a MXit user with the given UserId contained in the access token. * * CURRENT: * Url: http://api.mxit.com/user/media/file/{FOLDERNAME}?fileName={FILENAME} * * DEPRECATED: * Url: http://api.mxit.com/user/media/file/{FOLDERNAME}?fileName={FILENAME}&mimeType={MIMETYPE} * * User Token Required * * Required scope: content/write */ public function upload_gallery_image($folder, $filename, $mime_type, $data) { $this->_check_scope('upload_gallery_image', 'content/write'); // Base64 encoding is deprecated if (is_base64($data)) { throw new Exception('Base64 encoding of gallery data is deprecated'); } else { $url = $this->_base_user_api_url ."media/file/". urlencode($folder) .'?fileName='. urlencode($filename); $this->_api_headers($mime_type); $this->_call_api($url, 'POST', $data); } } /** * Rename a gallery file for a MXit user with the given UserId contained in the access token. * * Url: http://api.mxit.com/user/media/file/{FILEID} * * User Token Required * * Required scope: content/write */ public function rename_gallery_image($file_id, $destination) { $this->_check_scope('rename_gallery_image', 'content/write'); $url = $this->_base_user_api_url ."media/file/". urlencode($file_id); $this->_api_headers(); $this->_call_api($url, 'PUT', json_encode($destination)); } /** * Rename a gallery file for a MXit user with the given UserId contained in the access token. * * Url: http://api.mxit.com/user/media/file/{FILEID} * * User Token Required * * Required scope: content/write */ public function delete_gallery_image($file_id) { $this->_check_scope('delete_gallery_image', 'content/write'); $url = $this->_base_user_api_url ."media/file/". urlencode($file_id); $this->_api_headers(); $this->_call_api($url, 'DELETE'); } /** * Upload a file of any type to store and return a FileId once file offer has been sent * * CURRENT: * Url: http://api.mxit.com/user/media/file/send?fileName={FILENAME}&userId={USERID} * * DEPRECATED: * Url: http://api.mxit.com/user/media/file/send?fileName={FILENAME}&mimeType={MIMETYPE}&userId={USERID} * * User Token Required * * Required scope: content/send */ public function send_file($user_id, $filename, $mime_type, $data) { $this->_check_scope('send_file', 'content/send'); // Base64 encoding is deprecated if (is_base64($data)) { throw new Exception('Base64 encoding of gallery data is deprecated'); } else { $url = $this->_base_user_api_url ."media/file/send?fileName=". urlencode($filename) .'&userId='. urlencode($user_id); $this->_api_headers($mime_type); $this->_call_api($url, 'POST', $data); } } } ?>
  17. Hi there! I need some assistance. I'm a PHP noob and have been given a project to build a php 'calculator' for a client. Basically what needs to happen is the following - I have a table with predefined values, they are all numbers. The user will go to a form and add a number, this number then needs to be compared to the first column of the table after which it then needs to display only that row's values. As the numbers are predefined in the table the number the user enters then also needs to be rounded off to the nearest value found in the table. I've searched the internet and found snippets of code but can't quite understand how to put everything together. I understand how it should work, but just can't get there. I hope this all makes sense. If there is anyone who can help I would appreciate it a lot! Thanks
  18. I want to create a drop down menu that display main categories then all child categories with all of their sub child list like the one shown in below pic I am using a table named categories which uses hierarchical system like parent id, right id, left id and level looks like in below pic here is my categoriesTest.php <?php include 'common.php'; $query = "SELECT cat_id, parent_id, cat_name FROM " .$DBPrefix. "categories ORDER BY cat_name"; $res = mysql_query($query); $system->check_mysql($res, $query, __LINE__, __FILE__); $items = mysql_fetch_assoc($res); $html = ''; $parent = 0; $parent_stack = array(); // $items contains the results of the SQL query $children = array(); foreach ( $items as $item ) $children[$items['parent_id']][] = $item; while ( $option = each( $children[$parent] ) ) { if ( !empty( $option ) ) { // 1) The item contains children: // store current parent in the stack, and update current parent if ( !empty( $children[$option['value']['id']] ) ) { $html .= '<li>' . $option['value']['title'] . '</li>'; $html .= '<ul>'; array_push( $parent_stack, $parent ); $parent = $option['value']['id']; } // 2) The item does not contain children else $html .= '<li>' . $option['value']['title'] . '</li>'; } // 3) Current parent has no more children: // jump back to the previous menu level else { $html .= '</ul>'; $parent = array_pop( $parent_stack ); } } // At this point, the HTML is already built echo $html; ?> the above code not working and am not sure it is the correct way. can anyone help me out?? Thanks
  19. I am retriving records from mysql database that has expiry time limit. The time in the database is saved in "minutes". So for one hour, it'll be "3600" minutes. That's all fine. Now what I am trying to do is create a countdown clock using Javascript/jquery and I have ran into a bit of a problem. 1. I am retriving multiple records from the database that all have a countdown timer. Currently, it's only taking the time value of the first record and using that for all the records. I would like to know how I can make it so that each record will have it's own countdown timer value? 2. Everytime I refresh a page, it will reset the timer. How can I fix this? Here's my code. <?php foreach($rows as $row) { $get_expiry_time = $row['expiry_time']; <div class="record"> <div class="timer"> </div> </div> } ?> <script> $(document).ready(function(){ var countDownTime = <?php echo $get_expiry_time; ?>; function countDownTimer() { var hours = parseInt( countDownTime / 3600 ) % 24; var minutes = parseInt( countDownTime / 60 ) % 60; var seconds = countDownTime % 60; var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds); $('.timer').html(result); if(countDownTime == 0 ){ countDownTime = 60*60*60; } countDownTime = countDownTime - 1; setTimeout(function(){ countDownTimer() }, 1000); } countDownTimer(); }); </script>
  20. Hi I'm currently using a header to retrieve some info $prof = $_SERVER["HTTP_X_MXIT_PROFILE"]; It output the value as en,ZA,1991-01-30,Male,1 I'm trying to use the 1991-01-30 from the above output to calculate if the person is 18 years of age or older Any suggestions on how to do this I tried to put it into an array but was unsuccessful...
  21. Basically what I am trying to do is have an option of choosing an "expiry time" when inserting a record. I will then use that expiry time to make a countdown clock that will expire the record when reached 0; but that's the step after. Right now I am having a bit of issue inserting that expiry time into the database. Here is my code. The error i get in the option value is something like <option value="<b>Notice</b>: Undefined variable...">. <?php $date_added = date('Y-m-d H:i:s'); $expiry_1 = date('Y-m-d H:i:s', strtotime('$date_added + 1 hour')); $expiry_6 = date('Y-m-d H:i:s', strtotime('$date_added + 6 hours')); $expiry_12 = date('Y-m-d H:i:s', strtotime('$date_added + 12 hours')); ?> <fieldset> <label>Expiry Time</label> <select name="expiry_time"> <option value="0">Select Time</option> <option value="<?php echo $expiry_1; ?>">1 hour</option> <option value="<?php echo $expiry_6; ?>">6 hours</option> <option value="<?php echo $expiry_12; ?>">12 hours</option> </select> </fieldset>
  22. Hello Forum: I smoked down the Google servers on this one and didn't come up with what I'm looking for. I have a MySQL table that stores a couple fields, one of them being a date field (set by CURDATE()) when it was written to the table. I'm trying to use the PHP date() and the sql field to find the number of days that's elapse, but I can't seem to get that to work for me. Here's what I'm working with: $stmt = $db->prepare('SELECT a.attendeeid, s.attendeeid, fname, lname, suspend, reason, sdate, a.memberid, s.memberid FROM attendees AS a JOIN suspended AS s ON a.attendeeid = s.attendeeid WHERE a.memberid = :memberid AND suspend = "Y"'); $stmt->bindValue(':memberid', $memberid, PDO::PARAM_INT); $stmt->execute(); $result = $stmt->fetchAll(); ?> <div class="row"> <div class="table-repsonsive"> <table class="table table-bordered table-hover table-striped" style="margin-top:30px"> <thead> <tr> <th style="text-transform: uppercase">First</th> <th style="text-transform: uppercase">Last</th> <th style="text-transform: uppercase">Suspended</th> <th style="text-transform: uppercase">Suspension Date</th> <th style="text-transform: uppercase">Days on suspension</th> <th style="text-transform: uppercase">Reason</th> </tr> </thead> <?php foreach($result as $row ) { $i++; ?> <tbody> <?php echo '<tr style="'.getbgc($i). '">' ?> <td style="width:auto;"><?php echo $row[2] ?></td> <td style="width:auto;"><?php echo $row[3] ?></td> <td style="width:auto;"><?php echo $row[4] ?></td> <td style="width:auto;"><?php echo $row[6] ?></td> <td style="width:auto;"><?php echo strtodate(date('Y-m-d')) - $row[6] ?></td> // This is not working <td style="width:auto;"><?php echo $row[5] ?></td> $row[6] holds sdate from the query. Does anyone know how I can do this? Thanks.
  23. Hi I'm currently having a syntex error with my bad words filter function function filterBadWords($str) { $result1 = mysql_query("SELECT word FROM StringyChat_WordBan") or die(mysql_error()); $replacements = "x"; while($row = mysql_fetch_assoc($result1)) { $str = preg_replace('/\b' . $row['word'].'\b/ie', ':-x', $str); } return $str; } I know its the :-x part causing the problem but how can I fix it? and is there maybe a better way to do the filter because if I got the word "ass" in my list it will replace assassinate to :-x :-xinate ?
  24. i have this array: test={'dog','cow','shee'}; how can I pass it to a stored procedure: call sp_array(in i_arr1 text); what data type should I use? Iam currently looping through and multi executing the procedure in php to pass the values one by one .But is there a way to pass it to the procedure and then assign it to a cursor in sql.
  25. I tried to solve problem, but without success, so I am here to seek for some help. I have folder on web server, that contains subfolders and pdf files. I need PHP script that monitors folder and subfolders and create XML for RSS feed on site homepage whe new files are added to folders. Site is on local network only, it is not accesible via Internet. I tried number of scripts but without success. Any advice please?
×
×
  • Create New...

Important Information

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