r/learnphp • • Jan 31 '19

College Project

3 Upvotes

Hey guys,

For this semester of college, we have server-side web development. We are using HTML, CSS, JS & PHP to create the website. The whole premise of the final project is to create a landing page, a login & registration page & an upload area for users to upload their CV's so they can download them at a later time. I have experience in C, but I am pretty new to PHP.

Would you guys have any recommendations of websites/tutorials to use to meet the above requirements for the project?

Thanks,

WebDevIE


r/learnphp • • Jan 03 '19

How do you make a session run only for 30 minutes?

3 Upvotes

r/learnphp • • Nov 14 '18

Need good courses for beginner

3 Upvotes

Hi guys . I got a practica in a Webdesign firm. I need to learn php with laravel. I got some python and java knowledge but still a beginner . Do you know of good courses I could take ?


r/learnphp • • Oct 27 '18

Question on CORS

3 Upvotes

Guys hi,

When doing testing/developing previous dev added this to .htaccess:

<IfModule mod_setenvif.c>
  <IfModule mod_headers.c>
    <FilesMatch "\.(gif|png|jpe?g|svg|svgz|ico|webp)$">
      SetEnvIf Origin ":" IS_CORS
      Header set Access-Control-Allow-Origin "*" env=IS_CORS
    </FilesMatch>
  </IfModule>
</IfModule>

<IfModule mod_headers.c>
  <FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css|css)$">
    Header set Access-Control-Allow-Origin "*"
  </FilesMatch>
</IfModule>

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token, X-Accept-Charset,X-Accept"

And we still have it in .htaccess after testing was done. As far as i understand it's a potential security issues and should be removed. Am i right? Could you explain what each "paragraph" does?


r/learnphp • • Oct 25 '18

What is a one-armed conditional statement?

3 Upvotes

I was forced into doing PHP as 'mandatory elective' (god knows how that actually works or how it even makes sense) but out tutor has made it clear that they will not be teaching it to us, its down to us to learn on our own. But her English is appalling and trying to transcribe her assignment sheets is just as much work as the work itself.

We had to create a game and then repeat the same game but using 'a one armed conditional statement' instead. I searched for 'php one armed conditional statement' and all I could find on it was a link to one blank page from another college (http://www.cs.ucc.ie/~dgb/courses/pwd/27/php-one-armed-conditionals1.html) and nothing else that explains it. I tried with out the 'php' in front, thinking it might just be programming lingo but I found even less mentions of it. Is it a real thing? I'm started pulling my hair out over this, I can't find anything about it and she won't answer questions on the assignments.


r/learnphp • • Sep 11 '18

PHP/HTML/PHPMailer issues

3 Upvotes

Never been into backend stuff but I'm trying to do more and more. For some reason email scripts always get me. When I try the example script it works perfectly so I know my setup and inlog is fine. Buut when I'm trying to hackbuild it around my own form it doesn't send anything.

Down below is the code. Don't go too hard on me ;)
(I also probably hilarously tried to show what errors it was shooting with the $rorre variable to debug it but to no avail)

<?php
/**
 * This example shows how to handle a simple contact form.
 */
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
$msg = '';
$rorre= '';

//Don't run this unless we're handling a form submission
if (array_key_exists('email', $_POST)) {
    date_default_timezone_set('Etc/UTC');
    require 'vendor/autoload.php';

    //Create a new PHPMailer instance
    $mail = new PHPMailer;

    //Tell PHPMailer to use SMTP - requires a local mail server
    //Faster and safer than using mail()
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';                       // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = '[email protected]';    // SMTP username
    $mail->Password = '----';                      // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Use a fixed address in your own domain as the from address
    //**DO NOT** use the submitter's address here as it will be forgery
    //and will cause your messages to fail SPF checks
    $mail->setFrom('[email protected]', '---');

    //Send the message to yourself, or whoever should receive contact for submissions
    $mail->addAddress('---.nl', '----');

    //Put the submitter's address in a reply-to header
    //This will fail if the address provided is invalid,
    //in which case we should ignore the whole request
    if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
        $mail->Subject = 'PHPMailer contact form';

        //Keep it simple - don't use HTML
        $mail->isHTML(false);

        //Build a simple message body
        $mail->Body = <<<EOT
        Email: {$_POST['email']}
        Name: {$_POST['name']}
        Message: {$_POST['message']}
EOT;
        //Send the message, check for errors
        if (!$mail->send()) {

            //The reason for failing to send will be in $mail->ErrorInfo
            //but you shouldn't display errors to users - process the error, log it on your server.
            $msg = 'Sorry, something went wrong. Please try again later.';
        } else {
            $msg = 'Message sent! Thanks for contacting us.';
        }
    } else {
        $msg = 'Invalid email address, message ignored.';
    }
}
?>

<html>
    <head>
    
      <meta name="robots" content="noindex">
      <meta name="googlebot" content="noindex">

            <link href="https://fonts.googleapis.com/css?family=Raleway"rel="stylesheet">
            <link href="https://fonts.googleapis.com/icon?family=Material+Icons"rel="stylesheet">
            <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" media="screen,projection" rel="stylesheet" type="text/css">
            <link href="css/styles.css" rel="stylesheet" type="text/css">
                    
    </head>
    <body>
            <header>
                    <div class="row center-align header"> 
                   <div id="slideshow">
                     <div>
                       <img src="img/faber.jpg">
                     </div>
                     <div>
                       <img src="img/koen.jpg">
                     </div>
                        <div>
                       <img src="img/staatvast.jpg">
                     </div>
                        <div>
                       <img src="img/koen.jpg">
                     </div>
                  </div> 
                  </div>
                  </header>
                  <main>
                  <div class="container">
                    <div class="row intro" id="Intro">
                       <p><b>
                       <?php if (!empty($msg)) {
                            echo "<h2>$msg</h2>";
                        } ?>
                        </b></p>
                        <p><b>
                            <?php { echo "<h2>$rorre</h2>"; } ?>
                        </b></p>
                      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque cursus, dui id vehicula sagittis, diam purus feugiat mauris, accumsan porta purus tellus at elit. Vivamus ut vulputate ex. Etiam convallis ante sed ante faucibus, quis pulvinar mi mollis. Nam dictum ante a aliquam dapibus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas at malesuada elit, sit amet venenatis sem. Maecenas accumsan feugiat tortor in interdum. Nam lobortis risus non finibus posuere. Donec pellentesque quis purus nec pellentesque. Donec non scelerisque lacus.</p>
                      <p>Mauris et leo dictum mauris euismod aliquet accumsan sed felis. Suspendisse non luctus diam, nec tempus magna. In tempus ante quam. Integer elementum sollicitudin laoreet. Vestibulum fermentum justo eu consequat efficitur. Pellentesque et vehicula mauris, at dictum est. Donec nec aliquet sapien.</p>
                    </div>
                    <form method="POST">
                      <div class="row" id="ResInitNaam">
                        <div class="col s6 l2">
                           <div class="input-field">
                              <input id="resource" pattern="(R|r|[0-9])[0-9]{1,9}" type="text" class="validate" required>
                              <label for="resource">Res-/persnr.</label>
                           </div>
                        </div>
                        <div class="col s6 l2">
                           <div class="input-field">
                              <input id="initialen" type="text" class="validate" style="text-transform: uppercase;" required>
                              <label for="initialen">Initialen</label>
                           </div>
                        </div>
                        <div class="col s6 l4">
                           <div class="input-field">
                              <input id="voornaam" type="text" class="validate" required>
                              <label for="voornaam">Voornaam</label>
                           </div>
                        </div>
                        <div class="col s6 l4">
                           <div class="input-field">
                              <input id="achternaam" type="text" class="validate" required>
                              <label for="achternaam">Achternaam</label>
                           </div>
                        </div>
                  </div>
                      <div class="row" id="GebTelMail">
                        <div class="col s6 l2">
                           <div class="input-field">
                              <input id="geboortedatum" type="text" class="datepickerBirth" required>
                              <label for="geboortedatum">Geboortedatum</label>
                           </div>
                        </div>
                        <div class="col s6 l4">
                           <div class="input-field">
                              <input id="geboorteplaats" type="text" class="validate" required>
                              <label for="geboorteplaats">Geboorteplaats</label>
                           </div>
                        </div>
                        <div class="col s6 l2">
                           <div class="input-field">
                              <input id="telefoonnummer" pattern="(?:0|(?:\+|00) ?31 ?)(?:(?:[1-9] ?(?:[0-9] ?){8})|(?:6 ?-? ?[1-9] ?(?:[0-9] ?){7})|(?:[1,2,3,4,5,7,8,9]\d ?-? ?[1-9] ?(?:[0-9] ?){6})|(?:[1,2,3,4,5,7,8,9]\d{2} ?-? ?[1-9] ?(?:[0-9] ?){5}))" type="text" class="validate" required>
                              <label for="telefoonnummer">Telefoonnummer</label>
                           </div>
                        </div>
                        <div class="col s6 l4">
                           <div class="input-field">
                              <input id="emailadres" type="email" class="validate" required>
                              <label for="emailadres">Email</label>
                           </div>
                        </div>
                  </div>
                      <div class="row" id="StraatHuisnummer">
                        <div class="col s8">
                           <div class="input-field">
                              <input id="straat" type="text" class="validate" required>
                              <label for="straat">Straat</label>
                           </div>
                        </div>
                        <div class="col s4">
                           <div class="input-field">
                              <input id="huisnummer" type="text" class="validate" required>
                              <label for="huisnummer">Huisnummer</label>
                           </div>
                        </div>
                  </div>
                      <div class="row" id="PostcodeWoonplaats">
                        <div class="col s4">
                           <div class="input-field">
                              <input id="postcode" type="text" pattern="[1-9][0-9]{3}\s?[a-zA-Z]{2}" class="validate" required>
                              <label for="postcode">Postcode</label>
                           </div>
                        </div>
                        <div class="col s8">
                           <div class="input-field">
                              <input id="plaats" type="text" class="validate" required>
                              <label for="plaats">Plaats</label>
                           </div>
                        </div>
                  </div>
                      <div class="row" id="CodeCatKM">
                          <div class="input-field col s6 l4">
                            <select required>
                              <option value="" disabled selected>Label</option>
                              <option value="1">Faber</option>
                              <option value="2">Koen</option>
                              <option value="3">Staatvast</option>
                              <option value="4">Voort</option>
                            </select>
                          </div>
                          <div class="input-field col s6 l4">
                             <select id="klasseid" required>
                               <option value="" disabled selected>Klasse Auto</option>
                               <option value="A">A</option>
                               <option value="B">B</option>
                               <option value="C">C</option>
                               <option value="C+">C+</option>
                               <option value="D">D</option>
                             </select>
                           </div>
                          <div class="input-field col s12 l4">
                              <input id="kilometers" type="number" class="validate">
                              <label for="kilometers">Verwacht aantal kilometers per jaar</label>
                          </div>
                  </div>
                      <div class="row" id="Afleveren">
                        <div class="input-field col s6">
                           <div class="input-field">
                              <input id="afleverdatum" type="text" class="datepicker validate" required>
                              <label for="afleverdatum">Afleverdatum</label>
                           </div>
                        </div>
                        <div class="input-field col s6">
                          <div class="input-field">
                             <select id="vestigingkiezer" required>
                               <option value="" title="" disabled selected>Afleverlocatie</option>
                               <option value="1" title="Schurenbergweg 14, 1105AR  Amsterdam-Zuidoost">Fleetport Regio Amsterdam</option>
                               <option value="2" title="Van Oldenbarneveldtstraat 118, 6827AN Arnhem">Fleetport Regio Arnhem</option>
                               <option value="3" title="Konijnenberg 37a, 4825BC  Breda">Fleetport Regio Breda</option>
                               <option value="4" title="Ekkersrijt 2023, 5692BB  Son">Fleetport Regio Eindhoven</option>
                               <option value="5" title="Osloweg 127, 9723BK  Groningen">Fleetport Regio Groningen</option>
                               <option value="6" title="Belder 96 H, 4704RK  Roosendaal">Fleetport Regio Roosendaal</option>
                               <option value="7" title="Edisonlaan 24, 2665JC  Bleiswijk">Fleetport Regio Rotterdam</option>
                               <option value="8" title="Milieuparkweg 2, 6136KP  Sittard">Fleetport Regio Sittard</option>
                               <option value="9" title="Brabanthaven 8, 3433PJ  Nieuwegein">Fleetport Regio Utrecht</option>
                               <option value="10" title="Marsweg 3, 8013PD  Zwolle">Fleetport Regio Zwolle</option>
                             </select>
                            <span class="helper-text" data-error="wrong" data-success="right" id="fleetportadres"></span>
                          </div>
                        </div>
                      </div>
                      <div class="row" id="Aanvragerrow">
                        <div class="col s6">
                           <div class="input-field">
                              <input id="aanvrager" type="text" class="validate" required>
                              <label for="aanvrager">Naam aanvrager</label>
                           </div>
                        </div>
                        <div class="col s6">
                           <div class="input-field">
                                <input id="aanvragermail" type="email" class="validate" required>
                              <label for="aanvragermail">Email aanvrager</label>
                           </div>
                        </div>
                    </div>
                      <div class="row center-align" id="submitbutton">
                        <button class="btn-large waves-effect waves-light" type="submit" >Submit
                          <i class="material-icons right">directions_car</i>
                        </button>
                      </div>
                    </form>
                  </div>
                  </main>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
            <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
            <script src="js/scripts.js"></script>
    </body>
</html>

r/learnphp • • Sep 01 '18

How to echo items in a row result item if row result item is an array?

3 Upvotes

I am echoing out some data like this

while($row = $result->fetch_assoc()) {
    echo
    '<ul>' 
	. '<li>'.$row["make"].'</li>'
	. '<li>'.$row["year"].'</li>'
	. '<li>'.$row["color"].'</li>'
	. '<li>'.$row["service"].'</li>'
	. '<li>'.$row["addons"].'</li>'
    . '</ul>';
}

but $row["addons"] is an array that i would like to loop through and echo out the items. I am having a heck of a time trying to google for this.

How could I achieve this?

thank you.


r/learnphp • • Jul 29 '18

What's the point of specifying initial parameter values in a function argument?

3 Upvotes

For example:

function my_func($str = '', $bool = null) {
    // do stuff
}

// call function
my_func('hello', false);

I mean I think you need/have to pass in the right number of arguments for the function to work anyway.


r/learnphp • • Jun 20 '18

Can you run two methods that read external data simultaneously?

3 Upvotes

Hello,

I am asking this question because I am working on a script that will check the status of a tracking number that can be from two different mail companies, one American and the other Mexican.

Rather than having two different if statements that do the same thing I decided to instead have one if statement that will check if the tracking number has been stated as delivered on either of the companies.

In the theory of betogm this should work fine, in practice it doesn't work. I want to know if I did this correctly.

Can you please help me? Thanks!

If statement:

$tablaTracking = listadoTrackingsEnviadosParaCorreosDiarios();
if(mysqli_num_rows($tablaTracking) > 0){
    $i = 0;
	while($registro = mysqli_fetch_assoc($tablaTracking) && $i <= 100){
	    $tracking = $registro['art_traking'];
	    if(entregado($tracking) == "entregado" || rastreoRedpack($tracking) == "entregado"){
		    $listaArticuloTracking = listadoArticulosTracking($tracking);
		    while($regArt = mysqli_fetch_assoc($listaArticuloTracking)){
		        $articulo = $regArt['art_id_verificador'];
		        updateExportacionNoCorreo($articulo, '1');
		        updateEstatusCorreoExpoArticulo($articulo, '3');
		        updateExportacionPagEnviado($articulo);
		    }
		    $i++;
	    }
	}
}

Functions:

function entregado($tracking){
	$url = "http://production.shippingapis.com/shippingAPI.dll";
	$xmlRequest = $url.'?API=TrackV2&XML='.rawurlencode('<?xml version="1.0" encoding="UTF-8" ?><TrackRequest USERID="aaaaaaa"> ');
	$xmlRequest = $xmlRequest.rawurlencode('<TrackID ID="'.$tracking.'"></TrackID>');
	$xmlRequest = $xmlRequest.rawurlencode('</TrackRequest>');
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$xmlRequest);
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_HTTPGET, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$result = curl_exec($ch);
	curl_close($ch);

	$response = new SimpleXMLElement($result);
	$summary = (string) $response->TrackInfo->TrackSummary;
		
	if(stristr($summary,"delivered") or stristr($summary,"picked up") or stristr($summary, "available at a PO Box") ) return "entregado";
	elseif(stristr($summary, "return") or stristr($summary, "undeliverable as addressed")) return "devuelto";
}

function rastreoRedpack($tracking){
    $client = new SoapClient("https://ws.redpack.com.mx/RedpackAPI_WS/services/RedpackWS?wsdl");
    /**/$params = new SoapVar('<rastreo xmlns="http://ws.redpack.com">
    <PIN>PROD aaaaaaaaaaaaa</PIN>
    <idUsuario>aaaa</idUsuario>
    <guias>
    <ns1:numeroDeGuia xmlns:ns1="http://vo.redpack.com/xsd">'.$tracking.'</ns1:numeroDeGuia>
    </guias>
    </rastreo>',XSD_ANYXML);
    $response = $client->__soapCall('rastreo', array($params));
    $estatus = $response->return->paquetes->detallesRastreo[0]->evento;
    
    return strtolower($estatus);
}

r/learnphp • • Jun 15 '18

AJAX Validation with Google ReCaptcha

3 Upvotes

So I have figured out where I was going wrong and it was with the Google ReCaptcha.

I have a contact form that performs server side validation using JSON. I need to add check on Google ReCaptcha and throw an error message if it was skipped.

How can I properly do this?

PHP Script:

<?php

$errors         = array();  	// array to hold validation errors
$data 			= array(); 		// array to pass back data

// validate the variables ======================================================
	// if any of these variables don't exist, add an error to our $errors array

	if (empty($_POST['firstName']))
		$errors['firstName'] = 'First Name is required.';

	if (empty($_POST['lastName']))
		$errors['lastName'] = 'Last Name is required.';

	if (empty($_POST['companyName']))
		$errors['companyName'] = 'Company Name is required.';

	if (empty($_POST['companyAddress']))
		$errors['companyAddress'] = 'Company Address is required.';

	if (empty($_POST['city']))
		$errors['city'] = 'City is required.';

	if (empty($_POST['state']))
		$errors['state'] = 'State is required.';

	if (empty($_POST['emailAddress']))
		$errors['emailAddress'] = 'Email Address is required.';

	if (empty($_POST['comment']))
		$errors['comment'] = 'Comment is required.';

// return a response ===========================================================

	// if there are any errors in our errors array, return a success boolean of false
	if ( ! empty($errors)) {

		// if there are items in our errors array, return those errors
		$data['success'] = false;
		$data['errors']  = $errors;
	} else {

		// if there are no errors process our form, then return a message

		// DO ALL YOUR FORM PROCESSING HERE
		// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)

		// show a message of success and provide a true success variable
		$data['success'] = true;
		$data['message'] = 'Success!';
	}

	// return all our data to an AJAX call
	echo json_encode($data);

Javascript:

// Start
$(document).ready(function() {

	// process the form
	$('form').submit(function(event) {

		$('.form-group').removeClass('has-error'); // remove the error class
		$('.help-block').remove(); // remove the error text

		// get the form data
		// there are many ways to get this data using jQuery (you can use the class or id also)
		var formData = {
			'firstName' 				: $('input[name=firstName]').val(),
			'lastName' 				: $('input[name=lastName]').val(),
			'companyName' 				: $('input[name=companyName]').val(),
			'companyAddress' 				: $('input[name=companyAddress]').val(),
			'city' 				: $('input[name=city]').val(),
			'state' 				: $('input[name=state]').val(),
			'emailAddress' 			: $('input[name=emailAddress]').val(),
			'comment' 	: $('input[name=comment]').val()
		};

		// process the form
		$.ajax({
			type 		: 'POST', // define the type of HTTP verb we want to use (POST for our form)
			url 		: 'formMaster.php', // the url where we want to POST
			data 		: formData, // our data object
			dataType 	: 'json', // what type of data do we expect back from the server
			encode 		: true
		})
			// using the done promise callback
			.done(function(data) {

				// log data to the console so we can see
				console.log(data);

				// here we will handle errors and validation messages
				if ( ! data.success) {

					// handle errors for name ---------------
					if (data.errors.firstName) {
						$('#firstName-group').addClass('has-error'); // add the error class to show red input
						$('#firstName-group').append('<div class="help-block">' + data.errors.firstName + '</div>'); // add the actual error message under our input
					}

					// handle errors for name ---------------
					if (data.errors.lastName) {
						$('#lastName-group').addClass('has-error'); // add the error class to show red input
						$('#lastName-group').append('<div class="help-block">' + data.errors.lastName + '</div>'); // add the actual error message under our input
					}

					// handle errors for name ---------------
					if (data.errors.companyName) {
						$('#companyName-group').addClass('has-error'); // add the error class to show red input
						$('#companyName-group').append('<div class="help-block">' + data.errors.companyName + '</div>'); // add the actual error message under our input
					}

					// handle errors for Company Address ---------------
					if (data.errors.companyAddress) {
						$('#companyAddress-group').addClass('has-error'); // add the error class to show red input
						$('#companyAddress-group').append('<div class="help-block">' + data.errors.companyAddress + '</div>'); // add the actual error message under our input
					}

					// handle errors for Company Address ---------------
					if (data.errors.city) {
						$('#city-group').addClass('has-error'); // add the error class to show red input
						$('#city-group').append('<div class="help-block">' + data.errors.city + '</div>'); // add the actual error message under our input
					}

					// handle errors for Company Address ---------------
					if (data.errors.state) {
						$('#state-group').addClass('has-error'); // add the error class to show red input
						$('#state-group').append('<div class="help-block">' + data.errors.state + '</div>'); // add the actual error message under our input
					}

					// handle errors for Email Address ---------------
					if (data.errors.emailAddress) {
						$('#emailAddress-group').addClass('has-error'); // add the error class to show red input
						$('#emailAddress-group').append('<div class="help-block">' + data.errors.emailAddress + '</div>'); // add the actual error message under our input
					}

					// handle errors for superhero alias ---------------
					if (data.errors.comment) {
						$('#comment-group').addClass('has-error'); // add the error class to show red input
						$('#comment-group').append('<div class="help-block">' + data.errors.comment + '</div>'); // add the actual error message under our input
					}

				} else {

					// ALL GOOD! just show the success message!
					$('form').append('<div class="alert alert-success">' + data.message + '</div>');

					// usually after form submission, you'll want to redirect
					// window.location = '/thank-you'; // redirect a user to another page

				}
			})

			// using the fail promise callback
			.fail(function(data) {

				// show any errors
				// best to remove for production
				console.log(data);
			});

		// stop the form from submitting the normal way and refreshing the page
		event.preventDefault();
	});

});

I know that I need to input this code into the PHP but I am not sure how exactly should I feed it back to the Javascript for processing.

// ---------------------Start the recaptcha ------------------------------------//
if(isset($_POST['g-recaptcha-response']) && ($_POST['g-recaptcha-response'])){
				session_start();
		$ip = $_SERVER['REMOTE_ADDR'];
		$captcha = $_POST['g-recaptcha-response'];
		$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$captcha&remoteip=$ip");
		$result = json_decode($response,TRUE);
				if($result['success'] == 1){
						$_SESSION['result'] = $result['success'];
						}
// --------------------End Of the Captcha Check------------------------- //

And I got this portion:

		// ---------------------Start the recaptcha ------------------------------------//

	if(!isset($_SESSION['result']) || $_SESSION['result'] == 0){
		 	$errors[] =  'Captcha Error';
	}

	// --------------------End Of the Captcha Check------------------------- //

But when I add this in, the form becomes non-responsive with no errors thrown at all. Nothing in console log, absolutely nothing. What am I doing wrong?


r/learnphp • • Jun 14 '18

Why was my POST PHP endpoint not recognizing a POST send from Python?

3 Upvotes

edit: to clarify, the PHP POST endpoint is hit by the Python POST script, I did some server side logging on the PHP Post endpoint when it was called. But the $_SERVER/$_POST were empty when dumped. I was only able to get a GET type request to work.


I feel like I don't actually know how to write "APIs". I mean I can serve/receive stuff eg. create JSON object string and dump it, and also design specific endpoints that expect parameters that are then inserted into MySQL.

I say "expects parameters" because when I start using Node more I think I want to adopt a "can accept anything" method like a blob, so I can use Node as a proxy for a lot of random post requests and take advantage of that non-event blocking aspect.

Anyway the actual question.

So I would have my PHP endpoint look like this:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // get a parameter
    $expected parameter = $_POST['parameter_key'];
}

That approach has worked for me when everything is in the same spot with AJAX through CORS.

I don't think I've actually created a POST endpoint in PHP that can accept from anywhere, unless it's requested back end(say another PHP script).

Yeah I can't think off hand of any running instances where I am accepting POST requests from random clients.

So I've been getting by using GET whether by GET parameters or building a parameterized url.

From python I did a request like this:

import requests

requests.post(‘POST-expecting-endpoint', data = { ‘parameter_key’: parameter_val})

But when I dump $_POST and $_REQUEST, there's nothing. I was able to solve this problem by not solving it, eg. using params through python instead of data which made it a GET request. I changed my POST event to a GET event and used GET['parameter_key']

So I'm wondering, like for example I used this testing tool someone made that you can send post requests to and it works.

With AJAX I think what I send is form_data and the $_POST works as expected.

So I'm not sure, what am I missing?

Sorry I know this is PHP not about Python but it's joined, primarily focused on PHP(the POST receiving endpoint).

For the front-end POST with JavaScript I use either jQuery or mostly a plain AJAX script such as this one from MDN:

I'm trying to use Fetch but it wasn't working on the stuff I wrote.


r/learnphp • • Jun 02 '18

Best .csv format to import

3 Upvotes

Hi,

I'm learning PHP and mySQL and using a recipe app to do so. I am trying to pull in ingredients from recipes on allrecipes.com as example here. I am creating a .csv file, but finding this to be very manual work. I am using phpMyAdmin locally to add stuff to my database (tables, columns, data) because I am not knowledgeable enough to do this through commands, yet. When importing I use semi-colon (;) as my separator, which seems to be working, since I have commas in the text. I am just finding creating the doc takes forever.

What format is best to put my import file into? Right now I am using notepad to create lines. My table is setup with the following columns:

id;recipe_id;ingredient;amount;measurement

and the following data:

1;1;cream of coconut;1;cup
2;1;lemon juice;1;cup

Using that example page, I am working through each ingredient, but it seems like there would be a much easier way to do this.

If I were to use excel, it seems that I am not able to use each column in a spreadsheet, I would use one column and after each comma, use a new column. This seems inefficient as well.

When I do a search online, the results come up with how to import using a .csv file, not the format it needs to be in.

Thanks!


r/learnphp • • May 14 '18

How to improve the quality of your PHP code? Part 3 – End-to-end / integration testing

Thumbnail
schibsted.pl
3 Upvotes

r/learnphp • • Jan 03 '18

I got a job as a front end developer. I'm expected to transition into full stack PHP over a couple months. Also I will be the only developer at the company.

3 Upvotes

SO as the title says I got hired as the only developer for a small web agency. I am starting as a front end developer, and going forward I will be responsible for bringing myself up to a full stack PHP developer.

I need advice. Obviously I've dabbled in PHP in the past, but that really amounts to a couple courses I've done over the past year, of which I've forgotten almost everything from lack of use, and also as a result of the courses I took not having any sort of projects, and being more show and tell for language features and syntax.

What would help me is advice on courses I should take (preferably free, although once I start getting payed that will be less important), video series on youtube, books, and the like are also helpful to know about, as well as topics I should focus on more than others. I know security is going to be something very important to the job, so resources and topics on those that I should be on top of would be great.

Have to be honest, I'm very worried about the road ahead of me, it's a foggy day and I can't see 3 feet in front of my face, and that scares me. So with that in mind, any and all advice on how to proceed will be greatly appreciated.

Also on a side note, I did not apply to a full stack position and somehow negotiate myself into it having only front end skills. This company hired me as a front end developer, the job posting was for a front end developer, and it wasn't really discussed until the interview what the job would actually entail.


r/learnphp • • Jul 12 '17

What websites do you visit daily to read and learn about PHP (besides php.net)?

3 Upvotes

I'd like to know what websites do professional php developers visit daily to refresh their skills and to be up to date. It looks like there is a lot of information and websites that teach PHP and similar stuff, but it's impossible to learn from all of them, so I'd like to know the best ones that you use.


r/learnphp • • Mar 23 '17

PHP to python then back to PHP

3 Upvotes

As the title says is that even possible from a variable passed through ajax post to a php script that calls a python script then from the pyrhon script it calls a PHP script again

YES I KNOW THAT I'M OVERCOMPLICATING THIS but right now I'm on a strict time deadline and this task was given to me on short notice... and I have little experience in python though I'am willing to learn...

Right now I'm using the shell_exec command to call the python script and the os.system command to call the php script so my theory goes like this

From AJAX>PHP>Python>PHP

if it is possible can anyone give me an idea on how to do it?..

Edit: from AJAX it sends POST data (let's say the number 2) to PHP then from PHP it will send the POST data to Python here is where things get a little complicated Python will use the POST data to to find out which sensor feed it needs to listens to and the sensor data will be sent back to another PHP script to be run through calculations and said calculations will be displayed on a webpage


r/learnphp • • Dec 12 '16

code arrangement for database

3 Upvotes

When developing a database back-end in php, do most developers write generic database query functions that they feed all other queries through? I tend to have a function for almost every insert/update/select I use. But it has began to look suspiciously spaghetti-like. I'm thinking there must be a better way but the basic tutorials I've seen don't really address this.

Thanks


r/learnphp • • Sep 09 '16

Is it bad to echo JavaScript commands with PHP?

3 Upvotes

So when I do something like a $.post (Ajax) and being lazy/not the correct way to do it:

I do something like updating a JavaScript variable using

echo '<script type="text/JavaScript"> .
  'variable =' . $php_var . ';' .
  '</script>' 
;

I probably should use the return instead after .post like

.done( function(data) { 
  // use data to update client
});

I ask because while it works, I tried to do it on another page and none of the JavaScript was executing. No errors either. So in that case I had to use the return data method.


r/learnphp • • Aug 28 '16

Any good free php ebooks or book suggestions for a newbie.

3 Upvotes

As the post title states, looking for the best php ebooks that are free or cost effective. This is preferably for someone just starting out in php.

Suggestions of your favorite books that are paid will be taken too.

Thanks yall!


r/learnphp • • Aug 16 '16

I'm learning php, difference between: !filter_has_var and filter_has_var without exclamation point?

3 Upvotes

Hey guys, as the title suggests. I'm reading a book with a shit load of tutorials and explanations. Book may be outdated but i have to start somewhere i've been doing it for about 2 hours now nearly every day, on days i have off maybe a bit more

I stumbled upon !filter_has_var and filter_has_var, i fail to understand the difference, removing it from this piece of code, however, gives me an error.

function printGreeting() {
    $guess = filter_input(INPUT_POST, 'guess');
    $numpetals = filter_input(INPUT_POST, 'numPetals');
    if (!filter_has_var(INPUT_POST, 'guess')){
        print "<h3>Welcome to Petals Around the Rose</h3>!";
    } else if ($guess == $NumPetals) {
        print "<h3>You got it!</h3>";
    } else {
        print <<<HERE

<h3>from last try: </h3> <p> you guessed: <b> $guess </b> </p> <p> - and the correct answer was: <b>$numPetals</b> petals around the rose </p> HERE; } // end if } //end printGreeting

Anyone care to explain, many thanks!


r/learnphp • • Feb 22 '16

What do I do after codeacademy php course? How to I advance?

3 Upvotes

I wouldn't say i'm a bad learner, but i find it difficult to know where to advance from here. What steps do i take?

 

I've become really good at HTML and CSS. I can implement things with my eyes closed so to say, there's little I can't implement at this point. This is such a relief, to see and foremost PROVE to myself that I CAN do it. Feeling really confident now, i'm at where I wanted to be when I said I WANT to learn HTML/CSS. - I honestly didn't believe in myself too much - I want to prove to myself now that i'm capable of taking on php aswell.

 

I want to understand php and have decent knowledge. Due to work I can not invest much time into programming, however, I put an Excel schedule together, and I plan to do PHP for 2 hours a day each day. Maybe skip a day every now and then.

 

What do I do after code academy? What steps do I take?

 

I know there are guides out there, but I read a lot about security in php being of importance? How do I acquire this knowledge or do it the proper way from the start? Or is there no proper way and you just hammer at it the same way I did with html and css until one day you just "understand" it?

 

Is there some sort of setup. I'm doing code academy so far, i plan to repeat everything I did on code academy 3-4 times. Till I get a hand of it. Thing is, i'm clueless afterwards, what do I do? Where do I begin. What are some small things I can work on and gradually work my way up?

 

I was trying to search for some sort of "Class" like lessons for beginners. Where for instance it says.. Week 1 : Achieve X and X goal. Week two, achieve X and X. Not sure what to search for on google though.

 

Thank you


r/learnphp • • Nov 24 '15

Learning resources for beginner

3 Upvotes

I have finished up codecademy's PHP course and also doing WordPress theme development. But time to time I feel like my PHP knowledge is limiting me. I have sorta like prepared a list that I would follow/practice to enrich my PHP knowledge, for example I'd practice these -

  1. Contact Form with human identification and with validation.

  2. Making a simple forum

I'd appreciate if anyone helps me to expand this list. So that I can have a long list of things to practice.


r/learnphp • • Jun 10 '15

JetBrains PhpStorm - Ultimate Debugging Guide

Thumbnail
jetbrains.com
3 Upvotes

r/learnphp • • Apr 24 '15

Good modern book for novice learning OOP in PHP ?

3 Upvotes

I'm looking for an updated book, easy to read, with good examples for an introduction in OOP.


r/learnphp • • Jan 04 '15

What should I learn next?

3 Upvotes

I just finished turning an old PC into a ubuntu server. I have lamp installed along with Webmin and PHPmyAdmin. The goal is to be able to use the server to manage data from my app. I still need to learn PHP and mysql and how to properly use a database. Are there any recommendations on tutorials or what route I should take next? Also I will be going back to school in a few days, will I be fine accessing the server from the internet? Or will I have a need to access it directly?