PHP - Sending Post To A Page With Http Auth
Hi there,
Any help is greatly appreciated. I've commented out the code giving me trouble. Error = <br /> <b>Warning</b>: curl_setopt(): supplied argument is not a valid cURL handle resource in <b>/###.php</b> on line <b>34</b><br /> <br /> <b>Warning</b>: curl_setopt(): supplied argument is not a valid cURL handle resource in <b>/###.php</b> on line <b>35</b><br /> <?php $ch = curl_init(); $timeout = 30; $userAgent = $_SERVER['HTTP_USER_AGENT']; if ($_REQUEST['update']) { curl_setopt($ch, CURLOPT_URL, $_REQUEST['url']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_USERPWD, $_REQUEST['username'] . ':' . $_REQUEST['password']); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); //curl_setopt($c, CURLOPT_POST, true); //curl_setopt($c, CURLOPT_POSTFIELDS, $_REQUEST['update']); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); $response = curl_exec($ch); if (curl_errno($ch)) { echo curl_error($ch); } else { curl_close($ch); echo $response; } } Similar TutorialsI'm new to PHP, XML, and web development in general, so please bear with me... I'm working in a PHP environment and need to send user credentials $username and $password in XML via a HTTP post. Does that even make sense? Let me explain: I have already successfully used a method of capturing credentials, and they can be called by the use of $username and $password. I need to pass these on to an XML web service on another domain, but they need to be included in a larger piece of XML. To top it all off, I need this process to occur only when an image in a page is clicked. Here is the XML that needs to be sent (except that $username and $password are my strings from above): <xml-fragment xmlns:vp="http://my.host.com/somedirectory"> <vp:vprequest> <query>authenticateUser</query> </vp:vprequest> <vp:vpuser> <username>$username</username> <password>$password</password> <userid/> <firstname/> <lastname/> <useremail/> <assignedRoles> <roleDef/> </assignedRoles> </vp:vpuser> <vportal> <vportal_id>1</vportal_id> </vportal> </xml-fragment> I need to send it to: https://my.host.com/xmlwebapp Anything sending to the XML Web App must pass their XML data with the content type set to application/xml. I'm confused with how I should be sending this. I believe that the XML APP can receive HTTP POST, but I don't know how to write that code into PHP and then have it send it all as XML. Any help would be appreciated! Thank you! Hi Guys, This is my first post as part of the community. I am working on a personal project for myself and was trying to password protect some pages. Im newish to php and was wondering if HTTP AUTH headers work with MYSQL Databases for usernames and passwords. Any help or insight would be greatly appreciated! Thanks! Steve I need to send two cookie name/value pairs to the page I am trying to open using file_get_contents, in order for the person viewing the page to have associated dynamic content, but it isn't working, and I'm wondering if I'm setting it up right: if(isset($_COOKIE['bwd_data']) && isset($_COOKIE['bwd'])){ $cookie_val = $_COOKIE['bwd_data']; $cookie_val2 = $_COOKIE['bwd']; $opts = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "Cookie: bwd_data=" . $cookie_val . "\r\n" . "Cookie: bwd=" . $cookie_val2 ) ); $context = stream_context_create($opts); echo(file_get_contents(url::site('httperrors','http'), FALSE , $context)); }else{ echo(file_get_contents(url::site('httperrors','http'))); } Some background we are creating a system that collects rain data from multiple sensors and then every 15 mins sends a packet to the main server. I have been ingesting this data fine and storing the info into my database and storing a local .txt file of the packet. To forward this packet to our back up server I have been using: shell_exec("nc backup_server_address < ".$my_p); Where $my_p is the location of the .txt file. However, I have been requested to not use nc as it creates its own process every time it is called and for scalability issues we would like to forward the packet using PHP and not require a new process every time we receive a packet. I tried do some redirect stuff using headers("Location: backup_server_address"). If anyone can help that would be greatly appreciated. I have been using curl and curl_multi, but it takes about 500ms between each query. I am sending for example https://www.apidomain.com/user=test&pass=test It then should return an output of successful or unsuccessful. How can I do this to run the url in a loop of 10 iterations, without curl, but with the speed of a millisecond or less? Thanks! Hi, I'm trying to get HTTP post to work on my server but even the most basic script does not work. Can anyone help me? PHP script: <?php echo 'Hello ' . htmlspecialchars($_POST["name"]) . '!'; ?> I try and POST data to the script using: http://www.czoryk.co.uk/post_test.php?name=Chris But when I try and do that only ' Hello ! ' is displayed. I'm sure this is just a simple error but I can't figure out what's wrong. Thanks, Chris I am testing a url for http post request. It connects to the site then it is disconnected. In fire fox it is giving error that the "connection was reset". In google chrome it is giving error that "Unable to load the webpage because the server sent no data". Following is the script. I am new to curl and also new to http request response. The provider of this site tells me that everything is ok and it is sending data but i am not getting any data or any header of this site. <?php $data = '<?xml version="1.0" encoding="UTF-8"?><Request><Source ClientID="test_xml" Password="1234" /><RequestDetails Language="En"><SearchHotelPriceRequest><ServiceDestination DestinationType="city" DestinationCode="477" /><ImmediateConfirmationOnly>1</ImmediateConfirmationOnly><PeriodOfStay><CheckInDate>2012-03-01</CheckInDate><Duration>3</Duration></PeriodOfStay><Rooms> <Room NumberOfRooms="1" NumberOfAdults="2" /> </Rooms></SearchHotelPriceRequest></RequestDetails></Request>'; $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, 'https://62.218.28.13:8443/monWebService/Request/v2'); curl_setopt($ch, CURLOPT_POST, $data); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $data = curl_exec($ch); curl_close ($ch); echo $data; ?> Trying to run a simple program that, when submitted, stores the username and password as cookies. When clicking Submit, I get the error "HTTP Error 405 - The HTTP verb used to access this page is not allowed". If the username and password fields are left blank when submitting it's suppose to give a message to enter a username and password, but, I still get that error message. HTML form: Code: [Select] <!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" xml:lang="en" lang="en"> <head> <title>Week 1 Project--Cookies</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> <form action="cookie1.php" method="post"> <h2 align="center">Cookies</h2> <br /> <div> <p>Enter your username and password and click "Submit":</p><br /> <p>Username:<input type="text" name="username" size="20"></p> <p>Password:<input type="text" name="password" size="20"></p> </div> <br /> <div><input type="submit" name="submit" value="Submit" /></div> <br /> <div> <input type="reset" name="Reset" value="Start Over" /> </div> </form> </body> </html> PHP file: Code: [Select] <!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" xml:lang="en" lang="en"> <head> <title>Cookie File</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> <div> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { setcookie('username', $_POST['username'], time() + 2592000); setcookie('password', $_POST['password'], time() + 2592000); } if(($_POST['username'] == "") || ($_POST['password'] == "")) { print "You must enter both a username and password. Press the Back button on your browser and try again."; } else if (isset($_COOKIE['username'])) { print "Welcome, " .$_COOKIE['username']; } ?> </div> </body> </html> Hello there,
I am coding Arduino micro controller, and intended to GET the data from server MySQL db through php to turn ON/OFF LED. I could able to GET the data from manually updated MySQL db value, even I could able to successfully change the data of MySQL db from micro controller POST method. But I am getting error when trying to change the MySQL db value from browser using online POST tool, Following is PHP code at server 8 $api_key_value ="XXXXXXXXX";//Sample 9 $api_key =""; 10 $status = ""; 11 $id =""; 12 13 if ($_SERVER["REQUEST_METHOD"] == "POST") { 14 $api_key = test_input($_POST["api_key"]); 15 if($api_key == $api_key_value) { $id = test_input($_POST["id"]); $status = test_input($_POST["status"]); // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //$sql = "INSERT INTO led (status) //VALUES ('" . $status . "')"; $sql = "UPDATE led SET status='$status' WHERE id='$id'"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); } else { echo "Wrong API Key provided."; } } else { echo "No data posted with HTTP POST."; } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } Post Command: http://url/MySQL_POST.php?api_key=XXXXXXXXX&id=1&status=on Response/Error: Notice: Undefined index: api_key in <PATH>/MySQL_POST.php on line 14 Wrong API Key provided. Could be a basic issue, but I am very new to php coding and cannot solve this problem yet. Could someone please help? Thanks.
Hello, I am a newbie regarding PHP and have done mostly only front-end web design for a couple of years and recently started querying DB's and displaying the data, but now this is a new project.
I've tested code snippets as the ones below, but fail to incorporate them in the bigger picture of what I'm trying to achieve. <?php // https://gist.github.com/magnetikonline/650e30e485c0f91f2f40 class DumpHTTPRequestToFile { public function execute($targetFile) { $data = sprintf( "%s %s %s\n\nHTTP headers:\n", $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL'] ); foreach ($this->getHeaderList() as $name => $value) { $data .= $name . ': ' . $value . "\n"; } $data .= "\nRequest body:\n"; file_put_contents( $targetFile, $data . file_get_contents('php://input') . "\n" ); echo("Done!\n\n"); } private function getHeaderList() { $headerList = []; foreach ($_SERVER as $name => $value) { if (preg_match('/^HTTP_/',$name)) { // convert HTTP_HEADER_NAME to Header-Name $name = strtr(substr($name,5),'_',' '); $name = ucwords(strtolower($name)); $name = strtr($name,' ','-'); // add to list $headerList[$name] = $value; } } return $headerList; } } (new DumpHTTPRequestToFile)->execute('./dumprequest.csv'); This snippet also seems to return the headers and their values but I don't know how to efficiently write and append it to a TXT or CSV, or preferably, directly into a MySQL database. <?php foreach (getallheaders() as $name => $value) { echo "$name: $value"; echo "<br>"; } ?>
Any help towards storing the header values of HTTP POST requests into a database would be greatly appreciated! I've looked at various cURL tutorials and the PHP manual, but I don't see what I'm doing wrong here. My goal is to be able to send data to test.php and then have that page run a MySQL query to insert the TITLE and MESSAGE into the database. Any comments? :/ post.php <?php if(isset($_GET['title']) && isset($_GET['message']) && isset($_GET['times'])) { $array = array('title' => urlencode($_GET['title']), 'message' => urlencode($_GET['message'])); foreach($array as $key => $value) { $fields = $key.'='. $value .'&'; } rtrims($felds); //set our init handle $curl_init = curl_init(); //set our URL curl_setopt($curl_init, CURLOPT_URL, 'some url'); //set the number of fields we're sending curl_setopt($curl_init ,CURLOPT_POST, count($array)); for($i = 0; $i < $_GET['times']; $i++) { //send the POST data curl_setopt($curl_init, CURLOPT_POSTFIELDS, $fields); curl_exec($curl_init); echo 'post #'.$i. ' sent<br/>'; } //complete echo '<b>COMPLETE</b>'; //close session curl_close($curl_init); } else { ?> <form action="post.php" method="GET"> <table> <tr><td>Title</td><td><input type="text" name="title" maxlength="30"></td></tr> <tr><td>Content</td><td><textarea name="message" rows="20" cols="45" maxlength="2000"></textarea></td></tr> <tr><td>Process Amount</td><td><input type="text" name="times" size="5" maxlength="3"></td></tr> <tr><td>START</td><td><input type="submit" value="Initiate Posting"></td></tr> </table> </form> <?php } ?> test.php <?php mysql_connect('host', 'user', 'pass'); mysql_select_db('somedb'); if($_POST['title'] && $_POST['message']) { mysql_insert("INSERT INTO tests VALUES (null, '{$_POST['title']}', '{$_POST['message']}')"); } echo '<hr><br/>'; //query $query = mysql_query("SELECT * FROM tests ORDER BY id DESC"); while($row = mysql_fetch_assoc($query)) { echo $row['id'].'TITLE: '. $row['title'] .'<br/>MESSAGE: '. $row['message'] .'<br/><br/>'; } ?> I'm a total noob at PHP, and need to make a simple authentication server-side script for a Java application that is in no way associated with the server. My Java app URL encodes in this format(pretty standard): "key1"="value1" I THINK I have the correct code in PHP to read the HTTP POST data values... Code: [Select] $username = array("1", 2, 3, 4, 5); $match = FALSE; foreach($_POST as $key1 => $value1){ foreach($username as $key2 => $value2){ if ($value1 == $value2){ $match = TRUE; break; } } if ($match = TRUE) break; } After all this I'd like to send a response saying either TRUE or FALSE(in other words, I'd like to send the variable $match). I've looked far and wide for how to do this in PHP, and couldn't find a single helpful page. I have tried to make a redirect like this: redir.php?page=http://****.com Code: [Select] <?php if(is_file($_GET['page'])){$page = $_GET['page'];} else{$page = "DEFAULT.php";} header("Location: ".$page); ?> But I only get: Quote Forbidden You don't have permission to access /redir.php on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. What should I do? Could it have something to do with encoding of special characters? Ordinary php scripts like Code: [Select] <?php echo "Hello"; ?> Works fine. Some code from my pages ,
Page1 ( Redirecting page )
<html> <title>login_redirect.</title> body> <form name="redirect" action="http://mysite/page2.php" method="post"> <input type="hidden" name="mac" value="$(mac)"> </form> <script language="JavaScript"> <!-- document.redirect.submit(); //--> </script> </body> </html>Page 2 ( select product ) <?php session_start(); ini_set('display_errors',1); error_reporting(E_ALL); include '../lib/config.php'; include '../lib/opendb.php'; // get user mac adres from redirect post page1 $_SESSION['macid'] = $_POST['mac']; // set $macid for other use ( maybe not needed, am learning ) $macid = $_SESSION['macid']; // echo $macid does show mac adress, so variable is not empty here if (!empty($_POST["submit"])) { $product_choice = $_POST['accounttype']; $query= "SELECT AccountIndex, AccountCost, AccountName FROM AccountTypes WHERE AccountIndex='$product_choice'"; $result = mysql_query($query) or die('Query failed. ' . mysql_error()); while($row = mysql_fetch_array($result)) { $_SESSION['AccountIndex'] = $row['AccountIndex']; $_SESSION['AccountCost'] = $row['AccountCost']; $_SESSION['AccountName'] = $row['AccountName']; } header('Location: page3.php'); } // did leave out the other/html/form stuff herePage 3 ( show Session variables ) <?php ini_set('display_errors',1); error_reporting(E_ALL); session_start(); print_r($_SESSION); ?>Now, on page 3 i do see the right session varables, only the "macid" is empty. why ? Hi I am using facebook auth but email id not fetching from facebook login please help me why is happening? i have problem : I have a page(page1) that sends details to the login page(page2) to check if the details are correct checks these and if there is a match it directs them to the next page.(page 3) The page1 sends 3 details to the page 2 that are stored into variavles but as there is no submittion when they check the details how do i then send these details onto the page 3 ? Ok So the main purpose of this is: 1). User has to grab a OTP from the generator (work's) 2) the OTC updates in the database field (work's) via the person's user_email 3). it sends an email containing the OTP what it is not doing is, when they go and login, it just keeps saying invalid login credentials. I'm pasting my code below to see if anyone can help me out here. this is still a work in progress. do_login.php (not working here) Keep's saying invalid password. <?php if(empty($_POST)) exit; include 'config.php'; // declare post fields $post_user_email = trim($_POST['user_email']); $post_password = trim($_POST['authcode']); $post_autologin = $_POST['autologin']; if(($post_user_email == $config_email) && ($post_password == $config_password)) { $_SESSION['Site-Key'] = $config_email; // Autologin Requested? if($post_autologin == 1) { $password_hash = md5($config_password); // will result in a 32 characters hash setcookie ($cookie_name, 'usr='.$config_email.'&hash='.$password_hash, time() + $cookie_time); } exit('OK'); } else { echo '<div id="error_notification">The submitted login info is incorrect.</div>'; } ?> Index.php <?php require_once 'config.php'; if(isset($_SESSION['google-ads123123'])) { header("Location: http://forum.site1.com"); exit; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Access Required</TITLE> <script type="text/javascript" src="js/mootools-1.2.1-core-yc.js"></script> <script type="text/javascript" src="js/process.js"></script> <link rel="stylesheet" type="text/css" href="style.css" /> </HEAD> <BODY> <center> <div id="status"> <fieldset><legend align="center">Authentication</legend> <div id="login_response"><!-- spanner --></div> <form id="login" name="login" method="post" action="do_login.php"> <table align="center" width="200" border="0"> <tr> <td width="80">Email</td><td><input id="user_email" type="text" name="user_email"></td> </tr> <tr> <td>AuthCode:</td> <td><input type="password" name="authcode"></td> </tr> <tr> <td> </td> <td><input type="checkbox" name="autologin" value="1">Remember Me</td> </tr> <tr> <td> </td> <td><input id="submit" type="submit" name="submit" value="Login"> <br /> <a href="getcode.php"> Get Auth Code </a> <div id="ajax_loading"><img align="absmiddle" src="images/spinner.gif"> Processing...</div></td> </tr> </table> </form> </fieldset> </div> </center> </BODY> </HTML> getcode.php (generates a MD5 and adds into db) <?php $db_host = '123'; $db_username = '123'; $db_password = '123'; $db_name = '123'; @mysql_connect($db_host, $db_username, $db_password) or die(mysql_error()); @mysql_select_db($db_name) or die(mysql_error()); // This is displayed if all the fields are not filled in $empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>Click <a class=\"two\" href=\"javascript:history.go(-1)\">here</a> to go back"; // Convert to simple variables $email_address = $_POST['user_email']; if (!isset($_POST['user_email'])) { ?> <h2>Generate your Auth Code</h2> <form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>"> <p class="style3"><label for="user_email">Email:</label> <input type="text" title="Please enter your email address" name="user_email" size="30"/></p> <p class="style3"><label title="Generate Auth Code"> </label> <input type="submit" value="Submit" class="submit-button"/></p> </form> <?php } elseif (empty($email_address)) { echo $empty_fields_message; } else { $status = "OK"; $msg=""; //error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR); if (!stristr($email_address,"@") OR !stristr($email_address,".")) { $msg="Your email address is not correct<BR>"; $status= "NOTOK";} echo "<br><br>"; if($status=="OK"){ $query="SELECT username FROM users WHERE user_email = '$email_address'"; $st=mysql_query($query); $recs=mysql_num_rows($st); $row=mysql_fetch_object($st); $em=$row->user_email;// email is stored to a variable if ($recs == 0) { echo "<center><font face='Verdana' size='2' color=red><b>No Auth Code</b><br> Sorry Your address is not in our database ."; exit;} function makeRandomPassword() { $salt = "abchefghjkmnpqrstuvwxyz0123456789"; srand((double)microtime()*1000000); $i = 0; while ($i <= 7) { $num = rand() % 33; $tmp = substr($salt, $num, 1); $pass = $pass . $tmp; $i++; } return $pass; } $random_password = makeRandomPassword(); $db2_password = md5($random_password); $sql = mysql_query("UPDATE users SET authcode='$db2_password' WHERE user_email='$email_address'"); $subject = "Auth Code Verification"; $message = " Here is your Auth Code, Auth Code: $random_password Auth Code: $db2_password This is an automated response, please do not reply!"; mail($email_address, $subject, $message, "From: Auth Server<theslcguy@safe-mail.net.com>"); echo "Your Auth Code has been sent! <br /> Please check your email! <br /> Also Allow up to 5 minutes to recieve your Code...<br />"; echo "<br><br>Click <a href='http://auth.site1.com'>here</a> to login"; } else { echo "<center><font face='Verdana' size='2' color=red >$msg <br><br><input type='button' value='Retry' onClick='history.go(-1)'></center></font>";} } ?> Config.php <?php session_start(); // Start Session header('Cache-control: private'); // IE 6 FIX // always modified header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT'); // HTTP/1.1 header('Cache-Control: no-store, no-cache, must-revalidate'); header('Cache-Control: post-check=0, pre-check=0', false); // HTTP/1.0 header('Pragma: no-cache'); // ---------- LOGIN INFO ---------- // $config_email = $POST["user_email"]; $config_authcode = $POST["authcode"]; $cookie_name = 'google-ads123123'; $cookie_time = (3600 * 24 * 30); // 30 days if(!$_SESSION['google-ads123123']) { include_once 'autologin.php'; } ?> I'm making a login/sign up page and the following pieces are not working together properly. When I set up the login page following a guide, it had me direct input the structure and I added a user (password is encrypted). When I log in with that password/username, it passes authentication.php perfectly. When I use my signup form (signup.php is simply called by a button on an HTML), it fails saying "Incorrect Password!". I'd say it's failing because of encryption but it passes with my old login that is encrypted so I'm thoroughly lost. Authentication.php <?php session_start(); // Change this to your connection info. $DATABASE_HOST = 'localhost'; $DATABASE_USER = 'root'; $DATABASE_PASS = 'test'; $DATABASE_NAME = 'login'; // Try and connect using the info above. $con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME); if ( mysqli_connect_errno() ) { // If there is an error with the connection, stop the script and display the error. die ('Failed to connect to MySQL: ' . mysqli_connect_error()); } // Now we check if the data from the login form was submitted, isset() will check if the data exists. if ( !isset($_POST['username'], $_POST['password']) ) { // Could not get the data that should have been sent. die ('Please fill both the username and password field!'); } // Prepare our SQL, preparing the SQL statement will prevent SQL injection. if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) { // Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s" $stmt->bind_param('s', $_POST['username']); $stmt->execute(); // Store the result so we can check if the account exists in the database. $stmt->store_result(); if ($stmt->num_rows > 0) { $stmt->bind_result($id, $password); $stmt->fetch(); // Account exists, now we verify the password. // Note: remember to use password_hash in your registration file to store the hashed passwords. if (password_verify ($_POST['password'], $password)) { // Verification success! User has loggedin! // Create sessions so we know the user is logged in, they basically act like cookies but remember the data on the server. session_regenerate_id(); $_SESSION['loggedin'] = TRUE; $_SESSION['name'] = $_POST['username']; $_SESSION['id'] = $id; header('Location: dashboard.php'); } else { echo 'Incorrect password!'; } } else { echo 'Incorrect username!'; } $stmt->close(); } ?>
Signup.php <?php // get database connection include_once '../config/database.php'; // instantiate user object include_once '../objects/user.php'; $database = new Database(); $db = $database->getConnection(); $user = new User($db); // set user property values $user->username = $_POST['uname']; $user->password = base64_encode($_POST['password']); $user->created = date('Y-m-d H:i:s'); // create the user if($user->signup()){ $user_arr=array( "status" => true, "message" => "Successfully Signup!", "id" => $user->id, "username" => $user->username ); } else{ $user_arr=array( "status" => false, "message" => "Username already exists!" ); } print_r(json_encode($user_arr)); ?>
login.php <?php // include database and object files include_once '../config/database.php'; include_once '../objects/user.php'; // get database connection $database = new Database(); $db = $database->getConnection(); // prepare user object $user = new User($db); // set ID property of user to be edited $user->username = isset($_GET['username']) ? $_GET['username'] : die(); $user->password = base64_encode(isset($_GET['password']) ? $_GET['password'] : die()); // read the details of user to be edited $stmt = $user->login(); if($stmt->rowCount() > 0){ // get retrieved row $row = $stmt->fetch(PDO::FETCH_ASSOC); // create array $user_arr=array( "status" => true, "message" => "Successfully Login!", "id" => $row['id'], "username" => $row['username'] ); } else{ $user_arr=array( "status" => false, "message" => "Invalid Username or Password!", ); } // make it json format // print_r(json_encode($user_arr)); if (in_array("Successfully Login!", $user_arr)) { header('Location: ../../dashboard.html'); } ?>
Hi, I have a problem with my code probably it's authorisation mistake or something. I bought a book PHP6, MySQL, Apache Web Development and I am copying every excercise like it's in the book. If u have this book it's chapter 2, page 63. And here is the exact code from the book. It always says that the user ID or pass is incorrect. Code: [Select] <?php session_start (); $_SESSION['username'] = $_POST['user']; $_SESSION['userpass'] = $_POST['pass']; $_SESSION['authuser'] = 1; //over uzivatelske meno a heslo if ( ($_SESSION['username'] == 'Peter') and ($_SESSION['userpas'] == '12345')) { $_SESSION['authuser'] = 1; } else { echo "Unfortunately you do not have required authorisation to enter this site!"; exit(); } ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Najts oblubeny film!</title> </head> <body> <?php $oblubenyfilm = urlencode('Zivot Briana'); echo '<a href="moviesite.php?oblfilm=$oblubenyfilm\">'; echo 'Dalsie informacie o mojom oblubenom filme!'; echo '</a>' ?> </body> </html> The page is http://www.magicfoto.gigacast.net/test/login.php as you can see ID is "Peter" and pass "12345" If you know what should be wrong pls reply. PS.: I am a begginer so please be patient Thanks |