PHP - Detecting Mime Types
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.
Similar TutorialsHey 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'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; Probably a stupid question . . .
The MIME type in my php.ini file is set to text/html:
default_mimetype = "text/html"But, because I use XHTML 1.0 Strict, the MIME type of my web pages is set to text/xml: <meta http-equiv="content-type" content="text/xml; charset=utf-8" />I should therefore change the php.ini MIME type to text/xml, right? Hi all I am having a problem with an error message firing all the time? Code: [Select] if ((($_FILES["file"]["type"] != "application/zip")) || (($_FILES["file"]["type"] != "application/x-zip-compressed")) || (($_FILES["file"]["type"] != "application/x-zip"))) { header('Location: scontrol.php?alert=notzip'); } This is firing when I try uploading a zip, I have 2 questions, have I missed a MIME type (using Chrome) and is a Winrar ZIP different from a standard zip (its not a .rar file!) Thanks I sent an MIME email to an outlook account using Mail() and the HTML part was placed as an attachment for some reason. I dont get caught by most spam filters (just outlook and my school) but I wanted to get this worked out so I dont get caught by any spam filters. Can someone please take a look at my email system below and let me know if everything looks correct? Just in case you need this; I am using PostFix, Zimbra, running on Debian 6.0 (php5) //add From: header $headers = 'From:' . $from . "\n"; $headers .= 'Reply-To:' . $from . "\n"; $headers .= 'Return-Path:' . $from . "\n"; //specify MIME version 1.0 $headers .= "MIME-Version: 1.0\n"; //unique boundary $boundary = uniqid("market"); //tell e-mail client this e-mail contains//alternate versions $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n"; //plain text version of message $body = "--$boundary\r\n" . "Content-Type: text/plain; charset=ISO-8859-1\r\n" . "Content-Transfer-Encoding: base64\r\n\r\n"; //adds the remove to the string $body .= chunk_split(base64_encode($plaintxt)); //HTML version of message $body .= "--$boundary\r\n" . "Content-Type: text/html; charset=ISO-8859-1\r\n" . "Content-Transfer-Encoding: base64\r\n\r\n"; $body .= chunk_split(base64_encode($htmltxt)); $message = stripcslashes($body); $subject = stripcslashes($subject); mail($to1[$i], $subject, $message, $headers, "-f $from"); hi all new to php and having a sturggle with email.
I have a a form that when completed I wish to auto email the results to a new member simple enough . i also create a image with their unique name and member type and attach this to the email. I can attach the image and send an html email however I wish to send a plain text email along with this.
here lies the problem.
$to = $email ; $subject = 'some subject'; $bound_text = "010103689954"; $bound = "--".$bound_text."\r\n"; $bound_last = "--".$bound_text."--\r\n"; $headers = "From: <snip email removed>\r\n"; $headers .= "MIME-Version: 1.0\r\n" ."Content-Type: multipart/mixed; boundary=\"$bound_text\""; $message .= "If you can see this MIME than your client doesn't accept MIME types!\r\n" .$bound; /*HTML part of email*/ $message .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"; $message .="Content-Transfer-Encoding: 7bit\r\n\r\n"; $message .='<html><b>html version</b></html>\r\n' .$bound; /*Plain Text part of email*/ $message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n"; $message .="Plain text version\r\n" .$bound; /*Attachment part of the email adds jpeg memebrship card*/ $file = file_get_contents("create_membership_card.php?forename=$Forename&surname=$Surname&membership=$Membership"); $message .= "Content-Type: image/jpg; name=\"YourMembershipCard.jpg\"\r\n" ."Content-Transfer-Encoding: base64\r\n" ."Content-disposition: attachment; file=\"YourMembershipCard.jpg\"\r\n" ."\r\n" .chunk_split(base64_encode($file)) .$bound_last; mail($to, $subject, $message, $headers)This will send email in html and attach image but I can not get it to also send the plain/test version. example page to enter email and see what is sent http://www.hexhamcan....php?page=Email Any help with this would be great thanks in advance hope I have provided enough information Lee ps. great place you have here Edited by mac_gyver, 29 May 2014 - 07:26 PM. removed email address Is it not possible to get the mime type for a file uploaded using php? Am I going to be forced to use Pear? Php can read the mime type from an image, so why not from any file?? I recently changed something in an old script of mine and it doesn't work properly anymore. I don't know what I did, and I don't have a backup, oops! The code below is supposed to take inputs from a web form and turn them into an e-postcard, attaching and sending it as a jpeg on an email, ideally to be displayed inline. $name = $_POST['sendername']; $to = $_POST['recipient']; $from = $_POST['senderemail']; $subject = basename( $name)." has sent you a jCard!"; $message = $_POST['text']; $bcc = $_POST['bcc']; $finalimage = $_POST['finalimage']; //create a boundary string. It must be unique //so we use the MD5 algorithm to generate a random hash $random_hash = md5(date('r', time())); //define the headers we want passed. Note that they are separated with rn $headers = "From: ".$name." <".$from.">\r\nReply-To: ".$name." <".$from.">\r\nBcc: ".$bcc."\r\nX-Mailer: PHP/".phpversion();""; //add boundary string and mime type specification $headers .= "\r\nContent-Type: multipart/mixed; boundary='PHP-mixed-".$random_hash."'"; //read the attachment file contents into a string, //encode it with MIME base64, //and split it into smaller chunks $attachment = chunk_split(base64_encode(file_get_contents($finalimage))); //define the body of the message. ob_start(); //Turn on output buffering ?> --PHP-mixed-<?php echo $random_hash; ?> Content-Type: multipart/alternative; boundary='PHP-alt-<?php echo $random_hash; ?>' --PHP-alt-<?php echo $random_hash; ?> Content-Type: text/plain; charset='iso-8859-1'; Content-Transfer-Encoding: 7bit <?php echo $name; ?> sent you a jCard, click the attachment to view it. Send your own jCards at www.j-cards.co.uk! --PHP-alt-<?php echo $random_hash; ?> Content-Type: text/html; charset='iso-8859-1'; Content-Transfer-Encoding: 7bit <p><?php echo $name; ?> sent you this jCard:</p> <img src="cid:<?php echo $random_hash; ?>.jCard.jpg" /> <p>Send your own jCards at <a href="http://www.j-cards.co.uk">j-cards.co.uk</a>!</p> --PHP-alt-<?php echo $random_hash; ?>-- --PHP-mixed-<?php echo $random_hash; ?> Content-Type: image/jpeg; name='jCard.jpg' Content-Transfer-Encoding: base64 Content-ID: <<?php echo $random_hash; ?>.jCard.jpg> Content-Disposition: attachment; filename='/jCard.jpg' <?php echo $attachment; ?> --PHP-mixed-<?php echo $random_hash; ?>-- <?php //copy current buffer contents into $message variable and delete current output buffer $message = ob_get_clean(); //send the email $mail_sent = @mail( $to, $subject, $message, $headers ); //if the message is sent successfully return success page html. Otherwise return send fail html. echo $mail_sent ? "<html> snip... The email gets sent, and the source of the email looks identical to that of previous correctly displayed versions, but for some reason the email reader no longer renders the html, instead it just shows plain text, so it looks like the source just without headers - e.g.: Quote From: whoever@wherever.com To: friend@bestfriend.com --PHP-mixed-643f51499c414383c5735473100462e4 Content-Type: multipart/alternative; boundary='PHP-alt-643f51499c414383c5735473100462e4' --PHP-alt-643f51499c414383c5735473100462e4 Content-Type: text/plain; charset='iso-8859-1'; Content-Transfer-Encoding: 7bit Joe sent you a jCard, click the attachment to view it. Send your own jCards at www.j-cards.co.uk! --PHP-alt-643f51499c414383c5735473100462e4 Content-Type: text/html; charset='iso-8859-1'; Content-Transfer-Encoding: 7bit <p>Joe sent you this jCard:</p> <img src="cid:643f51499c414383c5735473100462e4.jCard.jpg" /> <p>Send your own jCards at <a href="http://www.j-cards.co.uk">j-cards.co.uk</a>!</p> --PHP-alt-643f51499c414383c5735473100462e4-- --PHP-mixed-643f51499c414383c5735473100462e4 Content-Type: image/jpeg; name='jCard.jpg' Content-Transfer-Encoding: base64 Content-ID: <643f51499c414383c5735473100462e4.jCard.jpg> Content-Disposition: attachment; filename='/jCard.jpg' /9j/4AAQSkZJRgABAQA... (base64 characters - very long - snipped) --PHP-mixed-643f51499c414383c5735473100462e4-- So everything is being sent, it's just an issue of getting it read correctly by the email program (worked before in gmail and hotmail). So I think it's an issue with the headers or boundary string I'm using, but they look alright to me, I just can't see what I've done wrong. Any ideas? Hey guys, Go easy on me, I'm not a large PHP coder at all however here is the issue I am having. I have acquired a wordpress plugin from a guy to deal with ticketing. From this plugin I am sending out a Mime multipart message with both HTML and plain text code. Here's the thing: If I send this out via gmail's SMTP server the message appears perfectly, however if I send it out via pro.turbo-smtp.com it arrives as an attachment due to the fact that in transit it seems to have lost it's Mime-Version: and Content-type: headers such as displayed below: Date: Fri, 19 Dec 2014 16:02:28 +0000 Return-Path: <REMOVEDADDRESS> To: REMOVEDADDRESS From: Name Here <REMOVEDADDRESS> Reply-To: Subject: Booking Confirmation Message-ID: <edc5de8156becec1bf53e402b25c9b93@REMOVED.co.uk> X-Priority: 3 X-Mailer: PHPMailer 5.2.7 (https://github.com/PHPMailer/PHPMailer/) MIME-Version: Content-Type: Content-Transfer-Encoding: 8bit --Part_A_aaa4586399e49459e0dce4368165275f Hey Mr A Sample, Thank you for booking with us.I am more than positive that this is not a PHP issue due to it appearing fine via google's SMTP server, but I am just wondering if anyone has ever came across such a thing and if anyone can shed any light? If anyone wants the PHP code I'm sure I can supply. Many thanks in advance!, Chris Hello, i have an upload form witch i cannot upload pdf it does not recognize the mine pdf type, any help please. here is the code $target_path = $_SERVER['DOCUMENT_ROOT'] . '/admin/upload/'; $target = "upload/".$HTTP_POST_FILES['uploadedfile']['name']; $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); $fileSize = $_FILES['uploadedfile']['size']; $fileType = $_FILES['uploadedfile']['type']; if ($_FILES['uploadedfile']['size'] > 0) { if (($_FILES["uploadedfile"]["type"] == "image/gif") || ($_FILES["uploadedfile"]["type"] == "image/jpeg") || ($_FILES["uploadedfile"]["type"] == "image/png" ) || ($_FILES["uploadedfile"]["type"] == "application/msword" ) || ($_FILES["uploadedfile"]["type"] == "application/pdf" ) && ($_FILES["uploadedfile"]["size"] < 512000)) { move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path); $query_upload="INSERT INTO upload (upload, chair, id_domeniu, email_1) VALUES ('" . $target . $_FILES['uploadedfile']['name'] . "', '3', '$id_domeniu', '".$_GET['email_1']."')"; $query_upload="UPDATE domenii SET upload='" . $target . $_FILES['uploadedfile']['name'] . "' WHERE email_1='".$email_1."'"; mysql_query($query_upload) or die(mysql_error()); } else { echo "<script language='javascript'>alert('Programul uploadat trebuie sa fie PDF, DOC, JPEG si mai mic de 500 kilobytes.');window.location = 'javascript:history.go(-1)';</script >"; exit(); } } Thanks in advance for any help you can provide on this. Bob G. BACKGROUND: I have an app that is hosted on Host Monster and its script includes a Class that is supposed to send MIME emails with or without attachments using only MIME types text, html, and image. It was working fine. I hadn't worked with or on it for about two months then found, last week, that it would no longer send emails even though the script runs without any Warnings. I've worked on this for several days now and I'm stuck. EXPECTED BEHAVIOR: When the script runs, it should send a simple text only email to a given email address and an more complex email that requires html and an in-line image in the body and an attachment with the same image. The image type is jpeg. ACTUAL BEHAVIOR: The script runs to completion with no Warning but sends neither of the two emails. CODE: Attached and cc'd below is a script which mimics the code in my app and the actual behavior described above but only for the simple email mentioned above. To simplify debug I've commented out that part of the script that should send out the more complex email mentioned above. Note: You can run the script by going to http://www.unitresearch03.com/Admin/SendUserEmailHM01.php Note: Line 6 can be changed to your own email address for testing BEGIN CODE: Code: [Select] <?php //TOP LINE CODE ////SIMPLE MIME EMAIL CODE - NO ATTACHMENTS ////////////////////////////////////////////// $mail = new mime_mail ; $mail->from = "ragsr@ix.netcom.com" ; $mail->to = "ragsr@ix.netcom.com" ; $mail->subject = "SIMPLE MIME EMAIL - NO ATTACHMENTS" ; $mail->body = "SIMPLE MIME EMAIL BODY" ; $mail->send() ; ////END OF SIMPLE MIME EMAIL CODE //////////////////////////////////////////////////////// ////START MIME EMAIL CODE - ALLOWS ATTACHEMENTS ///////////////////////////////////////////////// //SIMPLE SEND EMAIL PG.448 PHP REFERENCE PLUS ATTACHMENT EXAMPLE FROM SAME PAGE //include "mime_mail.inc"; //THIS CAUSED A WARNING AND, APPARENTLY, IS NOT REQUIRED. CODE OK W/O IT //READ FILE $filename="/home1/unitcons/public_html/unitresearch03/TCStripComposition-27Cb.jpg" ; $content_type="image/jpeg" ; //OPEN, EXTRACT DATA, THEN CLOSE FILE $fd=fopen($filename, "r") ; $data=fread($fd, filesize($filename)) ; fclose($fd) ; $fileX="/home1/unitcons/public_html/unitresearch03TCStripComposition-27Cb.jpg" ; $ftype=filetype ($filename) ; $fsize=filesize($filename) ; //echo "FILE TYPE :"."$ftype"."<br>" ; //echo "FD FILE TYPE :"."$fdltype"."<br>" ; //echo "DATA :"."$data"." END DATA"."<br>" ; //echo "FSIZE :"."$fsize"."<br>" ; //echo "FDSIZE :"."$fsize"."<br>" ; //echo "FD :"."$fd"."<br>" ; //CREATE OBJECT INSTANCE $mail = new mime_mail ; //SET ALL DATA SLOTS $mail->from = "thromptmweeklycs@unitresearch03.com" ; $mail->to = "ragsr@ix.netcom.com" ; $mail->subject = "XXXThrompTM Weekly Comic Strip - Week of 6/20/201" ; $mail->body = "<html>Hope you enjoy your ThrompTM today! <br> <br> <br> <img src=http://www.unitresearch03.com/TCStripComposition-27Cb.jpg height='197' width='500' > </html>"; //DEFINE ATTACHMENT $name = $fileX ; $message = $data ; //ADD ATTACHEMENT //$mail->add_attachment ($data, $filename, $content_type) ; //SEND EMAIL //$mail->send() ; ////EBD SEND EMAIL WITH ATTACHMENT ////MIME CLASS class mime_mail { var $parts; var $to; var $from; var $headers; var $subject; var $body ; /* * void mime_mail() * class constructor */ function mime_mail () { $this->parts = array() ; $this->to = "" ; $this->from = "" ; $this->subject = "" ; $this->body = "" ; $this->headers = "" ; } /* * void add_attachement (string message, [string name], [string ctype]) * Add an attachment to the mail object */ function add_attachment ($message, $name = "", $ctype = "text/html jpeg" ) //function add_attachment ($data, $fileX, $content_type ) { echo "CTYPE IN AA :"."$ctype"."<br>" ; //echo "MESSAGE IN AA :"."$message"."<br>" ; echo "ENCODE IN AA: "."$encode"."<br>" ; echo "NAME IN AA :"."$name"."<br>" ; //echo "DATA IN AA :"."$data"."<br>" ; $partsd = $this->parts[] = array ( "ctype" => $ctype, "message" => $message, "encode" => $encode, "name" => $name, ); echo ("ARRAY#1 CTYPE :"."$partsd[ctype]"."<br>") ; //echo ("ARRAY#2 MESSAGE :"."$partsd[message]"."<br>") ; echo ("ARRAY#3 ENCODE :"."$partsd[encode]"."<br>") ; echo ("ARRAY#4 NAME :"."$partsd[name]"."<br>") ; //echo ("ARRAY#5 DATA :"."$partsd[data]"."<br>") ; $sizeX=sizeof($this->parts) ; echo "SIZE OF ARRAY IN ADD ATTACHMENT:"."$sizeX"."<br>" ; } /* * void build_message (array part= * Build message parts of an multipart mail */ function build_message ($part ) { $message = $part[ "message"]; //echo "MESSAGE IN BUILD:"."$message"."<br>" ; $message = chunk_split(base64_encode($message)) ; //echo "MESSAGE :"."$message"."<br>" ; $encoding = "base64" ; $partctype = $part["ctype"] ; $partname = $part["name"] ; echo "PART CTYPE :"."$partctype"."<br>" ; echo "PART NAME :"."$partname"."<br>" ; return "Content-Type: ".$part["ctype"]. ($part["name"]?" ; name =\"". $part["name"]. "\"":""). "\nContent-Transfer-Encoding: $encoding\n\n$message\n" ; } /* * void build_multipart() * Build a multipart mail */ function build_multipart() { $boundary = "b".md5(uniqid(time())) ; $multipart = "Content-Type: multipart/mixed; boundary = $boundary\n\nThis is a MIME encoded message.\n\n--$boundary" ; //$sizeX=sizeof($this->parts) ; //echo "SIZE OF ARRAY :"."$sizeX"."<br>" ; for ($i = sizeof($this->parts)-1; $i >= 0; $i--) { $multipart .= "\n".$this->build_message($this->parts[$i])."--$boundary" ; //echo "MULTIPART :"."$multipart"."<br>" ; } return $multipart.= "--\n" ; } /* * string get_mail() * returns the constructed mail */ function get_mail($complete = true) { $complete = true ; echo "COMPLETE :"."$complete"."<br>" ; ////STAEMENT ADDED TO FORCE IF ($COMPLETE) {} BELOW TO RUN //echo "MESSAGE IN GET MAIL:"."$message"."<br>" ; $mime = "" ; if (!empty($this->from)) $mime .= "From: ".$this->from. "\n" ; echo "MIME 1:"."$mime"."<br>"; if (!empty($this->headers)) $mime .= $this->headers. "\n" ; echo "MIME 2:"."$mime"."<br>"; if ($complete) { echo "MIME 3:"."$mime"."<br>"; if (!empty($this->to)) { $mime .= "To: $this->to\n" ; echo "MIME 4:"."$mime"."<br>"; } if (!empty($this->subject)) { $mime .= "Subject: $this->subject\n" ; echo "MIME 5:"."$mime"."<br>"; } } if (!empty($this->body)) $this->add_attachment($this->body, "", "text/html"); echo "MIME 55:"."$mime"."<br>"; $mime .= "MIME-Version: 1.0\n".$this->build_multipart() ; echo "MIME 6:"."$mime"."<br>"; return $mime; } /* * void send() * Send the mail (last class-function to be called) */ //function send ($message, $data, $fileX, $content_type) function send () { //$bodyY=$this->body ; //echo "BODYY :"."$bodyY"."<br>" ; $mime=$this->get_mail () ; echo "MIME 7:"."$mime"."<br>" ; mail($this->to, $this->subject, "" , $mime) ; //mail($this->to, $this->subject, $this->body, $mime) ; } } ; ////END OF MIME CLASS CODE ///////////////////////////////////////////////////////////////// ?>END CODE: Hello,
I'm having a huge issue right now decoding a zip file from an attachment with a content-encoding of quoted-printable. I have tried a couple different methods (such as decoding the entire attachment or decoding it line by line), but none have produced a valid file when saved. What I don't understand is that I can download and open the file in Outlook fine, so there must be something wrong with the decoder. Here is a code snippet of my recent attempt:
elseif ($transferEncoding == 'quoted-printable'){ $fileError = true; $attachmentParts = explode("\n", $currentPart->getContent()); $attachmentArray = array(); foreach ($attachmentParts as $line){ array_push($attachmentArray, quoted_printable_decode($line)); } $attachment = implode("", $attachmentArray); file_put_contents($unzipPath . '.zip', $attachment); } $unzipper = new Decompress(array( 'adapter' => 'Zip', 'options' => array( 'target' => $unzipPath, ) )); $unzipper->filter($unzipPath . '.zip'); unlink($unzipPath . '.zip');I'm using Zend Framework 2 methods for unzipping the file when it's done, but there is a CRC error because the file is getting corrupted during the decode. This is how the file compares to the original (using Beyond Compare 3): So it is finding the hex for CLRF and removing it from the file. Any ideas on this would be greatly appreciated as I have been trying to solve this for about a month now. Thanks, -mcfloyd I am trying to eliminate this issue but I have had no luck here is my current code: Code: [Select] $from = 'help@my.com'; $body = "<html>\n"; $body .= "<body style=\"font-family:Verdana, Verdana, Geneva, sans-serif;\">\n"; $body .= $message; $body .= "</body>\n"; $body .= "</html>\n"; $boundary = uniqid('np'); $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; $headers = "From: $from"; $headers .= "\nMIME-Version: 1.0\n" ."Content-Type: multipart/alternative;\n" ." boundary=\"{$mime_boundary}\""; $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/html; \n" . "Content-Transfer-Encoding: 7bit\n\n" . $body . "\n\n" . "--{$mime_boundary}--\n"; mail($to, $subject, $message, $headers, '-f'.$from); I have tried adding the plain text part but nothing has worked, could someone else look at this and show me what I need to add so that it has the text/plain MIME part as well? What types of data can the $_SESSION cookie store? Objects? Resources? And how are these stored in text form? 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 I need a regular expression that detects a web address in a string of text. I need it to find any http://www or www. web address. Any domain (.co.uk, .com anything) All these would be picked up: http://domain.com http://www.domain.com www.domain.com http://domain.co.uk http://www.domain.co.uk www.domain.co.uk Also, it must pick up all folders and other url variables (www.site.com/page1?a=123 etc.) ** Also, most importantly:*** It must NOT pick up web addresses that are inside a <a href="">xxx</a> link already, only oes that are plain text and not embedded in this HTML. I have tried but it only does bits of the above. I can do the PHP code, just need to know the regular expression to drop into my preg_match_all code. Thanks in advance. 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. 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 |