Jump to content

imgrooot

Members
  • Posts

    383
  • Joined

  • Last visited

  • Days Won

    1

Everything posted by imgrooot

  1. Wow, none of the answers I looked at told me that it's the one receiving the AJAX call are the ones who need to add those headers. As for setting up proxy request, I'm not sure what you mean exactly but I did add a chrome extension allowing CORS to work on my browser. I turned it on and did the ajax call test again. Now I no longer get that error. So it seems to work. I would've assumed that the 3rd party api would be using CORS. Guess I will ask them about it.
  2. Basically I am submitting and retrieving data from a 3rd party's API. But every time I submit a form, it gives me this error. Access to XMLHttpRequest at 'https://3rdpartywebsite.com/api' from origin 'https://mywebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. So I have been researching and there seems to be so many different answers. I have tried adding this code to the page but still get an error. <?php // ADD THIS CODE ON THE VERY TOP OF THE PAGE I AM SUBMITTING THE FORM. header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Credentials: true"); header("Access-Control-Max-Age: 1000"); header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding"); header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE"); ?> I have also tried to add this to .htaccess file and still get the same error. Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type" Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS" I was wondering what am I doing wrong? What's the correct way of implementing CORS to my site?
  3. Good to know. Now I have another problem. How do I pass a value of a variable from another page to a json processing page? See the code below. Look at "'amount' => 1099". I would like to replace this number with my own product amount($total_amount = 20) that's listed on the index.php. If I call it directly on this server.php file, it'll get me that error again "Unexpected token < in JSON at position". //SERVER.PHP PAGE require_once '../library/stripe/init.php'; \Stripe\Stripe::setApiKey('sk_test_GPxllXVIfWnuczEjLAGh7BaX'); header('Content-Type: application/json'); # retrieve JSON from POST body $json_str = file_get_contents('php://input'); $json_obj = json_decode($json_str); try { // Create the PaymentIntent $intent = \Stripe\PaymentIntent::create([ 'amount' => 1099, 'currency' => 'usd', 'payment_method' => $json_obj->payment_method_id, # A PaymentIntent can be confirmed some time after creation, # but here we want to confirm (collect payment) immediately. 'confirm' => true, # If the payment requires any follow-up actions from the # customer, like two-factor authentication, Stripe will error # and you will need to prompt them for a new payment method. 'error_on_requires_action' => true, ]); generateResponse($intent); } catch (\Stripe\Exception\ApiErrorException $e) { // Display error on client echo json_encode(['error' => $e->getMessage()]); } function generateResponse($intent) { if ($intent->status == 'succeeded') { // Handle post-payment fulfillment echo json_encode(['success' => true]); } else { // Any other status would be unexpected, so error echo json_encode(['error' => 'Invalid PaymentIntent status']); } }
  4. Actually no "/site/server.php" won't work. I've tried it and for some reason it duplicates the site name like this "http://localhost/site/site/server.php". So it seems like the only way is with absolute urls. And yes I will have to change it when on live server.
  5. Alright so I think I may have solved the problem. Stripe's documentation sucks at explaining it properly. // REPLACE /pay WITH YOUR OWN URL THAT PROCESSES THE SERVER SIDE CODE. THAT CODE FILE HAS TO BE JSON AND NOT HTML. fetch('/pay', // THE URL HAS TO BE GLOBAL AND NOT RELATIVE. // SO FOR MY EXAMPLE, I HAD TO PUT THE FULL URL INSTEAD OF JUST THE PAGE FILE. fetch('http://localhost/site/server.php', I still have to do additional testing but so far it works. No errors.
  6. Yes but I think the reason why is because the url doesn't seem to be correct. // USING THIS URL /server.php // WILL GIVE ME THIS http://localhost/server.php //BUT I NEED THE URL TO BE LIKE THIS http://localhost/site/server.php How do do this? I've tried "../server.php" but that's all it shows. It doesn't show the main site directory.
  7. So if I do /server.php url in it's place, i still get the same error "Unexpected token < in JSON at position" error. Why would it do that if it's a correct url?
  8. I am using the Stripe API. Been at it for a day and still no luck. I keep getting this error. POST http://localhost/pay 404 (Not Found) Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position // this error is because of this line .then(handleServerResponse); It has specifically to do with this function. function handlePaymentMethodResult(result) { if (result.error) { // An error happened when collecting card details, show it in the payment form resultContainer.textContent = result.error.message; } else { // Otherwise send paymentMethod.id to your server (see Step 3) fetch('/pay', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ payment_method_id: result.paymentMethod.id }) }).then(function(result) { return result.json(); }).then(handleServerResponse); } } What is "/pay" suppose to be exactly? I assumed it was a page where i run my server process code. But it keeps giving me that error no matter what I try it. Here is my full mode. INDEX.php <?php require_once 'library/stripe/init.php'; ?> <!DOCTYPE HTML> <head> <meta charset="UTF-8"> <title>Title</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="---"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link rel="shortcut icon" href="/images/favicon.png" /> <link href="css/screen.css?v=1.1" media="screen, projection" rel="stylesheet" /> <script src="javascripts/jquery-3.2.0.min.js"></script> <script src="https://js.stripe.com/v3/"></script> <script src="javascripts/client.js" defer></script> </head> <body> <?php $total_amount = 20; ?> <div id="payment-box"> <div id="p-box-heading"> Total Amount: <span>$<?php if(empty($total_amount)){echo '0.00';}else{echo $total_amount;} ?> CAD</span> </div> <div id="p-box-body"> <form id="payment-form"> <div id="card-element"><!-- placeholder for Elements --></div> <button id="card-button">Submit Payment</button> <p id="payment-result"><!-- we'll pass the response from the server here --></p> </form> </div> </div> </body> CLIENT.js var stripe = Stripe("pk_test_ROlyXpDaTbqIvSpndWp7IdxW"); var elements = stripe.elements(); var cardElement = elements.create('card'); cardElement.mount('#card-element'); var form = document.getElementById('payment-form'); var resultContainer = document.getElementById('payment-result'); cardElement.on('change', function(event) { if (event.error) { resultContainer.textContent = event.error.message; } else { resultContainer.textContent = ''; } }); form.addEventListener('submit', function(event) { event.preventDefault(); resultContainer.textContent = ""; stripe.createPaymentMethod({ type: 'card', card: cardElement, }).then(handlePaymentMethodResult); }); function handlePaymentMethodResult(result) { if (result.error) { // An error happened when collecting card details, show it in the payment form resultContainer.textContent = result.error.message; } else { // Otherwise send paymentMethod.id to your server (see Step 3) fetch('/pay', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ payment_method_id: result.paymentMethod.id }) }).then(function(result) { return result.json(); }).then(handleServerResponse); } } function handleServerResponse(responseJson) { if (responseJson.error) { // An error happened when charging the card, show it in the payment form resultContainer.textContent = responseJson.error; } else { // Show a success message resultContainer.textContent = 'Success!'; } } SERVER.php \Stripe\Stripe::setApiKey('sk_test_GPxllXVIfWnuczEjLAGh7BaX'); header('Content-Type: application/json'); # retrieve JSON from POST body $json_str = file_get_contents('php://input'); $json_obj = json_decode($json_str); try { // Create the PaymentIntent $intent = \Stripe\PaymentIntent::create([ 'amount' => 1099, 'currency' => 'usd', 'payment_method' => $json_obj->payment_method_id, # A PaymentIntent can be confirmed some time after creation, # but here we want to confirm (collect payment) immediately. 'confirm' => true, # If the payment requires any follow-up actions from the # customer, like two-factor authentication, Stripe will error # and you will need to prompt them for a new payment method. 'error_on_requires_action' => true, ]); generateResponse($intent); } catch (\Stripe\Exception\ApiErrorException $e) { // Display error on client echo json_encode(['error' => $e->getMessage()]); } function generateResponse($intent) { if ($intent->status == 'succeeded') { // Handle post-payment fulfillment echo json_encode(['success' => true]); } else { // Any other status would be unexpected, so error echo json_encode(['error' => 'Invalid PaymentIntent status']); } }
  9. I have a "Users" table. I would like to find out the average users sign up in total. This table has a "joined date" column so I can track how many users sign up in a single day. For e.g. August 16 - 10 users August 17 - 20 users Auguest 18 - 30 users The total average of user sign ups would be 20 users based on the above results. So I am wondering how can I create this function? This is my starting query. $get_users = $db->prepare("SELECT user_id FROM users"); $get_users->execute(); $result_users = $get_users->fetchAll(PDO::FETCH_ASSOC); if(count($result_users) > 0) { foreach($result_users as $row) { $user_id = $row['user_id']; } }
  10. 1. What I meant was that originally I had a single browse.php page and included cities as parameters. For e.g. /browse.php?city=new-york. So I changed it to having each city as a separate page like /browse.php/new-york.php. So I am asking if I should leave it as is or change it back? 2. I am using IDs to retrieve the results from the database. If a city parameter ID is ''123", I can grab it form the url and search all the records in that city from the database. Isn't that how it's suppose to be done? If I use both, it would look like this. /browse.php?city=new-york&id=123. I don't know how to do pretty urls so I can't make it like your example.
  11. Really? That's how I had it originally but now I changed it to have a separate page for each city. Guess I'll change it back. Second question, is it okay to have an ID of a city and category as oppose to the name in the URL? Like this. /browse.php?city=123&category=456 Having an ID would make it a lot easier to retrieve data.
  12. This is more of an SEO question. I have a site with couple hundred categories within each city. I was wondering what the best approach is to do them? www.mysite.com/browse/apples?city=new-york www.mysite.com/browse/new-york?category=apples Which one is the better way to do it for seo purposes? If it's the first method, that would mean I would have to create couple hundred pages for those categories yes?
  13. I just realized what the issue was. The votes in the table have a different user_id than what I am currently logged in as. So naturally it will not return any results. Here's a new code based on your suggestion. Works fine. $count_votes = $db->prepare("SELECT SUM(votes) FROM entries WHERE user_id = :user_id"); $count_votes->bindParam(':user_id', $user_id); $count_votes->execute(); $get_votes = $count_votes->fetchColumn();
  14. I have a table with "votes" column. I basically want to retrieve the sum of all the votes columns associated with a user. This is the full code. It gives me "NULL" output. $count_votes = $db->prepare("SELECT SUM(votes) as total FROM entries WHERE user_id = :user_id"); $count_votes->bindParam(':user_id', $user_id); $count_votes->execute(); $t_votes = $count_votes->fetchColumn(); $get_votes = $t_votes['total']; echo $get_votes; But if I remove the user_id bind paramter, it gives me the results. But I need that parameter to show which user has how many votes. $count_votes = $db->prepare("SELECT SUM(votes) as total FROM entries"); $count_votes->execute(); $t_votes = $count_votes->fetchColumn(); $get_votes = $t_votes['total']; echo $get_votes; What am I doing wrong?
  15. Got it. Here is the updated form. It seems to work fine. // Message ID being an ID of individual message rows retrived from the DB. $message_id if(isset($_POST['submit']) AND $_POST['message-id'] == $message_id) { $post_message = trim($_POST['message']); $errors = array(); $db->beginTransaction(); if(empty($post_message)) { $errors[] = 'The message field can not be empty!'; } else { // ADD CODE HERE } if(empty($errors)) { $db->commit(); echo 'success'; } else { $db->rollBack(); } } <form action="" method="post"> <fieldset> <textarea name="message" maxlength="10000" placeholder="What would you like to say?"></textarea> </fieldset> <fieldset> <input type="hidden" name="message-id" value="<?php echo $message_id; ?>" /> <input type="submit" name="submit" value="Submit" /> </fieldset> </form>
  16. I am creating a user inbox system. I am retrieving all the unread messages. Each message row contains a "reply" form. So say I have 10 messages showing on a single page. That's 10 forms. What I would like to know is how can I submit any one of the 10 forms and not have it affect the remaining 9 forms? Here is the basic code. if(isset($_POST['submit'])) { $post_message = trim($_POST['message']); $errors = array(); $db->beginTransaction(); if(empty($post_message)) { $errors[] = 'The message field can not be empty!'; } if(empty($errors)) { $db->commit(); echo 'success'; } else { $db->rollBack(); } } <form action="" method="post"> <fieldset> <textarea name="message" maxlength="10000" placeholder="What would you like to say?"></textarea> </fieldset> <fieldset> <input type="submit" name="submit" value="Submit" /> </fieldset> </form>
  17. That makes sense. I reversed the order and it seems to work fine now. Yes project_id is an auto-increment primary key field. I honestly never had issues with this method before so I kept using it. But I actually do have "date_created" with each record. So I can "ORDER BY date_created" if need be.
  18. I have a basic query where I am retrieving project records. I basically want to show the records from newest to oldest, but I also want to show the Featured projects first. Each Featured project is marked by "1" in the mysql table column. If it's not featured, then it's marked "0". $find_records = $db->prepare("SELECT * FROM projects ORDER BY project_id DESC, featured DESC LIMIT 10"); $find_records->execute(); $result_records = $find_records->fetchAll(PDO::FETCH_ASSOC); if(count($result_records) > 0) { foreach($result_records as $row) { } } The issue with above query is that the ORDER BY works only for the first component(project_id) and ignores the second component(featured). Do you see what's wrong with it?
  19. This is my first time working with ADF. I've been researching and found this link. http://adfxml.info/adf_spec.pdf Apprantly ADF uses XML to format data. So say I have a car dealer that wants to receive leads in ADF format like this example. How do I go on about emailing this as an attachment? If I am using a PHPmailer, it requires a physical file to attach. So how do I save the bottom xml info as an attachment? Which file extension do I use? <?ADF VERSION "1.0"?> <?XML VERSION “1.0”?> <adf> <prospect> <requestdate>2000-03-30T15:30:20-08:00</requestdate> <vehicle> <year>1999</year> <make>Chevrolet</make> <model>Blazer</model> </vehicle> <customer> <contact> <name part="full">John Doe</name> <phone>393-999-3922</phone> </contact> </customer> <vendor> <contact> <name part="full">Acura of Bellevue</name> </contact> </vendor> </prospect> </adf>
  20. I am back and I have solved the issue. I just had to move up the $exif code before the orientation switch statement. It rotates the jpeg images now. There is a slight problem however. I'm not sure if it's normal or not. But if I upload a png or gif image, I get this error Warning: exif_read_data(phpA107.tmp): File not supported in 1. It uploads the png and gif images fine. 2. It doesn't compress gif and png images. Only jpegs are compressed. 3. Do I need to apply orientation code to the gif and png images in the function or only to jpeg? Having said that here's the new code. function compressImage($source_url, $destination_url, $quality) { //$quality :: 0 - 100 $info = getimagesize($source_url); $exif = exif_read_data($source_url); if(isset($exif['Orientation'])) { $orientation = $exif['Orientation']; } if($destination_url == NULL || $destination_url == "" ) { $destination_url = $source_url; } else if($info['mime'] == 'image/jpeg' || $info['mime'] == 'image/jpg') { $image = imagecreatefromjpeg($source_url); if(isset($orientation)) { switch($orientation) { case 8: $image = imagerotate($image, 90, 0); break; case 3: $image = imagerotate($image, 180, 0); break; case 6: $image = imagerotate($image, -90, 0); break; } } //save file //ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75). imagejpeg($image, $destination_url, $quality); //Free up memory imagedestroy($image); } else if($info['mime'] == 'image/gif') { $image = imagecreatefromgif($source_url); //save file //ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75). imagegif($image, $destination_url, $quality); } else if($info['mime'] == 'image/png') { $image = imagecreatefrompng($source_url); imageAlphaBlending($image, true); imageSaveAlpha($image, true); /* chang to png quality */ $png_quality = 9 - round(($quality / 100 ) * 9 ); imagePng($image, $destination_url, $png_quality);//Compression level: from 0 (no compression) to 9(full compression). //Free up memory imagedestroy($image); } else { return FALSE; } return $destination_url; }
  21. Alright after taking some time off, here is the reworked function. Its' combining compression and orientation. It no longer gives me any errors. But it's still not rotating the image when uploaded. Can you spot what's wrong with the code? function compressImage($source_url, $destination_url, $quality) { //$quality :: 0 - 100 $info = getimagesize($source_url); if($destination_url == NULL || $destination_url == "" ) { $destination_url = $source_url; } else if($info['mime'] == 'image/jpeg' || $info['mime'] == 'image/jpg') { $image = imagecreatefromjpeg($source_url); if(isset($orientation)) { switch($orientation) { case 8: $image = imagerotate($image, 90, 0); break; case 3: $image = imagerotate($image, 180, 0); break; case 6: $image = imagerotate($image, -90, 0); break; } } $exif = exif_read_data($source_url); if(isset($exif['Orientation'])) { $orientation = $exif['Orientation']; } //save file //ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75). imagejpeg($image, $destination_url, $quality); //Free up memory imagedestroy($image); } else if($info['mime'] == 'image/png') { $image = imagecreatefrompng($source_url); imageAlphaBlending($image, true); imageSaveAlpha($image, true); if(isset($orientation)) { switch($orientation) { case 8: $image = imagerotate($image, 90, 0); break; case 3: $image = imagerotate($image, 180, 0); break; case 6: $image = imagerotate($image, -90, 0); break; } } $exif = exif_read_data($source_url); if(isset($exif['Orientation'])) { $orientation = $exif['Orientation']; } /* chang to png quality */ $png_quality = 9 - round(($quality / 100 ) * 9 ); imagePng($image, $destination_url, $png_quality);//Compression level: from 0 (no compression) to 9(full compression). //Free up memory imagedestroy($image); } else { return FALSE; } return $destination_url; }
  22. I am trying but I keep getting same errors. Here is the combined function of compression and rotation. function compress_image($source_url, $destination_url, $quality) { $info = getimagesize($source_url); if($info['mime'] == 'image/jpeg' || $info['mime'] == 'image/jpg') { $image = imagecreatefromjpeg($source_url); } else if ($info['mime'] == 'image/gif') { $image = imagecreatefromgif($source_url); } else if ($info['mime'] == 'image/png') { $image = imagecreatefrompng($source_url); } else { $image = null; } $new_image = imagecreatefromstring(file_get_contents($image)); $exif = exif_read_data($image); if(!empty($exif['Orientation'])) { switch($exif['Orientation']) { case 8: $new_image = imagerotate($new_image,90,0); break; case 3: $new_image = imagerotate($new_image,180,0); break; case 6: $new_image = imagerotate($new_image,-90,0); break; } } imagejpeg($new_image, $destination_url, $quality); return $destination_url; }
  23. Here's what I have tried. It's still not working. I get the following errors. Warning: getimagesize() expects parameter 1 to be string, resource given in Warning: rename(XfdpPCBxns.jpg,../members/images/7/projects/8/): The system cannot find the file specified. (code: 2) in // Also if I var dump the $oriented_image variable in the code below, I get the following output. resource(92) of type (gd) // ORIGINAL CODE WITHOUT THE ORIENTATION $target_dir = '../members/images/'.$global_user_id.'/projects/'.$url_project_id.'/'; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); $source_file = $_FILES["fileToUpload"]["tmp_name"]; $random_name = generateRandomString(10); $new_image = $random_name . '.' . $imageFileType; $resized_image = compressImage($source_file, $new_image, 50); $new_file_path = $target_dir . $resized_image; $check = getimagesize($source_file); if(rename($new_image, $new_file_path)) { echo 'success'; } // NEW CODE WITH THE ORIENTATION FUNCTION $target_dir = '../members/images/'.$global_user_id.'/projects/'.$url_project_id.'/'; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); $source_file = $_FILES["fileToUpload"]["tmp_name"]; $oriented_image = getOrientedImage($source_file); $random_name = generateRandomString(10); $new_image = $random_name . '.' . $imageFileType; $resized_image = compressImage($oriented_image, $new_image, 50); $new_file_path = $target_dir . $resized_image; $check = getimagesize($oriented_image); if(rename($new_image, $new_file_path)) { echo 'success'; }
  24. So whether I am uploading an image through my iphone or sending that image to my computer and uploading it from the computer, it has the same effect. If I upload that image, it'll orient the image in landscape mode. Having said that, I found a function that can fix the orient issue. The problem is I don't know the proper way to integrate it into the image upload script. I have tried several different ways but they all give me errors. Can you show me where exactly I should use this function? // IMAGE ORIENTATION function getOrientedImage($imagePath) { $image = imagecreatefromstring(file_get_contents($imagePath)); $exif = exif_read_data($imagePath); if(!empty($exif['Orientation'])) { switch($exif['Orientation']) { case 8: $image = imagerotate($image,90,0); swapHW(); break; case 3: $image = imagerotate($image,180,0); break; case 6: $image = imagerotate($image,-90,0); swapHW(); break; } } return $image; } // IMAGE UPLOAD SCRIPT if(isset($_FILES['fileToUpload']) AND !empty($_FILES['fileToUpload']["name"])) { if(is_uploaded_file($_FILES['fileToUpload']["tmp_name"])) { $target_dir = '../members/images/'.$global_user_id.'/projects/'.$url_project_id.'/'; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); $source_file = $_FILES["fileToUpload"]["tmp_name"]; $random_name = generateRandomString(10); $new_image = $random_name . '.' . $imageFileType; $resized_image = compressImage($source_file, $new_image, 50); $new_file_path = $target_dir . $resized_image; if(!is_dir($target_dir)){ mkdir($target_dir, 0775, true); } $uploadOk = 1; // Check if image file is a actual image or fake image $check = getimagesize($source_file); if($check !== false) { // echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { $errors[] = 'File is not an image!'; $uploadOk = 0; } // Check if file already exists if (file_exists($target_file)) { $errors[] = 'Sorry, file already exists!'; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 5000000) { $errors[] = 'Sorry, your file size is bigger than 5mb!'; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "JPG" && $imageFileType != "PNG" && $imageFileType != "JPEG" && $imageFileType != "GIF") { $errors[] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed!'; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if($uploadOk == 0) { $errors[] = 'Sorry, your file was not uploaded!'; // if everything is ok, try to upload file } else { if(rename($new_image, $new_file_path)) { echo 'success'; } else { $errors[] = 'Sorry, there was an error uploading your file!'; } } } else { $errors[] = 'You must upload an image!'; } }
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.