PHP - Php: Displaying Different Menus To Different User Types.
Hi all,
I'm new to PHP and just looking for any advice anyone might have on the following problem I'm having. I have created a database and tables for registering and logging in users. Each record has three different User Types (or roles): 1, 2 and 3. Once the session has started, I would like to make certain menu items available to certain User Types. I suppose it is some sort of if...elseif statement such as: <?php if($UserType==1) echo {"<p>Menu1</p>"} elseif($UserType==2) echo {"<p>Menu2</p>"} elseif($UserType==3) echo {"<p>Menu3</p>"}; ?> Would anybody be able to point me in the right direction? I'd really appreciate any help at all. Similar TutorialsHi I was just wondering if someone could send me a good tutorial on pulling several fields from a table and displaying them all in one drop down menu for people to select one of them. I dont know what this is called to I dont know what to research online. Hi I have a single page submission update page which incorporates 7 drop down menus and 2 text input fields, everything works fine with the data updating back to the database, the only thing is that when the page is updated all the drop down menus are updated which includes ones that I don't want updated? I need to only update the drop down menus that have been selected? but am unsure how I do it? This is the code from the page, sorry if its a mess but I am not that experienced at the moment. This is a snippet of one of the drop down menus Code: [Select] <tr> <td class="heading">Current Status</td> <td><?php echo $statusdescrip ['status_description']; ?> <select name="status_id" > <?php $status_set = findstatus(); $statuslist = mysql_fetch_assoc ($status_set); ?> <?php do { ?> <option value="<?php echo $statuslist ['status_id']; ?>" ><?php echo $statuslist ['status_description']; ?></option> <?php } while ($statuslist = mysql_fetch_assoc ($status_set)); ?></select> <span class="compuls">*</span></td> </tr> I need help getting user comments from my database and displaying them in a format like you'd see in an online newspaper where each user's comments are displayed one after the other like this... Quote --------------------- By John Doe 8:30 p.m. on Sept 1, 2011 I really liked Debbie's article and encourage others to read it! --------------------- By Sally Peters 11:00 a.m. on Aug 30, 2011 I had the same thing happen to me!! --------------------- Here is the code I have on my "article.php" page below where I generate my Article... Code: [Select] // ********************** // Build Comments Query * // ********************** // Build query. $q = 'SELECT m.first_name, c.created_on, c.body, c.status FROM member AS m INNER JOIN comment AS c ON m.id = c.member_id WHERE article_id=?'; // Prepare statement. $stmt = mysqli_prepare($dbc, $q); // Bind variable. mysqli_stmt_bind_param($stmt, 'i', $articleID); // Execute query. mysqli_stmt_execute($stmt); // Store result-set. mysqli_stmt_store_result($stmt); // **************************** // Check for Comments Record. * // **************************** if (mysqli_stmt_num_rows($stmt)>=1){ // Comment in Database. $commentExists = TRUE; // Bind result-set to variables. mysqli_stmt_bind_result($stmt, $firstName, $createdOn, $body, $status); // Fetch record. mysqli_stmt_fetch($stmt); } Is it correct that mysqli_stmt_store_result($stmt); stores the entire query results? Where does it do that? Some hidden MySQL object in memory? How do I get the query results into a format where I can iterate through each record and display it? Thanks, Debbie i need to display the fullname and email of the logged in user. <?php session_start(); mysql_connect("localhost", "root", "") or die(mysql_error()); mysql_select_db("db_register") or die(mysql_error()); $query = "SELECT` fullname`, `email` FROM `members` WHERE `username`='".$_SESSION['user']."' LIMIT 1"; if($doQuery = mysql_query($query)) { if(mysql_num_rows($doQuery)) { $user = mysql_fetch_assoc($doQuery); print_r($user); } else { echo 'No result returned for the query: '.$query; } } else { echo 'The following query failed: '.$query; } $id = $user['id']; $fullname = $user['fullname']; $email = $user['email']; } ?> <br> Fullname : <?php echo $fullname; ?> <br> Email : <? echo $email; ?> ?> HELP please . Hello, I'm trying to build a registration/login system. I managed to set it up but i need that for the user when he/she is logged in to display his own information and to manage to edit them, First i need to display them, because i seem to not be doing it.. i know it's easy in principal but i am really new at this... So here is my code: The login.php page Code: [Select] <?php include ('database_connection.php'); if (isset($_POST['formsubmitted'])) { // Initialize a session: session_start(); $error = array();//this aaray will store all error messages if (empty($_POST['e-mail'])) {//if the email supplied is empty $error[] = 'You forgot to enter your Email '; } else { if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) { $Email = $_POST['e-mail']; } else { $error[] = 'Your EMail Address is invalid '; } } if (empty($_POST['Password'])) { $error[] = 'Please Enter Your Password '; } else { $Password = $_POST['Password']; } if (empty($error))//if the array is empty , it means no error found { $query_check_credentials = "SELECT * FROM members WHERE (Email='$Email' AND password='$Password') AND Activation IS NULL"; $result_check_credentials = mysqli_query($dbc, $query_check_credentials); if(!$result_check_credentials){//If the QUery Failed echo 'Query Failed '; } if (@mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull { // A match was made. $_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);//Assign the result of this query to SESSION Global Variable header("Location: page.php"); }else { $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect'; } } else { echo '<div class="errormsgbox"> <ol>'; foreach ($error as $key => $values) { echo ' <li>'.$values.'</li>'; } echo '</ol></div>'; } if(isset($msg_error)){ echo '<div class="warning">'.$msg_error.' </div>'; } /// var_dump($error); mysqli_close($dbc); } // End of the main Submit conditional. ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login Form</title> <style type="text/css"> body { font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif; font-size:12px; } .registration_form { margin:0 auto; width:500px; padding:14px; } label { width: 10em; float: left; margin-right: 0.5em; display: block } .submit { float:right; } fieldset { background:#EBF4FB none repeat scroll 0 0; border:2px solid #B7DDF2; width: 500px; } legend { color: #fff; background: #80D3E2; border: 1px solid #781351; padding: 2px 6px } .elements { padding:10px; } p { border-bottom:1px solid #B7DDF2; color:#666666; font-size:11px; margin-bottom:20px; padding-bottom:10px; } a{ color:#0099FF; font-weight:bold; } /* Box Style */ .success, .warning, .errormsgbox, .validation { border: 1px solid; margin: 0 auto; padding:10px 5px 10px 60px; background-repeat: no-repeat; background-position: 10px center; font-weight:bold; width:450px; } .success { color: #4F8A10; background-color: #DFF2BF; background-image:url('images/success.png'); } .warning { color: #9F6000; background-color: #FEEFB3; background-image: url('images/warning.png'); } .errormsgbox { color: #D8000C; background-color: #FFBABA; background-image: url('images/error.png'); } .validation { color: #D63301; background-color: #FFCCBA; background-image: url('images/error.png'); } </style> </head> <body> <form action="login.php" method="post" class="registration_form"> <fieldset> <legend>Login Form </legend> <p>Enter Your username and Password Below </p> <div class="elements"> <label for="name">Email :</label> <input type="text" id="e-mail" name="e-mail" size="25" /> </div> <div class="elements"> <label for="Password">Password:</label> <input type="password" id="Password" name="Password" size="25" /> </div> <div class="submit"> <input type="hidden" name="formsubmitted" value="TRUE" /> <input type="submit" value="Login" /> </div> </fieldset> </form> Go Back to <a href="#">Account Verification on sign up</a> </body> </html> This is the page's code where user is redirected after login Code: [Select] <?php ob_start(); session_start(); if(!isset($_SESSION['Username'])){ header("Location: login.php"); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Member Area </title> <style type="text/css"> .success { border: 1px solid; margin: 0 auto; padding:10px 5px 10px 60px; background-repeat: no-repeat; background-position: 10px center; font-weight:bold; width:450px; color: #4F8A10; background-color: #DFF2BF; background-image:url('images/success.png'); } </style> </head> <body> <div class="success">Welcome , <?php echo $_SESSION['Username'] ; ?></div> <? $b = time (); $date1 =date( "Y-m-d;h:i:s" , mktime(date("h")+6, date("i"), date("s"), date("m") , date("d"), date("Y"))); $str_time = "&receivedtimestamp="; $str_msg = "&msg=bkt"; $str_from = "from="; ?> <a href="http://testext.i-movo.com/api/receivesms.aspx?<?echo $str_from;?><?echo $_SESSION['phone'];?><?echo $str_time;?><?echo $date1;?><?echo $str_msg;?>">Get a Cupon</a> </br> <?php echo $_SESSION['Email'] ; ?> </br> <?php echo $_SESSION['phone'] ; ?> <p><strong>My Account</strong></p> <a href="myaccount.php">My Account</a><br> <a href="mysettings.php">Settings</a><br> <a href="logout.php">Logout </a> </body> </html> And finally the database structure is this one ... Code: [Select] CREATE TABLE IF NOT EXISTS `members` ( `Memberid` int(10) NOT NULL AUTO_INCREMENT, `Username` varchar(20) NOT NULL, `Email` varchar(50) NOT NULL, `Password` varchar(10) NOT NULL, `phone` varchar(25) NOT NULL, `Activation` varchar(60) DEFAULT NULL, PRIMARY KEY (`Memberid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=30 ; Please help me with this because i'm going mad Hi, I got this code which is meant to display the login details of the person that is logged in, however it just displays the details of the last person in the mysql table. I have set up some test logins, so if I login as paul1 the details for paul3 are displayed...confused Anyway, here is the page which displays the details Code: [Select] <?php session_start(); // This checks to make sure the session variable is registered // WARNING: DO NOT DELETE THE FOLLOWING LINE OF TEXT if( isset($_SESSION['username']) && isset($_SESSION['sid'])) { // You are free to edit the following code to suit your requirements include_once("../../data/server.php"); include_once("../../lib/userdata.php"); // THIS BIT WORKS AND DISPLAYS THE USERNAME $data = mysql_query("SELECT * FROM members") or die(mysql_error()); while($info = mysql_fetch_array( $data )) { include("../../lib/userinfo.php"); //////////////////////////////////////////// WARNING: YOU SHOULD NOT EDIT ANYTHING ABOVE THIS LINE //////////////////////////////////////////////////////// ECHO <<<PAGE <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>$siteName</title> <link rel="stylesheet" href="../../userstylesheet.css" type="text/css" /> </head> <div id="page"> <img alt="" src="../../images/leftCurve" height="6" width="6" id="left" /> <img alt="" src="../../images/rightCurve.gif" height="6" width="6" id="right" /> <div id="pageName"> <h1>$siteName</h1> </div> <div id="pageNav"> <div id="sectionLinks"> <a href="profile.php?username=$username">My Profile</a> <a href="modify.php?username=$username">Personal Details</a> <a href="message.php?username=$username">Messages</a> <a href="../../logout.php?username=$username">Logout</a></div> </div> <div id="content"> <div class="feature"> <h2>Welcome $username </h2> <p>This is the demonstration home.html template. You are free to edit this or any of the other templates to suit your own needs. </p> <p>This is the first page your member will see once they have logged in. </p> <p>If you look at the code for this page, you will see that all HTML code is placed between the ***PAGE and PAGE; tags. Please note that the three * should be replaced with the < character. This format must be kept to ensure that the user variables work. Changing this format may result in errors being returned.</p> <p>You may call member information using the $ tag and the variable name eg $ firstname without the space, will show the members first name, such as $firstname</p> <p>For any information please visit our site http://www.membersitemaker.co.uk. User guides will be added shortly and the forum will soon be full of help. </p> </div> </div> <div id="information"> <a href="#">About Us</a> | <a href="#">Site Map</a> | <a href="#">Privacy Policy</a> | <a href="#">Contact Us</a> | ©2011 $siteName </div> </div> </body> </html> PAGE; } //////////////////////////////////////// WARNING: DO NOT DELETE ANYTHING BELOW THIS LINE ////////////////////////////////////////////////////////// } else { // This will redirect the user to the login page if the session variables do not exist header( "Location: ../../../login.html" ); } ?> And here is the code for userdata.php Code: [Select] <?php // Decode sitename function decode_variable(&$siteName) { $siteName = urldecode($siteName); $siteName = str_replace('%20',' ',$siteName); return $siteName; } decode_variable($siteName); // Connnect to MySQL database include_once("../../data/mysql.php"); $mysqlPassword = (base64_decode($mysqlpword)); $db = mysql_connect("$localhost", "$mysqlusername", "$mysqlPassword") or die ("Error connecting to database"); mysql_select_db("$dbname", $db) or die ("An error occured when connecting to database"); // Carry out MySQL query ?> and userinfo.php Code: [Select] <?php $username = $info['username']; $firstname = $info['firstname']; $lastname = $info['lastname']; $address = $info['address']; $town = $info['town']; $county = $info['county']; $postcode = $info['postcode']; $email = $info['email']; $birth_year = $info['birth_year']; $country = $info['country']; $telephone_number = $info['telephone_number']; $mobile_number = $info['mobile_number']; $nickname = $info['nickname']; As always, your help is much appreciated Paul Hi guys Do you guys know if possible to open an external URL without actually displaying this to the user? We have a service where we wish to open an external URL which triggers sending out an SMS to the user. However..we cannot display the url opened to the user as it shows our username etc with the sms provider. basically the url looks like this: https://www.smsprovider.com/username=OurUsername&password=******&smsMsg_to_send=blablablablabla Is it possible to "trigger" this URL without letting our users see it? Thanks in advance for any help you may provide Hi all I have some code that displays the high scores for a game. Unfortunately, if a user has more than 1 high score in the table all scores for that user are displayed. I would like to only display the highest score per user. My Current Code Code: [Select] $sql_query = sprintf("SELECT * FROM `highscores` WHERE `gameID` = '106' ORDER BY `score` DESC"); //store the SQL query in the result variable $result = mysql_query($sql_query); if(mysql_num_rows($result)) { //output as long as there are still available fields while($row = mysql_fetch_row($result)) { echo ("$row[3] Scored :$row[5] <br>"); } } //if no fields exist else { echo "no values in the database"; } mysql_close($con); OutPut User1 300 User1 298 User 2 297 User1 296 User3 295 User2 290 I would like the output to be User1 300 User 2 297 User3 295 Any help is much appreciated What types of data can the $_SESSION cookie store? Objects? Resources? And how are these stored in text form? I have a scenario where users are downloading files from a legacy system and uploading the files into a new system that I am supporting. Many of the files do not have an extension (most are tiffs).
The issue we have is that the new system doesn't know how to open these files (we have them open in a preview window in the new system). I have tried numerous solutions, including finfo_file() and the depreciated mime_content_type() funcitons), but all they seem to return is "application/octet-stream".
Thanks.
This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=353735.0 Is it possible to define a variable's type at the start of your code? I believe you can "cast" a variable, but can I do something like this... Code: [Select] name string; age integer; gender string; children array; single: boolean; I know some people say PHP is better suited for the web because it is loosely-typed, but I'm anal-retentive and like my structure!! TomTees can someone explain to me why PHP returns so many different variants when throwing out visitor info using this piece of code? $ip = gethostbyaddr($_SERVER['REMOTE_ADDR']); here are some examples I have seen recently: planetlab24.gino-research.net.in.tum.de 10.32.64.124 49.129.197.35.bc.googleusercontent.com abts-north-dynamic-142.110.68.182.airtelbroadband.in 173-20-152-84.client.mchsi.com now, obviously i can understand the google one, and a few others. but, given the info and insight on these pages: https://www.php.net/manual/en/function.gethostbyaddr.php , and https://www.php.net/reserved.variables.server , why are the returns so different for different people? why does PHP see all different kinds of things? is the cause the way the user’s server is configured? some identifying info OF the server? and what about reserved IPs? like the “10.xx…” one I listed above? I’ve seen hundreds from that pool, and other blocks of reserved ones, and they have never had alpha-chars included in their captures. it’s always only the IP numbers. there a reason for that? really, all I’m looking for is why I see what I see. anyone help? furthermore, does anyone know if other server-side languages like c#, python, ruby or any js frameworks return different results than PHP ever would? thanks. I've asked this question before but still haven't really figured out how best to implement it, and have found myself hitting another roadblock. I have multiple types of charts (i.e. bar, pie, etc), and various endpoints to access them. I like to keep my routing script uncluttered, and feel the following does so. $app->get('/chart', function (Request $request, Response $response) { //List of chart with optional filtering $this->chartService->index($request->getQueryParams()); return $this->chartResponder->index($response, $index); }); $app->post('/chart', function (Request $request, Response $response) { //Create a new chart of type (i.e. bar, pie, etc) specified by type parameter $chart=$this->chartService->create($request->getParsedBody()); return $this->chartResponder->create($response, $chart); }); $app->get('/chart/{id:[0-9]+}', function (Request $request, Response $response, $args) { //View chart of given ID $chart=$this->chartService->detail((int)$args['id']); return $this->chartResponder->delete($response, $chart); }); $app->delete('/chart/{id:[0-9]+}', function (Request $request, Response $response, $args) { //Delete chart of given ID $this->chartService->delete((int)$args['id']); return $this->chartResponder->delete($response, null); }); $app->post('/chart/{id:[0-9]+}/series', function (Request $request, Response $response, $args) { //Add a new series to the collection for chart with given ID $chart=$this->chartService->addSeries((int)$args['id'], $request->getParsedBody()); return $this->chartResponder->update($response, $chart); }); $app->put('/chart/{id:[0-9]+}/series/{seriesPosition:[0-9]+}', function (Request $request, Response $response, $args) { //Modify series of given position in the collection for chart with given ID $chart=$this->chartService->updateSeries((int)$args['id'], (int)$args['seriesPosition'], $request->getParsedBody()); return $this->chartResponder->update($response, $chart); }); //More endpoints for chart of given ID... I then created the following service to support the endpoints. Off topic, but is this a service or a controller? My index() method is chart type agnostic. My create() method needs a means to determine what type of chart to create, and does so using the received chart "type" passed in the body to get the applicable repository. All the other methods receive the chart ID in the URL path and use it to first get the chart entity and then get the applicable repository based on the object. All seems good! <?php namespace NotionCommotion\ChartBuilder\Service; use NotionCommotion\ChartBuilder\Entity\Chart; class ChartService { protected $em; public function __construct(\Doctrine\ORM\EntityManager $em) { $this->em = $em; } public function index(array $params=[]):array { return $this->em->getRepository(Chart::class)->index($params); } public function create(array $params):Chart { //Get the specific repo based on $params['type]. Not perfect, but good enough $discriminatorMap=$this->em->getClassMetadata(Chart::class)->discriminatorMap; $repo = $this->em->getRepository($discriminatorMap[$params['type']]); //Validate data $chart=$repo->create($params); $this->em->persist($chart); $this->em->flush(); return $chart; } public function read(int $id):Chart { return $this->em->getRepository(Chart::class)->find($id); } public function delete(int $id):void { $this->em->remove($this->read($id)); $this->em->flush(); } public function addSeries(int $idPublic, array $id):Chart { $chart=$this->read($id); //Validate data $repo=$this->em->getRepository(get_class($chart)); $repo->addSeries($chart, $params); $this->em->persist($chart); $this->em->flush(); return $chart; } public function updateSeries(int $id, int $position, array $params):Chart { $chart=$this->read($id); $series=$chart->getSeries(); $seriesNode=$series->offsetGet($position); //Validate data $repo=$this->em->getRepository(get_class($seriesNode)); $repo->update($seriesNode, $params); $this->em->persist($chart); $this->em->flush(); return $chart; } } Until... I find myself needing to put non-database related functionality in the repository and violating the single responsibility principle. I am not a complete purist and might be willing to do so, however, there does not appear to be a clean way to inject dependencies in a Doctrine repository. One thought I had was to create specialized services maybe as follows: $c['chartService'] = function ($c) { return new ChartService( $c[EntityManager::class], [ 'bar'=>function ($c) {return new BarChartService($c[EntityManager::class]);}, 'pie'=>function ($c) {return new PieChartService($c[EntityManager::class], $c['someOtherObject']);}, //add more types... ] ); };
class ChartService { protected $em, $subServices=[]; public function __construct(\Doctrine\ORM\EntityManager $em, $subServices) { $this->em = $em; $this->subServices = $subServices; } public function index(array $params=[]):array {/* no change */} public function create(array $params):Chart {/* maybe no change */} public function __call($name, $args) { $chart=$this->em->getRepository(Chart::class)->find($args[0]); $subservice=$this->getSubservice($chart); $args[0]=$chart; return $subservice->$name(...$args); } } abstract class AbstractSpecificChartService { protected $em; public function __construct(\Doctrine\ORM\EntityManager $em) { $this->em = $em; } public function __call($name, $args) { throw new \Exception("Method $name not supported"); } protected function getSubservice(Chart $chart):self { //Haven't figured out but can do so if needed. } public function delete(Chart $chart):void { //Include methods common to all charts here $this->em->remove($chart); $this->em->flush(); } protected function helperMethods($foo) { //If necessary. } } class BarChartService extends AbstractSpecificChartService { //Override __construct if necessary public function updateSeries(Chart $chart, int $position, array $params):Chart { //Note that Chart and not $id is passed. //implement code as needed return $chart; } }
So, after this long story, how should I implement this? Thank you I am getting this error: Fatal error: Unsupported operand types. Code: [Select] <?php $new_player_credits = $player_credits + $game_credits; $new_player_exp = $player_exp + $game_exp; ?> I have absolutely no clue why I'm getting the error. Both of my variables are integers. I am in the process of creating a script where only certains video types can be uploaded but at the moment am stuck.
Here is my code -
<?php $title = isset($_POST['title']) ? $_POST['title'] : null; $desc = nl2br(isset($_POST['description'])) ? $_POST['description'] : null; $name = isset($_POST['fullname']) ? $_POST['fullname'] : null; $email = isset($_POST['email']) ? $_POST['email'] : null; $country = isset($_POST['country']) ? $_POST['country'] : null; $video = isset($_FILES['video']); $videoname = isset($_FILES['video']['name']); $videotmp = isset($_FILES['video']['tmp_name']); $videosize = isset($_FILES['video']['size']); $videotype = isset($_FILES['video']['type']); $videoacceptable = array( "video/mp4", "video/ogg", "video/quicktime", ); $videopath = "/videos/"; $videofile = $videopath . $video; if(isset($_POST['submit'])) { //ERROR MESSAGES / VALIDATION if(empty($title)) { $errors[] = "A title is required"; echo "<style type=\"text/css\"> #title { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } elseif(strlen($title) > 80) { $errors[] = "Your title can only be 80 characters long"; echo "<style type=\"text/css\"> #title { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } if(empty($desc)) { $errors[] = "A description is required"; echo "<style type=\"text/css\"> #description { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } if(empty($name)) { $errors[] = "Please enter your full name"; echo "<style type=\"text/css\"> #fullname { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } elseif(strlen($name) > 32) { $errors[] = "Your name can only be 32 characters long"; echo "<style type=\"text/css\"> #fullname { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } if(empty($email)) { $errors[] = "Please enter your email address"; echo "<style type=\"text/css\"> #email { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } elseif(strlen($email) > 50) { $errors[] = "Your email addess can only be 50 characters long"; echo "<style type=\"text/css\"> #email { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Please enter a valid email address"; echo "<style type=\"text/css\"> #email { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } if($videosize = 0) { $errors[] = "You forgot to upload a video"; } elseif($videosize >= 20000000) { $errors[] = "Your video size is too large, 20mb max"; } elseif(!in_array($videotype, $videoacceptable)) { $errors[] = "The file type is not allowed, only allowed .mp4, .ogg and .mov"; } if(count($errors) === 0) { $connect = mysqli_connect("localhost","username","password"); if(!$connect) { header("Location:"); // ADD ERROR LINK } $dbselect = mysqli_select_db("database"); if(!$dbselect) { header("Location:"); // ADD ERROR LINK } $query = mysqli_query("INSERT INTO cover_videos(title, desc, name, email, country, videotmp, videotype, videosize, videopath) VALUES('$title','$desc','$name','$email','$country','$videotmp','$videotype','$videosize','$videopath')"); move_uploaded_file($videotmp, $videofile); //SEND AN EMAIL TO THE USER $to = $email; $subject = "Thank's for your upload"; $message = ' <html> <head><title>We have received your video</title></head> <body> <h3>Good News!</h3> <p>We have recieved your video and is awaiting approval.</p> </body> </html> '; $headers = 'FROM: no-replyk' . "\r\n"; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers = 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); header("Location:"); //SUCCESSFUL UPLOAD PAGE } } ?>So whats happening is when i go to upload a file, im uploading a .mov file but the error message that pops up is "The file type is not allowed, only allowed .mp4, .ogg and .mov" but the .mov mime is in the videoacceptable array so im a bit stuck at the moment, any know whats the problem? I'm working on a two-file upload form and want to be able to check the mime types of two filenames in a string variable.
The code below was working when the variable @resume_path contained just one filename. How can I modify this to accommodate two files?
when I echo $resume_path, I get, for example: cover_letter_centerline.doc, cover_letter_ctg.doc
Thanks!
//DO NOT TRUST $_FILES['upfile']['mime'] VALUE !! //Check MIME Type by yourself. $finfo = new finfo(FILEINFO_MIME_TYPE); if (false === $ext = array_search( $finfo->file($_FILES['resume_path']['tmp_name']), array( 'txt' => 'text/plain', 'doc' => 'application/msword', 'pdf' => 'application/pdf', ), true )) { throw new RuntimeException('Invalid file format.'); } echo "Sorry, invalid file format. Please try again."; echo $ext; friends my url is like this Category=Love&ID=1 now in url if i do something like this Category4637=Hate19203&ID=1 the details are still showing, how can i fix this? if someone type Capegory instead of Category and a wrong category name which do not exist with that id in db send them to index.php? Hey Guys, How are custom Mime Types achieved? Had a quick search through the forums, and most of the posts relate to mail() questions. Did a google search and found a completely useless article that told me to edit a non-existent text box. Quick example, the file type I want is .WAgame, I got this far before I realised what I was doing didn't make sense. So I looked up mime types, knowing that this file would not exist. if ($_FILES["file"]["type"] != "file/WAgame") { naughty! } Help! Edit: I searched the forums and the Internet as a whole looking for more information on this, but all I've turned up is a lot of information on /how/ to use create_function(), not /when/ to use it. For instance: http://en.wikipedia.org/wiki/Lambda_calculus Let me reiterate that I understand how it works in general. However, in several years of PHP programming, even through the development of fairly complex, robust systems, I can only think of one case where I recall creating a dynamic function and even here I feel like it was a design mistake. Of course, I use anonymous functions all the time in JavaScript for callback code. It seems to be used from time-to-time to iterate over and apply transformations to sets, but I don't understand the advantage over foreach() for such a task. So, if someone is so-inclined, would you mind listing a general scenario or two where create_function() is the correct and appropriate solution to the problem? |