PHP - Validate Url Function, Which Support Http:// , And Www.
Hello,
I need function or something which check valid or not url. This function: function validateurl($url){ return preg_match('/^(http(s?):\/\/|ftp:\/\/{1})((\w+\.){1,})\w{2,}$/i', $url); } supports http://www.google.com or http://google.com , but doesn't support www.google.com ... How I can do Validate Url function, which will support http://www.google.com , http://google.com , and www.google.com ? Best Regards, Tadas Similar TutorialsI am trying to use this: http://php.net/manual/en/function.xml-parse-into-struct.php to parse this: Code: [Select] <?xml version="1.0" encoding="utf-8"?> <PaymentNotification xmlns="http://"> <PaymentMethod>card</PaymentMethod> <Hash>12345KKLS</Hash> <Payments> <Payment> <PaymentID>709750ba-b9b6-44c4-9812</PaymentID> <Amount>70</Amount> <Currency>USD</Currency> <Date>2011-05-11T07:41:44.957</Date> <StatusID>4</StatusID> </Payment> <Payment> <PaymentID>e0c66bae-c423-43c6-b896</PaymentID> <Amount>50</Amount> <Currency>USD</Currency> <Date>2011-05-11T07:42:13.55</Date> <StatusID>2</StatusID> </Payment> </Payments> </PaymentNotification> ...but can't work out which numbers to use. I only need to grab the payment ID where the statusID is 4 (for each one as could be 1 or more per xml message). It's very complicated http://php.net/manual/en/function.xml-parse-into-struct.php HI guys I have vreated a site and am now trying to validate the ip address i have created a function but am failing to get it to work i need to add the errors to add to the errors array but instead it keeps resetting and leaving me with the last error that is returned any help would be greatly appreciated im a newbie so if i can understand the concept behind whats happening it will be of great benefit Thanks Sean heres the code // Function validateIpaddress($address,$record,$errors) // { // if ($address !=="" or $address !=="ip_address") // { // Print_r($address); // echo "<br><br>"; // $fullstoppos = strpos(($address), "."); // echo "strpos = $fullstoppos"; // $fullstoppos2 = strpos(($address), ".", $fullstoppos+1); // echo "strpos2 = $fullstoppos2"; // $fullstoppos3 = strpos(($address), ".", $fullstoppos2+1); // echo "strpos3 = $fullstoppos3"; // } // if ($fullstoppos !==4 && $fullstoppos2 !==9 && $fullstoppos3 !==14) // { // $errors[] = "<br><font color='red'>Please correct the following.Or contact your client manager for assitance.<br>* $record is a required field.An ip address is a 16 digit numerical value. </font>"; // } // } $errors = validateIpaddres($_POST['destinationPoint'],A/AAAA record, $errors) Hey! I am trying to get a database table of users but am running into the error: Warning: file_get_contents(http://protege-ontology-editor-knowledge-acquisition-system.136.n4.nabble.com/template/NamlServlet.jtp?macro=user_nodes&user=68583) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 500 in get_user_from_parameter(nabble:utilities.naml:890) - <n.get_user_from_parameter.as_user_page.do/> - public v in C:\xampp\htdocs\website4js\stanford\loadUsernames.php on line 32 I have looked it up and it may be a security thing...The urls I am getting are http://protege-ontology-editor-knowledge-acquisition-system.136.n4.nabble.com/template/NamlServlet.jtp?macro=user_nodes&user=68583 but the error adds an nodes& part that screws it up. Any way around this? Code: [Select] <?PHP $maxPage = 0; $mainPage = "http://protege-ontology-editor-knowledge-acquisition-system.136.n4.nabble.com/template/NamlServlet.jtp?macro=app_people&node=136"; $mainContent = file_get_contents($mainPage); $pattern = "/(?<=\"Page )\d\d+/"; preg_match_all($pattern, $mainContent, $pageNumb); //find the max page for($i=0;$i<sizeof($pageNumb[0]);$i++) { if($pageNumb[0][$i] > $maxPage) { $maxPage = $pageNumb[0][$i]; } } //echo('Max page is: '.$maxPage.'\n'); //Get an array of all the pages $pages = array(); for($i=1;$i<$maxPage;$i++) { $pages[$i] = "http://protege-ontology-editor-knowledge-acquisition-system.136.n4.nabble.com/template/NamlServlet.jtp?macro=app_people&node=136&i=".($i*20); } //print_r($userPages); //Get personal page urls and add to MySQL mysql_connect("localhost" , "root") or die("Cant connect"); mysql_select_db("protegeusers") or die("Cant find database"); foreach($pages as $url) { $urlContents = file_get_contents($url); $pattern = "/http:\/\/protege-ontology-editor-knowledge-acquisition-system\.136\.n4\.nabble\.com\/template\/NamlServlet\.jtp\?macro=.+;user=\d+/"; preg_match_all($pattern, $urlContents, $personalPage); foreach($personalPage as $user) { for($i=0; $i<sizeof($user);$i++) { [color=green]$userContents = file_get_contents($user[$i]);[/color] $pattern1 = "/user\/SendEmail\.jtp\?type=user.+;user=\d+/"; $pattern2 = "/(?<=\">Send Email to ).+(?=<)/"; preg_match_all($pattern1, $userContents, $userEmail); preg_match_all($pattern2, $userContents, $username); [color=green]print_r($username); print_r($email);[/color] //$query = "INSERT INTO users (username, userurl) values ('$userName','$userUrl')"; //mysql_query($query); } } } ?> 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> How do I only redirect the page when index.php is present? Hi, I'm migrating a site from PHP4 (4.4.6) to PHP5 (5.3.5), am replacing all short open tags, and have many '<?=' opening tags to migrate as well. I saw a reference in the online docs about an equivalent '<?php=' tag, but it doesn't appear to work. What is the best way to 'find and replace' a PHP4 snippet like '<?= $var ?>' into a PHP5, non-short-open-tag equivalent? thanks, Barry Hey there, I'm having a issue when I edit the XML file from a string here. Now the SimpleXML functions edit the nodes of the XML file perfectly and everything is done the way I want but upon returning the file to a string it keeps putting a XML content type at the top of the file, E.G: Before XML File Is Edited: Code: [Select] <settings> <!-- Port the server will listen on --> <port>7781</port> <!-- Maximum number of players the server will support (Max 32) --> <maxplayers>10</maxplayers> <!-- Maximum number of vehicles the server will support (Max 140) --> <maxvehicles>100</maxvehicles> <!-- Password clients will have to enter to connect --> <!-- password>None</password --> <!-- Add the server to the master list --> <listed>true</listed> <!-- The hostname players will see --> <hostname>IV:MP Server</hostname> <!-- The address the server will bind to --> <!-- hostaddress>127.0.0.1</hostaddress --> <!-- Toggles frequently called events which has impact on CPU usage --> <frequentevents>false</frequentevents> <!-- The scripts the server will load and run --> <script>cp.nut</script> <script>whisper.nut</script> <script>namecheck.nut</script> <script>runcode.nut</script> <!-- The modules the server will load and run --> <!-- For windows: --> <!-- module>Sample.dll</module --> <!-- For linux: --> <!-- module>Sample.so</module --> </settings> After XML File Is Edited Code: [Select] <?xml version=1.0?> <settings> <!-- Port the server will listen on --> <port>7781</port> <!-- Maximum number of players the server will support (Max 32) --> <maxplayers>10</maxplayers> <!-- Maximum number of vehicles the server will support (Max 140) --> <maxvehicles>100</maxvehicles> <!-- Password clients will have to enter to connect --> <!-- password>None</password --> <!-- Add the server to the master list --> <listed>true</listed> <!-- The hostname players will see --> <hostname>IV:MP Server</hostname> <!-- The address the server will bind to --> <!-- hostaddress>127.0.0.1</hostaddress --> <!-- Toggles frequently called events which has impact on CPU usage --> <frequentevents>false</frequentevents> <!-- The scripts the server will load and run --> <script>cp.nut</script> <script>whisper.nut</script> <script>namecheck.nut</script> <script>runcode.nut</script> <!-- The modules the server will load and run --> <!-- For windows: --> <!-- module>Sample.dll</module --> <!-- For linux: --> <!-- module>Sample.so</module --> </settings> Notice the addition to the header of the file "<?xml version=1.0?>". This is causing issues when the XML file is read by the server. Could anybody help me stop the SimpleXML editor from placing this in the header of the file? Thanks. Hello. I'm working on a site which I'd prefer to use SVG for some of the images. However, since not all browsers support SVG, I'm going to set a global variable to true if I detect the browser supports SVG. Using this, I can check to see if SVG is supported and show PNG/gif/jpg images in the place of the SVG in older browsers (and add a small banner at the top prompting them to upgrade to a modern browser). I can already do this using javascript. But seeing as javascript can be disabled, newer browsers that can support SVG might not be fed those images (which are much smaller files). The javascript I'm using to test SVG support is as follows Code: [Select] document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Shape", "1.1") the php code I tried, seeing as how it would make sense, is the following DOMImplementation::hasFeature("http://www.w3.org/TR/SVG11/feature#Shape", "1.1") (both of those were used in conditional branches) Is there any way to get php to test for SVG support? Or do I need to stick with javascript? Thanks for reading! Hey Everyone, I was hoping someone out there could help me figure something out. I am trying to create a ticket database, when I create a ticket, I give the option to upload a file, which works ok. But I am stumped at trying to display mulitply files to one ticket. If I have a ticket no 0001 and two files associted to 0001, i end up printing two 0001 tickets each with a single file. I want to print one 0001 with both files listed under it. I'm not sure if it's possible to do a while within a while so I hoping someone can help me figure that out. Thanks for your help PHP Code: <HTML><BODY><table align="center" width="600"><tr><td> <?php include 'connect.php'; // how many rows to show per page $rowsPerPage = 3; // by default we show first page $pageNum = 1; // if $_GET['page'] defined, use it as page number if(isset($_GET['page'])) { $pageNum = $_GET['page']; } // counting the offset $offset = ($pageNum - 1) * $rowsPerPage; $query = " SELECT tickets.ticketno, tickets.tickettitle, tickets.customer, tickets.status, tickets.dateresolved, tickets.datecreated, tickets.description, files.name, files.content FROM tickets LEFT JOIN files ON tickets.ticketno=files.ticketno ORDER BY ticketno LIMIT $offset, $rowsPerPage"; $result = mysql_query($query) or die('Error, query failed'); while($row = mysql_fetch_array($result)) { echo "<table align='center'><tr><td colspan='2'><img src='images\line_v9.gif'></td></tr>"; echo "<tr><td> <b>Ticket No -- " . $row['ticketno'] . "</b></td><td> Ticket Title -- " . $row['tickettitle'] . "</td></tr>"; echo "<tr><td> Customer -- " . $row['customer'] . "</td><td> Description -- " . $row['status'] . "</td></tr>"; echo "<tr><td> Date Resolved -- " . $row['dateresolved'] . "</td><td> Date Created -- ". $row['datecreated'] ."</td></tr>"; echo "<tr><td colspan='2'> Description -- " . $row['description'] . "</td></tr>"; echo "<tr><td colspan='2'> </td></tr><tr><td colspan='2'> <b>Reference Documents</b> </td></tr>"; echo "<tr><td> File -- " . $row['name'] . "</td><td> <a href='http://www.dbitpro.com/csp/files/" . $row['name'] . "'>Download Here</a></td></tr></table>"; } $query = " SELECT files.*, tickets.* FROM files,tickets WHERE tickets.ticketno=files.ticketno"; $result = mysql_query($query) or die('Error, query failed'); while($row = mysql_fetch_array($result)) { echo "<table><tr><td> File -- " . $row['name'] . "</td><td> Ticketno" . $row['ticketno'] . "</td></tr></table>"; } // how many rows we have in database $query = "SELECT COUNT(ticketno) AS numrows FROM tickets"; $result = mysql_query($query) or die('Error, query failed'); $row = mysql_fetch_array($result, MYSQL_ASSOC); $numrows = $row['numrows']; // how many pages we have when using paging? $maxPage = ceil($numrows/$rowsPerPage); // print the link to access each page $self = $_SERVER['PHP_SELF']; // creating previous and next link // plus the link to go straight to // the first and last page if ($pageNum > 1) { $page = $pageNum - 1; $prev = " <a href=\"$self?page=$page\">[Prev]</a> "; $first = " <a href=\"$self?page=1\">[First Page]</a> "; } else { $prev = ' '; // we're on page one, don't print previous link $first = ' '; // nor the first page link } if ($pageNum < $maxPage) { $page = $pageNum + 1; $next = " <a href=\"$self?page=$page\">[Next]</a> "; $last = " <a href=\"$self?page=$maxPage\">[Last Page]</a> "; } else { $next = ' '; // we're on the last page, don't print next link $last = ' '; // nor the last page link } // print the navigation link echo $first . $prev . " Showing page $pageNum of $maxPage pages " . $next . $last; // and close the database connection mysql_close($con) ?> </td></tr></table> </BODY></HTML> Hi everyone,
I'm hoping the someone can guide me in the right direction for what I need to do. Does anyone know of a really good tutorial and/or information about a plugin product that is available to do what I need? For example, what I need is to create a website that has the ability to allow video conferencing between a teacher and students. This what I envision - a college professor can log on to his website and display a live video feed of him. Also, as each of his students log on, their live video feed is then also supplied. Would prefer a already made plugin product but would also like to look at raw code in PHP to see how something like this could be accomplished. Thank you in advance.
Charles
This topic has been moved to HTML Help. http://www.phpfreaks.com/forums/index.php?topic=311943.0 I think it's fsockopen that enables you to do web requests right?? I was wondering if you could also make it use a proxy instead of your website's IP. Would that be possible? As written here i am trying todo the php remote support. What i was wondering is in sections line $ret .= 'cd client && ..\\win\\'.filename7z ' a ' etc, why does the user use \\ instead of a single \ and whats with the &&? i have the original php file and it reads $ret .= shell_exec('cd client;' . $filename7Z . ' a '' etc Now i know the original was made for Xampp in windows but i can get it nor this guys version to work. I assume that the \\ and && are specific to windows file systems but i can figure out how. I am trying to modify it to work on my 2k8r2 server or win7(running xampp) but get dead ends in both places. My Ubuntu server is a whole diff animal. can anyone give me any guidance? original file location here Title: Software Developer Support Lead
About Us:
We are a small, rapidly growing software company based in Wilmington, NC. Our mission is simple: help companies, cities, and school systems save money in bulk fuel acquisition and managing their fleets of vehicles. We are in the fuel industry and we want transparency. We have a diligent, diverse team, which enjoys challenges and the joy of extracting our best in our daily work life.
Who We Are Seeking:
A charismatic individual to serve as a first line of defense for our software team's most valuable product. Ideally you would be happiest when making others happy, especially as it relates to solving elusive problems in code, or logic in a large, web application. If you have high expectations of your work, and that of others, and seek to solve problems at their core, this will be a good fit for you. We strive to deal with difficult problems today so that tomorrow will be a better place.
About The Position:
You will be the primary point of contact between our Operations and Development teams--this means you will have to help refine problems, research code, develop and apply rock-solid solutions, and work well with others in the process. In short, you will be coding, but you will also plan, weighing many potential outcomes, and test the result. You will need to know Linux, MVC frameworks, PHP, MSSQL/MySQL and have a desire to learn: both about technology and from our experiences.
General:
B.S. in Computer Science, or comparable
comfortable in PHP, MySQL/MSSQL, Javascript, jQuery
familiarity with any web framework (Yii experience preferred)
excellent communication skills
explain what is on your mind: with words, pictures, metaphors, UML, etc.
1 or more years of experience desired
Helpful Characteristics:
daily user of Linux (Arch, Fedora, CentOS, for example)
familiarity with vim, tmux
personality traits which would be helpful
methodical in nature
willingness to learn
desire to please
re-enforcing standards, rather than "just get the job done"
ability to work with a team
"Pair Programming" is a daily practice
regular code reviews
group project planning
plan first, act later
asking questions is considered a strength
highly communicative in nature
work with Operations Team to refine the actual problem
determine the source of the problem
propose solution to Software Architect
implement a solution
Please email résumé and cover sheet to development@goenergies.com.
I have an array of proxies and I need one to be chosen randomly and applied to each curl handle. This script runs successfully when proxy support is removed, but as soon as I try to add a proxy it refuses to connect. My proxies are good. I have private proxies that validate by confirming that the IP address of the requester is on a whitelist of IPs I configured. I've also tried working public proxies with no validation, with the same result. The error it returns is that it "cannot connect to google.com:3238". Why it's trying to connect to that port is beyond me, the proxies I use, their port is 3238, but it should be connecting to IP:PORT then Google.com:80. Not sure why it's mixing them up. Here's my code: Code: [Select] function multi($urls,$proxies,$agents,$referer) { // create the multi curl handle $mh = curl_multi_init(); $handles = array(); $i = 0; foreach ($urls as $url) { // create a new single curl handle $ch = curl_init(); // setting several options like url, timeout, returntransfer // simulate multithreading by calling the wait.php script and sleeping for $rand seconds curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_PROXY, $proxies[rand(0,count($proxies))]); curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt'); curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt'); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_REFERER, $referer); curl_setopt($ch, CURLOPT_USERAGENT, $agent); // add this handle to the multi handle curl_multi_add_handle($mh,$ch); // put the handles in an array to loop this later on $handles[] = $ch; $i++; } // execute the multi handle $running=null; do { curl_multi_exec($mh,$running); // added a usleep for 0.25 seconds to reduce load usleep (250000); } while ($running > 0); echo 'Curl error: ' . curl_error($ch)."<br />".print_r(curl_getinfo($ch)); // get the content of the urls (if there is any) for($i=0;$i<count($handles);$i++) { // get the content of the handle $output[] = curl_multi_getcontent($handles[$i]); // remove the handle from the multi handle curl_multi_remove_handle($mh,$handles[$i]); } // close the multi curl handle to free system resources curl_multi_close($mh); // echo the output to the screen return $output; } I only post on forums as a last resort. Typically a few Google searches solves the problem, but I've spent too much time researching this one with no progress. I'm assuming it's simply a parameter that needs to be added to the CURL handles, but I've tried every proxy related config option out there and still no dice. I'm pretty new to PHP, and by new, I mean I have never done it or any other form of coding before starting my job a month or so ago. I've basically been manually trying to pick up PHP as I go. The website that I am working on had its core built, but I am trying to add functionality to it. The website already had the contact for that you can see he http://www.janova.us/index.php/contact The form would submit an email to an email address based on which subject was picked. I have since added a simple file upload field. My problem, however, is tying in the form to the email. I need to upload it and then send it as an attachment with the email. Here is what I am working with currently: <div id="breadCrumbs"> <a href="index.php">MAIN</a> > <a href="index.php/contact">CONTACT</a> </div> <? $user =& JFactory::getUser(); $user_id = $user -> get('id'); $user_name = $user -> get('name'); $db = JFactory::getDBO(); $query = "SELECT jos_content.introtext, jos_content.fulltext FROM jos_content WHERE catid = 68 AND sectionid = 5 LIMIT 0,3"; $db->setQuery($query); $rows = $db->loadRowList(); ?> <div id="contactTop"> <div id="contactBanner"></div> <div id="contactInfo"> <? echo $rows[0][0]; echo $rows[0][1]; ?> </div> </div> <div id="contactGreeting"> <? echo $rows[1][0]; echo $rows[1][1]; ?> </div> <? if($user_id > 0) { $query = "SELECT jos_users.name, jos_users.email FROM jos_users WHERE id = ".$user_id; $db->setQuery($query); $user_data = $db->loadRow(); } if(isset($_POST["submit"])) { $error = false; $subjectError = false; $messageError = false; $nameError = false; $emailError = false; if(!isset($_POST["subject"]) || empty($_POST["subject"])) { $error = true; $subjectError = true; } if(!isset($_POST["message"]) || empty($_POST["message"])) { $error = true; $messageError = true; } if(!isset($_POST["name"]) || empty($_POST["name"])) { $error = true; $nameError = true; } if(!isset($_POST["email"]) || empty($_POST["email"])) { $error = true; $emailError = true; } else if(!ereg("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$",$_POST["email"])) { $error = true; $emailError = true; echo $_POST["email"]; } if(!$error) { $to = $_POST["subject"]."@janova.us"; $from = $_POST["email"]; $subject = $_POST["subject"]." by: ".$_POST["name"]; $message = $_POST["subject"]."\n\r\n\r".$_POST["message"]."\n\r\n\r-".$_POST["name"]; $headers = "From: $from"; <!----------BEGIN ADDED CODE-------------------------> // Obtain file upload vars $fileatt = $_FILES['fileatt']['tmp_name']; $fileatt_type = $_FILES['fileatt']['type']; $fileatt_name = $_FILES['fileatt']['name']; if (is_uploaded_file($fileatt)) { // Read the file to be attached ('rb' = read binary) $file = fopen($fileatt,'rb'); $data = fread($file,filesize($fileatt)); fclose($file); // Generate a boundary string $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; // Add the headers for a file attachment $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; // Add a multipart boundary above the plain message $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; // Base64 encode the file data $data = chunk_split(base64_encode($data)); // Add file attachment to the message $message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" . " name=\"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" . //" filename=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n"; } <!-----------END ADDED CODE----------------> mail($to,$subject,$message,$headers); echo "Your request has been submitted."; } else { ?> <form action="#" id="contactForm" method="post"> <div id="contactFormLeft"> <? if($user_id > 0) { ?> <label> Your name<? if($nameError) { ?><span class="formError">*</span><? }?> </label><br/> <input type="text" name="name" value="<?=$user_data[0];?>"/><br/> <label> Your email<? if($emailError) { ?><span class="formError">*</span><? }?> </label><br/> <input type="text" name="email" value="<?=$user_data[1];?>"/><br/> <? } else { ?> <label> Your name<? if($nameError) { ?><span class="formError">*</span><? }?> </label><br/> <input type="text" name="name" value="<?=$_POST["name"];?>"/><br/> <label> Your email<? if($emailError) { ?><span class="formError">*</span><? }?> </label><br/> <input type="text" name="email" value="<?=$_POST["email"];?>"/><br/> <? } ?> <label> Subject<? if($subjectError) { ?><span class="formError">*</span><? }?> </label><br/> <select name="subject"> <option value="support" <? if($_POST["subject"]=="support") { echo "selected ";}?>>Support</option> <option value="training" <? if($_POST["subject"]=="training") { echo "selected ";}?>>Training</option> <option value="hr" <? if($_POST["subject"]=="hr") { echo "selected ";}?>>HR</option> <option value="sales" <? if($_POST["subject"]=="sales") { echo "selected ";}?>>Consultation</option> </select> <br/> <input type="submit" id="submit" name="submit" value=""/><br/> </div> <div id="contactFormRight"> <label> Message<? if($messageError) { ?><span class="formError">*</span><? }?> </label><br/> <textarea name="message"><?=$_POST["message"];?></textarea><br/> </div> </form> <? } } else { ?> <!--Request More Info AKA Contact Page--> <!--Intro Text from Article--> <form action="#" id="contactForm" method="post"> <div id="contactFormLeft"> <? if($user_id > 0) { ?> <label> Your name </label><br/> <input type="text" name="name" value="<?=$user_data[0];?>"/><br/> <label> Your email </label><br/> <input type="text" name="email" value="<?=$user_data[1];?>"/><br/> <? } else { ?> <label> Your name </label><br/> <input type="text" name="name" value="<?=$_POST["name"];?>"/><br/> <label> Your email </label><br/> <input type="text" name="email" value="<?=$_POST["email"];?>"/><br/> <? } ?> <label> Subject </label><br/> <select name="subject"> <option value="support" <? if($_POST["subject"]=="support") { echo "selected ";}?>>Support</option> <option value="sales" <? if($_POST["subject"]=="sales") { echo "selected ";}?>>Consultation</option> <option value="training" <? if($_POST["subject"]=="training") { echo "selected ";}?>>Training</option> <option value="hr" <? if($_POST["subject"]=="hr") { echo "selected ";}?>>HR</option> </select> <br/> <input type="submit" id="submit" name="submit" value=""/> </div> <div id="contactFormRight"> <label> Message </label><br/> <textarea name="message"><?=$_POST["message"];?></textarea><br/> <!-----------ADDED FILE UPLOAD BOX ------------------> <label> Attach File: </label> <br/> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> <input type="file" name="fileatt" /> <br/> <!------------END FILE UPLOAD BOX---------------------> </div> </form> <? } ?> I have commented the changes I have added to the original code so that you can see what I have done. Any input on this would be greatly appreciated. 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 creating a system for my students. I teach Photography and I want to do more online integration for my class. As of right now I have a whole system in which the students have their on accounts on my site. Now the challenging part for me. I need students to upload photos to me, and I will critique them. My questions for this forum a 1. Should I have a line of code that creates a folder per user to upload photos to? 2. Should I have the photos stored in the SQL database? 3. Are there any scripts out there that can be easily adapted for this idea? Adam Hi, My Client wants me to create one gaming site using Core PHP. We can add flash games via admin. Please assist me to do this. If you any reference, pls send me. Waiting for your favorable responses. thanks, sundar These are the specs that come to mind, CPU, RAM, Storage, Bandwith
My question is this, once you know what the point of a website is, whether it is to host videos, design something with an editor, ecommerce, if I ask a costumer "How many people do you expect to be on your site?"
Is that a fair question? Or is that arbitrary or even rhetorical like "Duh... the maximum count"
I want to know based on what is being accessed whether it is the photos displayed on page, character count, flash / javascript, whatever... how can I estimate?
This is for assigning VPS's depending on the clients requirement
|